1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.692.4.12 2009/08/14 08:37:53 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)=@_;
485: my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Community - for which you wish to add/modify a user role');
486: my $id_functions = &javascript_index_functions();
487: my $output = '
488: <script type="text/javascript" language="JavaScript">
489: // <![CDATA[
490: var stdeditbrowser;'."\n";
491:
492: $output .= <<"ENDSTDBRW";
493: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
494: var url = '/adm/pickcourse?';
495: var domainfilter = getDomainFromSelectbox(formname,udom);
496: if (domainfilter != null) {
497: if (domainfilter != '') {
498: url += 'domainfilter='+domainfilter+'&';
499: }
500: }
501: url += 'form=' + formname + '&cnumelement='+uname+
502: '&cdomelement='+udom+
503: '&cnameelement='+desc;
504: if (extra_element !=null && extra_element != '') {
505: if (formname == 'rolechoice' || formname == 'studentform') {
506: url += '&roleelement='+extra_element;
507: if (domainfilter == null || domainfilter == '') {
508: url += '&domainfilter='+extra_element;
509: }
510: }
511: else {
512: if (formname == 'portform') {
513: url += '&setroles='+extra_element;
514: }
515: }
516: }
517: if (formname == 'ccrs') {
518: var ownername = document.forms[formid].ccuname.value;
519: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
520: url += '&cloner='+ownername+':'+ownerdom;
521: }
522: if (multflag !=null && multflag != '') {
523: url += '&multiple='+multflag;
524: }
525: if (crstype == 'Course/Community') {
526: if (formname == 'cu') {
527: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
528: if (crstype == "") {
529: alert("$crs_or_grp_alert");
530: return;
531: }
532: }
533: }
534: if (crstype !=null && crstype != '') {
535: url += '&type='+crstype;
536: }
537: var title = 'Course_Browser';
538: var options = 'scrollbars=1,resizable=1,menubar=0';
539: options += ',width=700,height=600';
540: stdeditbrowser = open(url,title,options,'1');
541: stdeditbrowser.focus();
542: }
543: $id_functions
544: ENDSTDBRW
545: if ($sec_element ne '') {
546: $output .= &setsec_javascript($sec_element,$formname);
547: }
548: $output .= '
549: // ]]>
550: </script>';
551: return $output;
552: }
553:
554: sub javascript_index_functions {
555: return <<"ENDJS";
556:
557: function getFormIdByName(formname) {
558: for (var i=0;i<document.forms.length;i++) {
559: if (document.forms[i].name == formname) {
560: return i;
561: }
562: }
563: return -1;
564: }
565:
566: function getIndexByName(formid,item) {
567: for (var i=0;i<document.forms[formid].elements.length;i++) {
568: if (document.forms[formid].elements[i].name == item) {
569: return i;
570: }
571: }
572: return -1;
573: }
574:
575: function getDomainFromSelectbox(formname,udom) {
576: var userdom;
577: var formid = getFormIdByName(formname);
578: if (formid > -1) {
579: var domid = getIndexByName(formid,udom);
580: if (domid > -1) {
581: if (document.forms[formid].elements[domid].type == 'select-one') {
582: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
583: }
584: if (document.forms[formid].elements[domid].type == 'hidden') {
585: userdom=document.forms[formid].elements[domid].value;
586: }
587: }
588: }
589: return userdom;
590: }
591:
592: ENDJS
593:
594: }
595:
596: sub userbrowser_javascript {
597: my $id_functions = &javascript_index_functions();
598: return <<"ENDUSERBRW";
599:
600: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom) {
601: var url = '/adm/pickuser?';
602: var userdom = getDomainFromSelectbox(formname,udom);
603: if (userdom != null) {
604: if (userdom != '') {
605: url += 'srchdom='+userdom+'&';
606: }
607: }
608: url += 'form=' + formname + '&unameelement='+uname+
609: '&udomelement='+udom+
610: '&ulastelement='+ulast+
611: '&ufirstelement='+ufirst+
612: '&uemailelement='+uemail+
613: '&hideudomelement='+hideudom+
614: '&coursedom='+crsdom;
615: var title = 'User_Browser';
616: var options = 'scrollbars=1,resizable=1,menubar=0';
617: options += ',width=700,height=600';
618: var stdeditbrowser = open(url,title,options,'1');
619: stdeditbrowser.focus();
620: }
621:
622: function fix_domain (formname,udom,origdom) {
623: var formid = getFormIdByName(formname);
624: if (formid > -1) {
625: var domid = getIndexByName(formid,udom);
626: var hidedomid = getIndexByName(formid,origdom);
627: if (hidedomid > -1) {
628: var fixeddom = document.forms[formid].elements[hidedomid].value;
629: if (domid > -1) {
630: var slct = document.forms[formid].elements[domid];
631: if (slct.type == 'select-one') {
632: var i;
633: for (i=0;i<slct.length;i++) {
634: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
635: }
636: }
637: if (slct.type == 'hidden') {
638: slct.value = fixeddom;
639: }
640: }
641: }
642: }
643: return;
644: }
645:
646: $id_functions
647: ENDUSERBRW
648: }
649:
650:
651: sub setsec_javascript {
652: my ($sec_element,$formname) = @_;
653: my $setsections = qq|
654: function setSect(sectionlist) {
655: var sectionsArray = new Array();
656: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
657: sectionsArray = sectionlist.split(",");
658: }
659: var numSections = sectionsArray.length;
660: document.$formname.$sec_element.length = 0;
661: if (numSections == 0) {
662: document.$formname.$sec_element.multiple=false;
663: document.$formname.$sec_element.size=1;
664: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
665: } else {
666: if (numSections == 1) {
667: document.$formname.$sec_element.multiple=false;
668: document.$formname.$sec_element.size=1;
669: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
670: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
671: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
672: } else {
673: for (var i=0; i<numSections; i++) {
674: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
675: }
676: document.$formname.$sec_element.multiple=true
677: if (numSections < 3) {
678: document.$formname.$sec_element.size=numSections;
679: } else {
680: document.$formname.$sec_element.size=3;
681: }
682: document.$formname.$sec_element.options[0].selected = false
683: }
684: }
685: }
686: |;
687: return $setsections;
688: }
689:
690:
691: sub selectcourse_link {
692: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
693: my $linktext = &mt('Select Course');
694: if ($selecttype eq 'Community') {
695: $linktext = &mt('Select Community');
696: }
697: return '<span class="LC_nobreak">'
698: ."<a href='"
699: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
700: .'","'.$udomele.'","'.$desc.'","'.$extra_element
701: .'","'.$multflag.'","'.$selecttype.'");'
702: ."'>".$linktext.'</a>'
703: .'</span>';
704: }
705:
706: sub selectauthor_link {
707: my ($form,$udom)=@_;
708: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
709: &mt('Select Author').'</a>';
710: }
711:
712: sub selectuser_link {
713: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
714: $coursedom,$linktext) = @_;
715: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
716: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom'".
717: ');">'.$linktext.'</a>';
718: }
719:
720: sub check_uncheck_jscript {
721: my $jscript = <<"ENDSCRT";
722: function checkAll(field) {
723: if (field.length > 0) {
724: for (i = 0; i < field.length; i++) {
725: field[i].checked = true ;
726: }
727: } else {
728: field.checked = true
729: }
730: }
731:
732: function uncheckAll(field) {
733: if (field.length > 0) {
734: for (i = 0; i < field.length; i++) {
735: field[i].checked = false ;
736: }
737: } else {
738: field.checked = false ;
739: }
740: }
741: ENDSCRT
742: return $jscript;
743: }
744:
745: sub select_timezone {
746: my ($name,$selected,$onchange,$includeempty)=@_;
747: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
748: if ($includeempty) {
749: $output .= '<option value=""';
750: if (($selected eq '') || ($selected eq 'local')) {
751: $output .= ' selected="selected" ';
752: }
753: $output .= '> </option>';
754: }
755: my @timezones = DateTime::TimeZone->all_names;
756: foreach my $tzone (@timezones) {
757: $output.= '<option value="'.$tzone.'"';
758: if ($tzone eq $selected) {
759: $output.=' selected="selected"';
760: }
761: $output.=">$tzone</option>\n";
762: }
763: $output.="</select>";
764: return $output;
765: }
766:
767: sub select_datelocale {
768: my ($name,$selected,$onchange,$includeempty)=@_;
769: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
770: if ($includeempty) {
771: $output .= '<option value=""';
772: if ($selected eq '') {
773: $output .= ' selected="selected" ';
774: }
775: $output .= '> </option>';
776: }
777: my (@possibles,%locale_names);
778: my @locales = DateTime::Locale::Catalog::Locales;
779: foreach my $locale (@locales) {
780: if (ref($locale) eq 'HASH') {
781: my $id = $locale->{'id'};
782: if ($id ne '') {
783: my $en_terr = $locale->{'en_territory'};
784: my $native_terr = $locale->{'native_territory'};
785: my @languages = &Apache::lonlocal::preferred_languages();
786: if (grep(/^en$/,@languages) || !@languages) {
787: if ($en_terr ne '') {
788: $locale_names{$id} = '('.$en_terr.')';
789: } elsif ($native_terr ne '') {
790: $locale_names{$id} = $native_terr;
791: }
792: } else {
793: if ($native_terr ne '') {
794: $locale_names{$id} = $native_terr.' ';
795: } elsif ($en_terr ne '') {
796: $locale_names{$id} = '('.$en_terr.')';
797: }
798: }
799: push (@possibles,$id);
800: }
801: }
802: }
803: foreach my $item (sort(@possibles)) {
804: $output.= '<option value="'.$item.'"';
805: if ($item eq $selected) {
806: $output.=' selected="selected"';
807: }
808: $output.=">$item";
809: if ($locale_names{$item} ne '') {
810: $output.=" $locale_names{$item}</option>\n";
811: }
812: $output.="</option>\n";
813: }
814: $output.="</select>";
815: return $output;
816: }
817:
818: sub select_language {
819: my ($name,$selected,$includeempty) = @_;
820: my %langchoices;
821: if ($includeempty) {
822: %langchoices = ('' => 'No language preference');
823: }
824: foreach my $id (&languageids()) {
825: my $code = &supportedlanguagecode($id);
826: if ($code) {
827: $langchoices{$code} = &plainlanguagedescription($id);
828: }
829: }
830: return &select_form($selected,$name,%langchoices);
831: }
832:
833: =pod
834:
835: =item * &linked_select_forms(...)
836:
837: linked_select_forms returns a string containing a <script></script> block
838: and html for two <select> menus. The select menus will be linked in that
839: changing the value of the first menu will result in new values being placed
840: in the second menu. The values in the select menu will appear in alphabetical
841: order unless a defined order is provided.
842:
843: linked_select_forms takes the following ordered inputs:
844:
845: =over 4
846:
847: =item * $formname, the name of the <form> tag
848:
849: =item * $middletext, the text which appears between the <select> tags
850:
851: =item * $firstdefault, the default value for the first menu
852:
853: =item * $firstselectname, the name of the first <select> tag
854:
855: =item * $secondselectname, the name of the second <select> tag
856:
857: =item * $hashref, a reference to a hash containing the data for the menus.
858:
859: =item * $menuorder, the order of values in the first menu
860:
861: =back
862:
863: Below is an example of such a hash. Only the 'text', 'default', and
864: 'select2' keys must appear as stated. keys(%menu) are the possible
865: values for the first select menu. The text that coincides with the
866: first menu value is given in $menu{$choice1}->{'text'}. The values
867: and text for the second menu are given in the hash pointed to by
868: $menu{$choice1}->{'select2'}.
869:
870: my %menu = ( A1 => { text =>"Choice A1" ,
871: default => "B3",
872: select2 => {
873: B1 => "Choice B1",
874: B2 => "Choice B2",
875: B3 => "Choice B3",
876: B4 => "Choice B4"
877: },
878: order => ['B4','B3','B1','B2'],
879: },
880: A2 => { text =>"Choice A2" ,
881: default => "C2",
882: select2 => {
883: C1 => "Choice C1",
884: C2 => "Choice C2",
885: C3 => "Choice C3"
886: },
887: order => ['C2','C1','C3'],
888: },
889: A3 => { text =>"Choice A3" ,
890: default => "D6",
891: select2 => {
892: D1 => "Choice D1",
893: D2 => "Choice D2",
894: D3 => "Choice D3",
895: D4 => "Choice D4",
896: D5 => "Choice D5",
897: D6 => "Choice D6",
898: D7 => "Choice D7"
899: },
900: order => ['D4','D3','D2','D1','D7','D6','D5'],
901: }
902: );
903:
904: =cut
905:
906: sub linked_select_forms {
907: my ($formname,
908: $middletext,
909: $firstdefault,
910: $firstselectname,
911: $secondselectname,
912: $hashref,
913: $menuorder,
914: ) = @_;
915: my $second = "document.$formname.$secondselectname";
916: my $first = "document.$formname.$firstselectname";
917: # output the javascript to do the changing
918: my $result = '';
919: $result.='<script type="text/javascript" language="JavaScript">'."\n";
920: $result.="// <![CDATA[\n";
921: $result.="var select2data = new Object();\n";
922: $" = '","';
923: my $debug = '';
924: foreach my $s1 (sort(keys(%$hashref))) {
925: $result.="select2data.d_$s1 = new Object();\n";
926: $result.="select2data.d_$s1.def = new String('".
927: $hashref->{$s1}->{'default'}."');\n";
928: $result.="select2data.d_$s1.values = new Array(";
929: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
930: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
931: @s2values = @{$hashref->{$s1}->{'order'}};
932: }
933: $result.="\"@s2values\");\n";
934: $result.="select2data.d_$s1.texts = new Array(";
935: my @s2texts;
936: foreach my $value (@s2values) {
937: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
938: }
939: $result.="\"@s2texts\");\n";
940: }
941: $"=' ';
942: $result.= <<"END";
943:
944: function select1_changed() {
945: // Determine new choice
946: var newvalue = "d_" + $first.value;
947: // update select2
948: var values = select2data[newvalue].values;
949: var texts = select2data[newvalue].texts;
950: var select2def = select2data[newvalue].def;
951: var i;
952: // out with the old
953: for (i = 0; i < $second.options.length; i++) {
954: $second.options[i] = null;
955: }
956: // in with the nuclear
957: for (i=0;i<values.length; i++) {
958: $second.options[i] = new Option(values[i]);
959: $second.options[i].value = values[i];
960: $second.options[i].text = texts[i];
961: if (values[i] == select2def) {
962: $second.options[i].selected = true;
963: }
964: }
965: }
966: // ]]>
967: </script>
968: END
969: # output the initial values for the selection lists
970: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
971: my @order = sort(keys(%{$hashref}));
972: if (ref($menuorder) eq 'ARRAY') {
973: @order = @{$menuorder};
974: }
975: foreach my $value (@order) {
976: $result.=" <option value=\"$value\" ";
977: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
978: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
979: }
980: $result .= "</select>\n";
981: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
982: $result .= $middletext;
983: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
984: my $seconddefault = $hashref->{$firstdefault}->{'default'};
985:
986: my @secondorder = sort(keys(%select2));
987: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
988: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
989: }
990: foreach my $value (@secondorder) {
991: $result.=" <option value=\"$value\" ";
992: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
993: $result.=">".&mt($select2{$value})."</option>\n";
994: }
995: $result .= "</select>\n";
996: # return $debug;
997: return $result;
998: } # end of sub linked_select_forms {
999:
1000: =pod
1001:
1002: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
1003:
1004: Returns a string corresponding to an HTML link to the given help
1005: $topic, where $topic corresponds to the name of a .tex file in
1006: /home/httpd/html/adm/help/tex, with underscores replaced by
1007: spaces.
1008:
1009: $text will optionally be linked to the same topic, allowing you to
1010: link text in addition to the graphic. If you do not want to link
1011: text, but wish to specify one of the later parameters, pass an
1012: empty string.
1013:
1014: $stayOnPage is a value that will be interpreted as a boolean. If true,
1015: the link will not open a new window. If false, the link will open
1016: a new window using Javascript. (Default is false.)
1017:
1018: $width and $height are optional numerical parameters that will
1019: override the width and height of the popped up window, which may
1020: be useful for certain help topics with big pictures included.
1021:
1022: =cut
1023:
1024: sub help_open_topic {
1025: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1026: $text = "" if (not defined $text);
1027: $stayOnPage = 0 if (not defined $stayOnPage);
1028: if ($env{'browser.interface'} eq 'textual') {
1029: $stayOnPage=1;
1030: }
1031: $width = 350 if (not defined $width);
1032: $height = 400 if (not defined $height);
1033: my $filename = $topic;
1034: $filename =~ s/ /_/g;
1035:
1036: my $template = "";
1037: my $link;
1038:
1039: $topic=~s/\W/\_/g;
1040:
1041: if (!$stayOnPage) {
1042: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1043: } else {
1044: $link = "/adm/help/${filename}.hlp";
1045: }
1046:
1047: # Add the text
1048: if ($text ne "") {
1049: $template .=
1050: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1051: "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1052: }
1053:
1054: # Add the graphic
1055: my $title = &mt('Online Help');
1056: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1057: $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
1058: '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
1059: '" title="'.$title.'" /></a>';
1060: if ($text ne '') {
1061: $template.='</span></td></tr></table>';
1062: }
1063: return $template;
1064:
1065: }
1066:
1067: # This is a quicky function for Latex cheatsheet editing, since it
1068: # appears in at least four places
1069: sub helpLatexCheatsheet {
1070: my ($topic,$text,$not_author) = @_;
1071: my $out;
1072: my $addOther = '';
1073: if ($topic) {
1074: $addOther = &Apache::loncommon::help_open_topic($topic,$text,
1075: undef, undef, 600) .
1076: '</td><td>';
1077: }
1078: $out = '<table><tr><td>'.
1079: $addOther .
1080: &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
1081: undef,undef,600).
1082: '</td><td>'.
1083: &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
1084: undef,undef,600).
1085: '</td>';
1086: unless ($not_author) {
1087: $out .= '<td>'.
1088: &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
1089: undef,undef,600).
1090: '</td>';
1091: }
1092: $out .= '</tr></table>';
1093: return $out;
1094: }
1095:
1096: sub general_help {
1097: my $helptopic='Student_Intro';
1098: if ($env{'request.role'}=~/^(ca|au)/) {
1099: $helptopic='Authoring_Intro';
1100: } elsif ($env{'request.role'}=~/^cc/) {
1101: $helptopic='Course_Coordination_Intro';
1102: } elsif ($env{'request.role'}=~/^dc/) {
1103: $helptopic='Domain_Coordination_Intro';
1104: }
1105: return $helptopic;
1106: }
1107:
1108: sub update_help_link {
1109: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1110: my $origurl = $ENV{'REQUEST_URI'};
1111: $origurl=~s|^/~|/priv/|;
1112: my $timestamp = time;
1113: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1114: $$datum = &escape($$datum);
1115: }
1116:
1117: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1118: my $output .= <<"ENDOUTPUT";
1119: <script type="text/javascript">
1120: // <![CDATA[
1121: banner_link = '$banner_link';
1122: // ]]>
1123: </script>
1124: ENDOUTPUT
1125: return $output;
1126: }
1127:
1128: # now just updates the help link and generates a blue icon
1129: sub help_open_menu {
1130: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1131: = @_;
1132: $stayOnPage = 0 if (not defined $stayOnPage);
1133: # only use pop-up help (stayOnPage == 0)
1134: # if environment.remote is on (using remote control UI)
1135: if ($env{'browser.interface'} eq 'textual' ||
1136: $env{'environment.remote'} eq 'off' ) {
1137: $stayOnPage=1;
1138: }
1139: my $output;
1140: if ($component_help) {
1141: if (!$text) {
1142: $output=&help_open_topic($component_help,undef,$stayOnPage,
1143: $width,$height);
1144: } else {
1145: my $help_text;
1146: $help_text=&unescape($topic);
1147: $output='<table><tr><td>'.
1148: &help_open_topic($component_help,$help_text,$stayOnPage,
1149: $width,$height).'</td></tr></table>';
1150: }
1151: }
1152: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1153: return $output.$banner_link;
1154: }
1155:
1156: sub top_nav_help {
1157: my ($text) = @_;
1158: $text = &mt($text);
1159: my $stay_on_page =
1160: ($env{'browser.interface'} eq 'textual' ||
1161: $env{'environment.remote'} eq 'off' );
1162: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1163: : "javascript:helpMenu('open')";
1164: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1165:
1166: my $title = &mt('Get help');
1167:
1168: return <<"END";
1169: $banner_link
1170: <a href="$link" title="$title">$text</a>
1171: END
1172: }
1173:
1174: sub help_menu_js {
1175: my ($text) = @_;
1176:
1177: my $stayOnPage =
1178: ($env{'browser.interface'} eq 'textual' ||
1179: $env{'environment.remote'} eq 'off' );
1180:
1181: my $width = 620;
1182: my $height = 600;
1183: my $helptopic=&general_help();
1184: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1185: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1186: my $start_page =
1187: &Apache::loncommon::start_page('Help Menu', undef,
1188: {'frameset' => 1,
1189: 'js_ready' => 1,
1190: 'add_entries' => {
1191: 'border' => '0',
1192: 'rows' => "110,*",},});
1193: my $end_page =
1194: &Apache::loncommon::end_page({'frameset' => 1,
1195: 'js_ready' => 1,});
1196:
1197: my $template .= <<"ENDTEMPLATE";
1198: <script type="text/javascript">
1199: // <![CDATA[
1200: // <!-- BEGIN LON-CAPA Internal
1201: var banner_link = '';
1202: function helpMenu(target) {
1203: var caller = this;
1204: if (target == 'open') {
1205: var newWindow = null;
1206: try {
1207: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1208: }
1209: catch(error) {
1210: writeHelp(caller);
1211: return;
1212: }
1213: if (newWindow) {
1214: caller = newWindow;
1215: }
1216: }
1217: writeHelp(caller);
1218: return;
1219: }
1220: function writeHelp(caller) {
1221: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1222: caller.document.close()
1223: caller.focus()
1224: }
1225: // END LON-CAPA Internal -->
1226: // ]]>
1227: </script>
1228: ENDTEMPLATE
1229: return $template;
1230: }
1231:
1232: sub help_open_bug {
1233: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1234: unless ($env{'user.adv'}) { return ''; }
1235: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1236: $text = "" if (not defined $text);
1237: $stayOnPage = 0 if (not defined $stayOnPage);
1238: if ($env{'browser.interface'} eq 'textual' ||
1239: $env{'environment.remote'} eq 'off' ) {
1240: $stayOnPage=1;
1241: }
1242: $width = 600 if (not defined $width);
1243: $height = 600 if (not defined $height);
1244:
1245: $topic=~s/\W+/\+/g;
1246: my $link='';
1247: my $template='';
1248: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1249: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1250: if (!$stayOnPage)
1251: {
1252: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1253: }
1254: else
1255: {
1256: $link = $url;
1257: }
1258: # Add the text
1259: if ($text ne "")
1260: {
1261: $template .=
1262: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1263: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1264: }
1265:
1266: # Add the graphic
1267: my $title = &mt('Report a Bug');
1268: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1269: $template .= <<"ENDTEMPLATE";
1270: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1271: ENDTEMPLATE
1272: if ($text ne '') { $template.='</td></tr></table>' };
1273: return $template;
1274:
1275: }
1276:
1277: sub help_open_faq {
1278: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1279: unless ($env{'user.adv'}) { return ''; }
1280: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1281: $text = "" if (not defined $text);
1282: $stayOnPage = 0 if (not defined $stayOnPage);
1283: if ($env{'browser.interface'} eq 'textual' ||
1284: $env{'environment.remote'} eq 'off' ) {
1285: $stayOnPage=1;
1286: }
1287: $width = 350 if (not defined $width);
1288: $height = 400 if (not defined $height);
1289:
1290: $topic=~s/\W+/\+/g;
1291: my $link='';
1292: my $template='';
1293: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1294: if (!$stayOnPage)
1295: {
1296: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1297: }
1298: else
1299: {
1300: $link = $url;
1301: }
1302:
1303: # Add the text
1304: if ($text ne "")
1305: {
1306: $template .=
1307: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1308: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1309: }
1310:
1311: # Add the graphic
1312: my $title = &mt('View the FAQ');
1313: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1314: $template .= <<"ENDTEMPLATE";
1315: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1316: ENDTEMPLATE
1317: if ($text ne '') { $template.='</td></tr></table>' };
1318: return $template;
1319:
1320: }
1321:
1322: ###############################################################
1323: ###############################################################
1324:
1325: =pod
1326:
1327: =item * &change_content_javascript():
1328:
1329: This and the next function allow you to create small sections of an
1330: otherwise static HTML page that you can update on the fly with
1331: Javascript, even in Netscape 4.
1332:
1333: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1334: must be written to the HTML page once. It will prove the Javascript
1335: function "change(name, content)". Calling the change function with the
1336: name of the section
1337: you want to update, matching the name passed to C<changable_area>, and
1338: the new content you want to put in there, will put the content into
1339: that area.
1340:
1341: B<Note>: Netscape 4 only reserves enough space for the changable area
1342: to contain room for the original contents. You need to "make space"
1343: for whatever changes you wish to make, and be B<sure> to check your
1344: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1345: it's adequate for updating a one-line status display, but little more.
1346: This script will set the space to 100% width, so you only need to
1347: worry about height in Netscape 4.
1348:
1349: Modern browsers are much less limiting, and if you can commit to the
1350: user not using Netscape 4, this feature may be used freely with
1351: pretty much any HTML.
1352:
1353: =cut
1354:
1355: sub change_content_javascript {
1356: # If we're on Netscape 4, we need to use Layer-based code
1357: if ($env{'browser.type'} eq 'netscape' &&
1358: $env{'browser.version'} =~ /^4\./) {
1359: return (<<NETSCAPE4);
1360: function change(name, content) {
1361: doc = document.layers[name+"___escape"].layers[0].document;
1362: doc.open();
1363: doc.write(content);
1364: doc.close();
1365: }
1366: NETSCAPE4
1367: } else {
1368: # Otherwise, we need to use semi-standards-compliant code
1369: # (technically, "innerHTML" isn't standard but the equivalent
1370: # is really scary, and every useful browser supports it
1371: return (<<DOMBASED);
1372: function change(name, content) {
1373: element = document.getElementById(name);
1374: element.innerHTML = content;
1375: }
1376: DOMBASED
1377: }
1378: }
1379:
1380: =pod
1381:
1382: =item * &changable_area($name,$origContent):
1383:
1384: This provides a "changable area" that can be modified on the fly via
1385: the Javascript code provided in C<change_content_javascript>. $name is
1386: the name you will use to reference the area later; do not repeat the
1387: same name on a given HTML page more then once. $origContent is what
1388: the area will originally contain, which can be left blank.
1389:
1390: =cut
1391:
1392: sub changable_area {
1393: my ($name, $origContent) = @_;
1394:
1395: if ($env{'browser.type'} eq 'netscape' &&
1396: $env{'browser.version'} =~ /^4\./) {
1397: # If this is netscape 4, we need to use the Layer tag
1398: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1399: } else {
1400: return "<span id='$name'>$origContent</span>";
1401: }
1402: }
1403:
1404: =pod
1405:
1406: =item * &viewport_geometry_js
1407:
1408: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1409:
1410: =cut
1411:
1412:
1413: sub viewport_geometry_js {
1414: return <<"GEOMETRY";
1415: var Geometry = {};
1416: function init_geometry() {
1417: if (Geometry.init) { return };
1418: Geometry.init=1;
1419: if (window.innerHeight) {
1420: Geometry.getViewportHeight = function() { return window.innerHeight; };
1421: Geometry.getViewportWidth = function() { return window.innerWidth; };
1422: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1423: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1424: }
1425: else if (document.documentElement && document.documentElement.clientHeight) {
1426: Geometry.getViewportHeight =
1427: function() { return document.documentElement.clientHeight; };
1428: Geometry.getViewportWidth =
1429: function() { return document.documentElement.clientWidth; };
1430:
1431: Geometry.getHorizontalScroll =
1432: function() { return document.documentElement.scrollLeft; };
1433: Geometry.getVerticalScroll =
1434: function() { return document.documentElement.scrollTop; };
1435: }
1436: else if (document.body.clientHeight) {
1437: Geometry.getViewportHeight =
1438: function() { return document.body.clientHeight; };
1439: Geometry.getViewportWidth =
1440: function() { return document.body.clientWidth; };
1441: Geometry.getHorizontalScroll =
1442: function() { return document.body.scrollLeft; };
1443: Geometry.getVerticalScroll =
1444: function() { return document.body.scrollTop; };
1445: }
1446: }
1447:
1448: GEOMETRY
1449: }
1450:
1451: =pod
1452:
1453: =item * &viewport_size_js()
1454:
1455: 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.
1456:
1457: =cut
1458:
1459: sub viewport_size_js {
1460: my $geometry = &viewport_geometry_js();
1461: return <<"DIMS";
1462:
1463: $geometry
1464:
1465: function getViewportDims(width,height) {
1466: init_geometry();
1467: width.value = Geometry.getViewportWidth();
1468: height.value = Geometry.getViewportHeight();
1469: return;
1470: }
1471:
1472: DIMS
1473: }
1474:
1475: =pod
1476:
1477: =item * &resize_textarea_js()
1478:
1479: emits the needed javascript to resize a textarea to be as big as possible
1480:
1481: creates a function resize_textrea that takes two IDs first should be
1482: the id of the element to resize, second should be the id of a div that
1483: surrounds everything that comes after the textarea, this routine needs
1484: to be attached to the <body> for the onload and onresize events.
1485:
1486: =back
1487:
1488: =cut
1489:
1490: sub resize_textarea_js {
1491: my $geometry = &viewport_geometry_js();
1492: return <<"RESIZE";
1493: <script type="text/javascript">
1494: // <![CDATA[
1495: $geometry
1496:
1497: function getX(element) {
1498: var x = 0;
1499: while (element) {
1500: x += element.offsetLeft;
1501: element = element.offsetParent;
1502: }
1503: return x;
1504: }
1505: function getY(element) {
1506: var y = 0;
1507: while (element) {
1508: y += element.offsetTop;
1509: element = element.offsetParent;
1510: }
1511: return y;
1512: }
1513:
1514:
1515: function resize_textarea(textarea_id,bottom_id) {
1516: init_geometry();
1517: var textarea = document.getElementById(textarea_id);
1518: //alert(textarea);
1519:
1520: var textarea_top = getY(textarea);
1521: var textarea_height = textarea.offsetHeight;
1522: var bottom = document.getElementById(bottom_id);
1523: var bottom_top = getY(bottom);
1524: var bottom_height = bottom.offsetHeight;
1525: var window_height = Geometry.getViewportHeight();
1526: var fudge = 23;
1527: var new_height = window_height-fudge-textarea_top-bottom_height;
1528: if (new_height < 300) {
1529: new_height = 300;
1530: }
1531: textarea.style.height=new_height+'px';
1532: }
1533: // ]]>
1534: </script>
1535: RESIZE
1536:
1537: }
1538:
1539: =pod
1540:
1541: =head1 Excel and CSV file utility routines
1542:
1543: =over 4
1544:
1545: =cut
1546:
1547: ###############################################################
1548: ###############################################################
1549:
1550: =pod
1551:
1552: =item * &csv_translate($text)
1553:
1554: Translate $text to allow it to be output as a 'comma separated values'
1555: format.
1556:
1557: =cut
1558:
1559: ###############################################################
1560: ###############################################################
1561: sub csv_translate {
1562: my $text = shift;
1563: $text =~ s/\"/\"\"/g;
1564: $text =~ s/\n/ /g;
1565: return $text;
1566: }
1567:
1568: ###############################################################
1569: ###############################################################
1570:
1571: =pod
1572:
1573: =item * &define_excel_formats()
1574:
1575: Define some commonly used Excel cell formats.
1576:
1577: Currently supported formats:
1578:
1579: =over 4
1580:
1581: =item header
1582:
1583: =item bold
1584:
1585: =item h1
1586:
1587: =item h2
1588:
1589: =item h3
1590:
1591: =item h4
1592:
1593: =item i
1594:
1595: =item date
1596:
1597: =back
1598:
1599: Inputs: $workbook
1600:
1601: Returns: $format, a hash reference.
1602:
1603: =cut
1604:
1605: ###############################################################
1606: ###############################################################
1607: sub define_excel_formats {
1608: my ($workbook) = @_;
1609: my $format;
1610: $format->{'header'} = $workbook->add_format(bold => 1,
1611: bottom => 1,
1612: align => 'center');
1613: $format->{'bold'} = $workbook->add_format(bold=>1);
1614: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1615: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1616: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1617: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1618: $format->{'i'} = $workbook->add_format(italic=>1);
1619: $format->{'date'} = $workbook->add_format(num_format=>
1620: 'mm/dd/yyyy hh:mm:ss');
1621: return $format;
1622: }
1623:
1624: ###############################################################
1625: ###############################################################
1626:
1627: =pod
1628:
1629: =item * &create_workbook()
1630:
1631: Create an Excel worksheet. If it fails, output message on the
1632: request object and return undefs.
1633:
1634: Inputs: Apache request object
1635:
1636: Returns (undef) on failure,
1637: Excel worksheet object, scalar with filename, and formats
1638: from &Apache::loncommon::define_excel_formats on success
1639:
1640: =cut
1641:
1642: ###############################################################
1643: ###############################################################
1644: sub create_workbook {
1645: my ($r) = @_;
1646: #
1647: # Create the excel spreadsheet
1648: my $filename = '/prtspool/'.
1649: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1650: time.'_'.rand(1000000000).'.xls';
1651: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1652: if (! defined($workbook)) {
1653: $r->log_error("Error creating excel spreadsheet $filename: $!");
1654: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1655: "This error has been logged. ".
1656: "Please alert your LON-CAPA administrator").
1657: '</p>');
1658: return (undef);
1659: }
1660: #
1661: $workbook->set_tempdir('/home/httpd/perl/tmp');
1662: #
1663: my $format = &Apache::loncommon::define_excel_formats($workbook);
1664: return ($workbook,$filename,$format);
1665: }
1666:
1667: ###############################################################
1668: ###############################################################
1669:
1670: =pod
1671:
1672: =item * &create_text_file()
1673:
1674: Create a file to write to and eventually make available to the user.
1675: If file creation fails, outputs an error message on the request object and
1676: return undefs.
1677:
1678: Inputs: Apache request object, and file suffix
1679:
1680: Returns (undef) on failure,
1681: Filehandle and filename on success.
1682:
1683: =cut
1684:
1685: ###############################################################
1686: ###############################################################
1687: sub create_text_file {
1688: my ($r,$suffix) = @_;
1689: if (! defined($suffix)) { $suffix = 'txt'; };
1690: my $fh;
1691: my $filename = '/prtspool/'.
1692: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1693: time.'_'.rand(1000000000).'.'.$suffix;
1694: $fh = Apache::File->new('>/home/httpd'.$filename);
1695: if (! defined($fh)) {
1696: $r->log_error("Couldn't open $filename for output $!");
1697: $r->print(&mt('Problems occurred in creating the output file. '
1698: .'This error has been logged. '
1699: .'Please alert your LON-CAPA administrator.'));
1700: }
1701: return ($fh,$filename)
1702: }
1703:
1704:
1705: =pod
1706:
1707: =back
1708:
1709: =cut
1710:
1711: ###############################################################
1712: ## Home server <option> list generating code ##
1713: ###############################################################
1714:
1715: # ------------------------------------------
1716:
1717: sub domain_select {
1718: my ($name,$value,$multiple)=@_;
1719: my %domains=map {
1720: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1721: } &Apache::lonnet::all_domains();
1722: if ($multiple) {
1723: $domains{''}=&mt('Any domain');
1724: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1725: return &multiple_select_form($name,$value,4,\%domains);
1726: } else {
1727: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1728: return &select_form($name,$value,%domains);
1729: }
1730: }
1731:
1732: #-------------------------------------------
1733:
1734: =pod
1735:
1736: =head1 Routines for form select boxes
1737:
1738: =over 4
1739:
1740: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1741:
1742: Returns a string containing a <select> element int multiple mode
1743:
1744:
1745: Args:
1746: $name - name of the <select> element
1747: $value - scalar or array ref of values that should already be selected
1748: $size - number of rows long the select element is
1749: $hash - the elements should be 'option' => 'shown text'
1750: (shown text should already have been &mt())
1751: $order - (optional) array ref of the order to show the elements in
1752:
1753: =cut
1754:
1755: #-------------------------------------------
1756: sub multiple_select_form {
1757: my ($name,$value,$size,$hash,$order)=@_;
1758: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1759: my $output='';
1760: if (! defined($size)) {
1761: $size = 4;
1762: if (scalar(keys(%$hash))<4) {
1763: $size = scalar(keys(%$hash));
1764: }
1765: }
1766: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1767: my @order;
1768: if (ref($order) eq 'ARRAY') {
1769: @order = @{$order};
1770: } else {
1771: @order = sort(keys(%$hash));
1772: }
1773: if (exists($$hash{'select_form_order'})) {
1774: @order = @{$$hash{'select_form_order'}};
1775: }
1776:
1777: foreach my $key (@order) {
1778: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1779: $output.='selected="selected" ' if ($selected{$key});
1780: $output.='>'.$hash->{$key}."</option>\n";
1781: }
1782: $output.="</select>\n";
1783: return $output;
1784: }
1785:
1786: #-------------------------------------------
1787:
1788: =pod
1789:
1790: =item * &select_form($defdom,$name,%hash)
1791:
1792: Returns a string containing a <select name='$name' size='1'> form to
1793: allow a user to select options from a hash option_name => displayed text.
1794: See lonrights.pm for an example invocation and use.
1795:
1796: =cut
1797:
1798: #-------------------------------------------
1799: sub select_form {
1800: my ($def,$name,%hash) = @_;
1801: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1802: my @keys;
1803: if (exists($hash{'select_form_order'})) {
1804: @keys=@{$hash{'select_form_order'}};
1805: } else {
1806: @keys=sort(keys(%hash));
1807: }
1808: foreach my $key (@keys) {
1809: $selectform.=
1810: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1811: ($key eq $def ? 'selected="selected" ' : '').
1812: ">".&mt($hash{$key})."</option>\n";
1813: }
1814: $selectform.="</select>";
1815: return $selectform;
1816: }
1817:
1818: # For display filters
1819:
1820: sub display_filter {
1821: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1822: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1823: return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1824: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1825: (&mt('all'),10,20,50,100,1000,10000))).
1826: '</label></span> <span class="LC_nobreak">'.
1827: &mt('Filter [_1]',
1828: &select_form($env{'form.displayfilter'},
1829: 'displayfilter',
1830: ('currentfolder' => 'Current folder/page',
1831: 'containing' => 'Containing phrase',
1832: 'none' => 'None'))).
1833: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1834: }
1835:
1836: sub gradeleveldescription {
1837: my $gradelevel=shift;
1838: my %gradelevels=(0 => 'Not specified',
1839: 1 => 'Grade 1',
1840: 2 => 'Grade 2',
1841: 3 => 'Grade 3',
1842: 4 => 'Grade 4',
1843: 5 => 'Grade 5',
1844: 6 => 'Grade 6',
1845: 7 => 'Grade 7',
1846: 8 => 'Grade 8',
1847: 9 => 'Grade 9',
1848: 10 => 'Grade 10',
1849: 11 => 'Grade 11',
1850: 12 => 'Grade 12',
1851: 13 => 'Grade 13',
1852: 14 => '100 Level',
1853: 15 => '200 Level',
1854: 16 => '300 Level',
1855: 17 => '400 Level',
1856: 18 => 'Graduate Level');
1857: return &mt($gradelevels{$gradelevel});
1858: }
1859:
1860: sub select_level_form {
1861: my ($deflevel,$name)=@_;
1862: unless ($deflevel) { $deflevel=0; }
1863: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1864: for (my $i=0; $i<=18; $i++) {
1865: $selectform.="<option value=\"$i\" ".
1866: ($i==$deflevel ? 'selected="selected" ' : '').
1867: ">".&gradeleveldescription($i)."</option>\n";
1868: }
1869: $selectform.="</select>";
1870: return $selectform;
1871: }
1872:
1873: #-------------------------------------------
1874:
1875: =pod
1876:
1877: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
1878:
1879: Returns a string containing a <select name='$name' size='1'> form to
1880: allow a user to select the domain to preform an operation in.
1881: See loncreateuser.pm for an example invocation and use.
1882:
1883: If the $includeempty flag is set, it also includes an empty choice ("no domain
1884: selected");
1885:
1886: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1887:
1888: 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.
1889:
1890: =cut
1891:
1892: #-------------------------------------------
1893: sub select_dom_form {
1894: my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
1895: if ($onchange) {
1896: $onchange = ' onchange="'.$onchange.'"';
1897: }
1898: my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1899: if ($includeempty) { @domains=('',@domains); }
1900: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1901: foreach my $dom (@domains) {
1902: $selectdomain.="<option value=\"$dom\" ".
1903: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1904: if ($showdomdesc) {
1905: if ($dom ne '') {
1906: my $domdesc = &Apache::lonnet::domain($dom,'description');
1907: if ($domdesc ne '') {
1908: $selectdomain .= ' ('.$domdesc.')';
1909: }
1910: }
1911: }
1912: $selectdomain .= "</option>\n";
1913: }
1914: $selectdomain.="</select>";
1915: return $selectdomain;
1916: }
1917:
1918: #-------------------------------------------
1919:
1920: =pod
1921:
1922: =item * &home_server_form_item($domain,$name,$defaultflag)
1923:
1924: input: 4 arguments (two required, two optional) -
1925: $domain - domain of new user
1926: $name - name of form element
1927: $default - Value of 'default' causes a default item to be first
1928: option, and selected by default.
1929: $hide - Value of 'hide' causes hiding of the name of the server,
1930: if 1 server found, or default, if 0 found.
1931: output: returns 2 items:
1932: (a) form element which contains either:
1933: (i) <select name="$name">
1934: <option value="$hostid1">$hostid $servers{$hostid}</option>
1935: <option value="$hostid2">$hostid $servers{$hostid}</option>
1936: </select>
1937: form item if there are multiple library servers in $domain, or
1938: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
1939: if there is only one library server in $domain.
1940:
1941: (b) number of library servers found.
1942:
1943: See loncreateuser.pm for example of use.
1944:
1945: =cut
1946:
1947: #-------------------------------------------
1948: sub home_server_form_item {
1949: my ($domain,$name,$default,$hide) = @_;
1950: my %servers = &Apache::lonnet::get_servers($domain,'library');
1951: my $result;
1952: my $numlib = keys(%servers);
1953: if ($numlib > 1) {
1954: $result .= '<select name="'.$name.'" />'."\n";
1955: if ($default) {
1956: $result .= '<option value="default" selected="selected">'.&mt('default').
1957: '</option>'."\n";
1958: }
1959: foreach my $hostid (sort(keys(%servers))) {
1960: $result.= '<option value="'.$hostid.'">'.
1961: $hostid.' '.$servers{$hostid}."</option>\n";
1962: }
1963: $result .= '</select>'."\n";
1964: } elsif ($numlib == 1) {
1965: my $hostid;
1966: foreach my $item (keys(%servers)) {
1967: $hostid = $item;
1968: }
1969: $result .= '<input type="hidden" name="'.$name.'" value="'.
1970: $hostid.'" />';
1971: if (!$hide) {
1972: $result .= $hostid.' '.$servers{$hostid};
1973: }
1974: $result .= "\n";
1975: } elsif ($default) {
1976: $result .= '<input type="hidden" name="'.$name.
1977: '" value="default" />';
1978: if (!$hide) {
1979: $result .= &mt('default');
1980: }
1981: $result .= "\n";
1982: }
1983: return ($result,$numlib);
1984: }
1985:
1986: =pod
1987:
1988: =back
1989:
1990: =cut
1991:
1992: ###############################################################
1993: ## Decoding User Agent ##
1994: ###############################################################
1995:
1996: =pod
1997:
1998: =head1 Decoding the User Agent
1999:
2000: =over 4
2001:
2002: =item * &decode_user_agent()
2003:
2004: Inputs: $r
2005:
2006: Outputs:
2007:
2008: =over 4
2009:
2010: =item * $httpbrowser
2011:
2012: =item * $clientbrowser
2013:
2014: =item * $clientversion
2015:
2016: =item * $clientmathml
2017:
2018: =item * $clientunicode
2019:
2020: =item * $clientos
2021:
2022: =back
2023:
2024: =back
2025:
2026: =cut
2027:
2028: ###############################################################
2029: ###############################################################
2030: sub decode_user_agent {
2031: my ($r)=@_;
2032: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2033: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2034: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2035: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2036: my $clientbrowser='unknown';
2037: my $clientversion='0';
2038: my $clientmathml='';
2039: my $clientunicode='0';
2040: for (my $i=0;$i<=$#browsertype;$i++) {
2041: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2042: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2043: $clientbrowser=$bname;
2044: $httpbrowser=~/$vreg/i;
2045: $clientversion=$1;
2046: $clientmathml=($clientversion>=$minv);
2047: $clientunicode=($clientversion>=$univ);
2048: }
2049: }
2050: my $clientos='unknown';
2051: if (($httpbrowser=~/linux/i) ||
2052: ($httpbrowser=~/unix/i) ||
2053: ($httpbrowser=~/ux/i) ||
2054: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2055: if (($httpbrowser=~/vax/i) ||
2056: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2057: if ($httpbrowser=~/next/i) { $clientos='next'; }
2058: if (($httpbrowser=~/mac/i) ||
2059: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2060: if ($httpbrowser=~/win/i) { $clientos='win'; }
2061: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2062: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2063: $clientunicode,$clientos,);
2064: }
2065:
2066: ###############################################################
2067: ## Authentication changing form generation subroutines ##
2068: ###############################################################
2069: ##
2070: ## All of the authform_xxxxxxx subroutines take their inputs in a
2071: ## hash, and have reasonable default values.
2072: ##
2073: ## formname = the name given in the <form> tag.
2074: #-------------------------------------------
2075:
2076: =pod
2077:
2078: =head1 Authentication Routines
2079:
2080: =over 4
2081:
2082: =item * &authform_xxxxxx()
2083:
2084: The authform_xxxxxx subroutines provide javascript and html forms which
2085: handle some of the conveniences required for authentication forms.
2086: This is not an optimal method, but it works.
2087:
2088: =over 4
2089:
2090: =item * authform_header
2091:
2092: =item * authform_authorwarning
2093:
2094: =item * authform_nochange
2095:
2096: =item * authform_kerberos
2097:
2098: =item * authform_internal
2099:
2100: =item * authform_filesystem
2101:
2102: =back
2103:
2104: See loncreateuser.pm for invocation and use examples.
2105:
2106: =cut
2107:
2108: #-------------------------------------------
2109: sub authform_header{
2110: my %in = (
2111: formname => 'cu',
2112: kerb_def_dom => '',
2113: @_,
2114: );
2115: $in{'formname'} = 'document.' . $in{'formname'};
2116: my $result='';
2117:
2118: #---------------------------------------------- Code for upper case translation
2119: my $Javascript_toUpperCase;
2120: unless ($in{kerb_def_dom}) {
2121: $Javascript_toUpperCase =<<"END";
2122: switch (choice) {
2123: case 'krb': currentform.elements[choicearg].value =
2124: currentform.elements[choicearg].value.toUpperCase();
2125: break;
2126: default:
2127: }
2128: END
2129: } else {
2130: $Javascript_toUpperCase = "";
2131: }
2132:
2133: my $radioval = "'nochange'";
2134: if (defined($in{'curr_authtype'})) {
2135: if ($in{'curr_authtype'} ne '') {
2136: $radioval = "'".$in{'curr_authtype'}."arg'";
2137: }
2138: }
2139: my $argfield = 'null';
2140: if (defined($in{'mode'})) {
2141: if ($in{'mode'} eq 'modifycourse') {
2142: if (defined($in{'curr_autharg'})) {
2143: if ($in{'curr_autharg'} ne '') {
2144: $argfield = "'$in{'curr_autharg'}'";
2145: }
2146: }
2147: }
2148: }
2149:
2150: $result.=<<"END";
2151: var current = new Object();
2152: current.radiovalue = $radioval;
2153: current.argfield = $argfield;
2154:
2155: function changed_radio(choice,currentform) {
2156: var choicearg = choice + 'arg';
2157: // If a radio button in changed, we need to change the argfield
2158: if (current.radiovalue != choice) {
2159: current.radiovalue = choice;
2160: if (current.argfield != null) {
2161: currentform.elements[current.argfield].value = '';
2162: }
2163: if (choice == 'nochange') {
2164: current.argfield = null;
2165: } else {
2166: current.argfield = choicearg;
2167: switch(choice) {
2168: case 'krb':
2169: currentform.elements[current.argfield].value =
2170: "$in{'kerb_def_dom'}";
2171: break;
2172: default:
2173: break;
2174: }
2175: }
2176: }
2177: return;
2178: }
2179:
2180: function changed_text(choice,currentform) {
2181: var choicearg = choice + 'arg';
2182: if (currentform.elements[choicearg].value !='') {
2183: $Javascript_toUpperCase
2184: // clear old field
2185: if ((current.argfield != choicearg) && (current.argfield != null)) {
2186: currentform.elements[current.argfield].value = '';
2187: }
2188: current.argfield = choicearg;
2189: }
2190: set_auth_radio_buttons(choice,currentform);
2191: return;
2192: }
2193:
2194: function set_auth_radio_buttons(newvalue,currentform) {
2195: var i=0;
2196: while (i < currentform.login.length) {
2197: if (currentform.login[i].value == newvalue) { break; }
2198: i++;
2199: }
2200: if (i == currentform.login.length) {
2201: return;
2202: }
2203: current.radiovalue = newvalue;
2204: currentform.login[i].checked = true;
2205: return;
2206: }
2207: END
2208: return $result;
2209: }
2210:
2211: sub authform_authorwarning{
2212: my $result='';
2213: $result='<i>'.
2214: &mt('As a general rule, only authors or co-authors should be '.
2215: 'filesystem authenticated '.
2216: '(which allows access to the server filesystem).')."</i>\n";
2217: return $result;
2218: }
2219:
2220: sub authform_nochange{
2221: my %in = (
2222: formname => 'document.cu',
2223: kerb_def_dom => 'MSU.EDU',
2224: @_,
2225: );
2226: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2227: my $result;
2228: if (keys(%can_assign) == 0) {
2229: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2230: } else {
2231: $result = '<label>'.&mt('[_1] Do not change login data',
2232: '<input type="radio" name="login" value="nochange" '.
2233: 'checked="checked" onclick="'.
2234: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2235: '</label>';
2236: }
2237: return $result;
2238: }
2239:
2240: sub authform_kerberos {
2241: my %in = (
2242: formname => 'document.cu',
2243: kerb_def_dom => 'MSU.EDU',
2244: kerb_def_auth => 'krb4',
2245: @_,
2246: );
2247: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2248: $autharg,$jscall);
2249: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2250: if ($in{'kerb_def_auth'} eq 'krb5') {
2251: $check5 = ' checked="checked"';
2252: } else {
2253: $check4 = ' checked="checked"';
2254: }
2255: $krbarg = $in{'kerb_def_dom'};
2256: if (defined($in{'curr_authtype'})) {
2257: if ($in{'curr_authtype'} eq 'krb') {
2258: $krbcheck = ' checked="checked"';
2259: if (defined($in{'mode'})) {
2260: if ($in{'mode'} eq 'modifyuser') {
2261: $krbcheck = '';
2262: }
2263: }
2264: if (defined($in{'curr_kerb_ver'})) {
2265: if ($in{'curr_krb_ver'} eq '5') {
2266: $check5 = ' checked="checked"';
2267: $check4 = '';
2268: } else {
2269: $check4 = ' checked="checked"';
2270: $check5 = '';
2271: }
2272: }
2273: if (defined($in{'curr_autharg'})) {
2274: $krbarg = $in{'curr_autharg'};
2275: }
2276: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2277: if (defined($in{'curr_autharg'})) {
2278: $result =
2279: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2280: $in{'curr_autharg'},$krbver);
2281: } else {
2282: $result =
2283: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2284: }
2285: return $result;
2286: }
2287: }
2288: } else {
2289: if ($authnum == 1) {
2290: $authtype = '<input type="hidden" name="login" value="krb" />';
2291: }
2292: }
2293: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2294: return;
2295: } elsif ($authtype eq '') {
2296: if (defined($in{'mode'})) {
2297: if ($in{'mode'} eq 'modifycourse') {
2298: if ($authnum == 1) {
2299: $authtype = '<input type="hidden" name="login" value="krb" />';
2300: }
2301: }
2302: }
2303: }
2304: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2305: if ($authtype eq '') {
2306: $authtype = '<input type="radio" name="login" value="krb" '.
2307: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2308: $krbcheck.' />';
2309: }
2310: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2311: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2312: $in{'curr_authtype'} eq 'krb5') ||
2313: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2314: $in{'curr_authtype'} eq 'krb4')) {
2315: $result .= &mt
2316: ('[_1] Kerberos authenticated with domain [_2] '.
2317: '[_3] Version 4 [_4] Version 5 [_5]',
2318: '<label>'.$authtype,
2319: '</label><input type="text" size="10" name="krbarg" '.
2320: 'value="'.$krbarg.'" '.
2321: 'onchange="'.$jscall.'" />',
2322: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2323: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2324: '</label>');
2325: } elsif ($can_assign{'krb4'}) {
2326: $result .= &mt
2327: ('[_1] Kerberos authenticated with domain [_2] '.
2328: '[_3] Version 4 [_4]',
2329: '<label>'.$authtype,
2330: '</label><input type="text" size="10" name="krbarg" '.
2331: 'value="'.$krbarg.'" '.
2332: 'onchange="'.$jscall.'" />',
2333: '<label><input type="hidden" name="krbver" value="4" />',
2334: '</label>');
2335: } elsif ($can_assign{'krb5'}) {
2336: $result .= &mt
2337: ('[_1] Kerberos authenticated with domain [_2] '.
2338: '[_3] Version 5 [_4]',
2339: '<label>'.$authtype,
2340: '</label><input type="text" size="10" name="krbarg" '.
2341: 'value="'.$krbarg.'" '.
2342: 'onchange="'.$jscall.'" />',
2343: '<label><input type="hidden" name="krbver" value="5" />',
2344: '</label>');
2345: }
2346: return $result;
2347: }
2348:
2349: sub authform_internal{
2350: my %in = (
2351: formname => 'document.cu',
2352: kerb_def_dom => 'MSU.EDU',
2353: @_,
2354: );
2355: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2356: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2357: if (defined($in{'curr_authtype'})) {
2358: if ($in{'curr_authtype'} eq 'int') {
2359: if ($can_assign{'int'}) {
2360: $intcheck = 'checked="checked" ';
2361: if (defined($in{'mode'})) {
2362: if ($in{'mode'} eq 'modifyuser') {
2363: $intcheck = '';
2364: }
2365: }
2366: if (defined($in{'curr_autharg'})) {
2367: $intarg = $in{'curr_autharg'};
2368: }
2369: } else {
2370: $result = &mt('Currently internally authenticated.');
2371: return $result;
2372: }
2373: }
2374: } else {
2375: if ($authnum == 1) {
2376: $authtype = '<input type="hidden" name="login" value="int" />';
2377: }
2378: }
2379: if (!$can_assign{'int'}) {
2380: return;
2381: } elsif ($authtype eq '') {
2382: if (defined($in{'mode'})) {
2383: if ($in{'mode'} eq 'modifycourse') {
2384: if ($authnum == 1) {
2385: $authtype = '<input type="hidden" name="login" value="int" />';
2386: }
2387: }
2388: }
2389: }
2390: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2391: if ($authtype eq '') {
2392: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2393: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2394: }
2395: $autharg = '<input type="password" size="10" name="intarg" value="'.
2396: $intarg.'" onchange="'.$jscall.'" />';
2397: $result = &mt
2398: ('[_1] Internally authenticated (with initial password [_2])',
2399: '<label>'.$authtype,'</label>'.$autharg);
2400: $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>';
2401: return $result;
2402: }
2403:
2404: sub authform_local{
2405: my %in = (
2406: formname => 'document.cu',
2407: kerb_def_dom => 'MSU.EDU',
2408: @_,
2409: );
2410: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2411: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2412: if (defined($in{'curr_authtype'})) {
2413: if ($in{'curr_authtype'} eq 'loc') {
2414: if ($can_assign{'loc'}) {
2415: $loccheck = 'checked="checked" ';
2416: if (defined($in{'mode'})) {
2417: if ($in{'mode'} eq 'modifyuser') {
2418: $loccheck = '';
2419: }
2420: }
2421: if (defined($in{'curr_autharg'})) {
2422: $locarg = $in{'curr_autharg'};
2423: }
2424: } else {
2425: $result = &mt('Currently using local (institutional) authentication.');
2426: return $result;
2427: }
2428: }
2429: } else {
2430: if ($authnum == 1) {
2431: $authtype = '<input type="hidden" name="login" value="loc" />';
2432: }
2433: }
2434: if (!$can_assign{'loc'}) {
2435: return;
2436: } elsif ($authtype eq '') {
2437: if (defined($in{'mode'})) {
2438: if ($in{'mode'} eq 'modifycourse') {
2439: if ($authnum == 1) {
2440: $authtype = '<input type="hidden" name="login" value="loc" />';
2441: }
2442: }
2443: }
2444: }
2445: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2446: if ($authtype eq '') {
2447: $authtype = '<input type="radio" name="login" value="loc" '.
2448: $loccheck.' onchange="'.$jscall.'" onclick="'.
2449: $jscall.'" />';
2450: }
2451: $autharg = '<input type="text" size="10" name="locarg" value="'.
2452: $locarg.'" onchange="'.$jscall.'" />';
2453: $result = &mt('[_1] Local Authentication with argument [_2]',
2454: '<label>'.$authtype,'</label>'.$autharg);
2455: return $result;
2456: }
2457:
2458: sub authform_filesystem{
2459: my %in = (
2460: formname => 'document.cu',
2461: kerb_def_dom => 'MSU.EDU',
2462: @_,
2463: );
2464: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2465: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2466: if (defined($in{'curr_authtype'})) {
2467: if ($in{'curr_authtype'} eq 'fsys') {
2468: if ($can_assign{'fsys'}) {
2469: $fsyscheck = 'checked="checked" ';
2470: if (defined($in{'mode'})) {
2471: if ($in{'mode'} eq 'modifyuser') {
2472: $fsyscheck = '';
2473: }
2474: }
2475: } else {
2476: $result = &mt('Currently Filesystem Authenticated.');
2477: return $result;
2478: }
2479: }
2480: } else {
2481: if ($authnum == 1) {
2482: $authtype = '<input type="hidden" name="login" value="fsys" />';
2483: }
2484: }
2485: if (!$can_assign{'fsys'}) {
2486: return;
2487: } elsif ($authtype eq '') {
2488: if (defined($in{'mode'})) {
2489: if ($in{'mode'} eq 'modifycourse') {
2490: if ($authnum == 1) {
2491: $authtype = '<input type="hidden" name="login" value="fsys" />';
2492: }
2493: }
2494: }
2495: }
2496: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2497: if ($authtype eq '') {
2498: $authtype = '<input type="radio" name="login" value="fsys" '.
2499: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2500: $jscall.'" />';
2501: }
2502: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2503: ' onchange="'.$jscall.'" />';
2504: $result = &mt
2505: ('[_1] Filesystem Authenticated (with initial password [_2])',
2506: '<label><input type="radio" name="login" value="fsys" '.
2507: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2508: '</label><input type="password" size="10" name="fsysarg" value="" '.
2509: 'onchange="'.$jscall.'" />');
2510: return $result;
2511: }
2512:
2513: sub get_assignable_auth {
2514: my ($dom) = @_;
2515: if ($dom eq '') {
2516: $dom = $env{'request.role.domain'};
2517: }
2518: my %can_assign = (
2519: krb4 => 1,
2520: krb5 => 1,
2521: int => 1,
2522: loc => 1,
2523: );
2524: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2525: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2526: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2527: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2528: my $context;
2529: if ($env{'request.role'} =~ /^au/) {
2530: $context = 'author';
2531: } elsif ($env{'request.role'} =~ /^dc/) {
2532: $context = 'domain';
2533: } elsif ($env{'request.course.id'}) {
2534: $context = 'course';
2535: }
2536: if ($context) {
2537: if (ref($authhash->{$context}) eq 'HASH') {
2538: %can_assign = %{$authhash->{$context}};
2539: }
2540: }
2541: }
2542: }
2543: my $authnum = 0;
2544: foreach my $key (keys(%can_assign)) {
2545: if ($can_assign{$key}) {
2546: $authnum ++;
2547: }
2548: }
2549: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2550: $authnum --;
2551: }
2552: return ($authnum,%can_assign);
2553: }
2554:
2555: ###############################################################
2556: ## Get Kerberos Defaults for Domain ##
2557: ###############################################################
2558: ##
2559: ## Returns default kerberos version and an associated argument
2560: ## as listed in file domain.tab. If not listed, provides
2561: ## appropriate default domain and kerberos version.
2562: ##
2563: #-------------------------------------------
2564:
2565: =pod
2566:
2567: =item * &get_kerberos_defaults()
2568:
2569: get_kerberos_defaults($target_domain) returns the default kerberos
2570: version and domain. If not found, it defaults to version 4 and the
2571: domain of the server.
2572:
2573: =over 4
2574:
2575: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2576:
2577: =back
2578:
2579: =back
2580:
2581: =cut
2582:
2583: #-------------------------------------------
2584: sub get_kerberos_defaults {
2585: my $domain=shift;
2586: my ($krbdef,$krbdefdom);
2587: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2588: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2589: $krbdef = $domdefaults{'auth_def'};
2590: $krbdefdom = $domdefaults{'auth_arg_def'};
2591: } else {
2592: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2593: my $krbdefdom=$1;
2594: $krbdefdom=~tr/a-z/A-Z/;
2595: $krbdef = "krb4";
2596: }
2597: return ($krbdef,$krbdefdom);
2598: }
2599:
2600:
2601: ###############################################################
2602: ## Thesaurus Functions ##
2603: ###############################################################
2604:
2605: =pod
2606:
2607: =head1 Thesaurus Functions
2608:
2609: =over 4
2610:
2611: =item * &initialize_keywords()
2612:
2613: Initializes the package variable %Keywords if it is empty. Uses the
2614: package variable $thesaurus_db_file.
2615:
2616: =cut
2617:
2618: ###################################################
2619:
2620: sub initialize_keywords {
2621: return 1 if (scalar keys(%Keywords));
2622: # If we are here, %Keywords is empty, so fill it up
2623: # Make sure the file we need exists...
2624: if (! -e $thesaurus_db_file) {
2625: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2626: " failed because it does not exist");
2627: return 0;
2628: }
2629: # Set up the hash as a database
2630: my %thesaurus_db;
2631: if (! tie(%thesaurus_db,'GDBM_File',
2632: $thesaurus_db_file,&GDBM_READER(),0640)){
2633: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2634: $thesaurus_db_file);
2635: return 0;
2636: }
2637: # Get the average number of appearances of a word.
2638: my $avecount = $thesaurus_db{'average.count'};
2639: # Put keywords (those that appear > average) into %Keywords
2640: while (my ($word,$data)=each (%thesaurus_db)) {
2641: my ($count,undef) = split /:/,$data;
2642: $Keywords{$word}++ if ($count > $avecount);
2643: }
2644: untie %thesaurus_db;
2645: # Remove special values from %Keywords.
2646: foreach my $value ('total.count','average.count') {
2647: delete($Keywords{$value}) if (exists($Keywords{$value}));
2648: }
2649: return 1;
2650: }
2651:
2652: ###################################################
2653:
2654: =pod
2655:
2656: =item * &keyword($word)
2657:
2658: Returns true if $word is a keyword. A keyword is a word that appears more
2659: than the average number of times in the thesaurus database. Calls
2660: &initialize_keywords
2661:
2662: =cut
2663:
2664: ###################################################
2665:
2666: sub keyword {
2667: return if (!&initialize_keywords());
2668: my $word=lc(shift());
2669: $word=~s/\W//g;
2670: return exists($Keywords{$word});
2671: }
2672:
2673: ###############################################################
2674:
2675: =pod
2676:
2677: =item * &get_related_words()
2678:
2679: Look up a word in the thesaurus. Takes a scalar argument and returns
2680: an array of words. If the keyword is not in the thesaurus, an empty array
2681: will be returned. The order of the words returned is determined by the
2682: database which holds them.
2683:
2684: Uses global $thesaurus_db_file.
2685:
2686: =cut
2687:
2688: ###############################################################
2689: sub get_related_words {
2690: my $keyword = shift;
2691: my %thesaurus_db;
2692: if (! -e $thesaurus_db_file) {
2693: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2694: "failed because the file does not exist");
2695: return ();
2696: }
2697: if (! tie(%thesaurus_db,'GDBM_File',
2698: $thesaurus_db_file,&GDBM_READER(),0640)){
2699: return ();
2700: }
2701: my @Words=();
2702: my $count=0;
2703: if (exists($thesaurus_db{$keyword})) {
2704: # The first element is the number of times
2705: # the word appears. We do not need it now.
2706: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2707: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2708: my $threshold=$mostfrequentcount/10;
2709: foreach my $possibleword (@RelatedWords) {
2710: my ($word,$wordcount)=split(/\,/,$possibleword);
2711: if ($wordcount>$threshold) {
2712: push(@Words,$word);
2713: $count++;
2714: if ($count>10) { last; }
2715: }
2716: }
2717: }
2718: untie %thesaurus_db;
2719: return @Words;
2720: }
2721:
2722: =pod
2723:
2724: =back
2725:
2726: =cut
2727:
2728: # -------------------------------------------------------------- Plaintext name
2729: =pod
2730:
2731: =head1 User Name Functions
2732:
2733: =over 4
2734:
2735: =item * &plainname($uname,$udom,$first)
2736:
2737: Takes a users logon name and returns it as a string in
2738: "first middle last generation" form
2739: if $first is set to 'lastname' then it returns it as
2740: 'lastname generation, firstname middlename' if their is a lastname
2741:
2742: =cut
2743:
2744:
2745: ###############################################################
2746: sub plainname {
2747: my ($uname,$udom,$first)=@_;
2748: return if (!defined($uname) || !defined($udom));
2749: my %names=&getnames($uname,$udom);
2750: my $name=&Apache::lonnet::format_name($names{'firstname'},
2751: $names{'middlename'},
2752: $names{'lastname'},
2753: $names{'generation'},$first);
2754: $name=~s/^\s+//;
2755: $name=~s/\s+$//;
2756: $name=~s/\s+/ /g;
2757: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2758: return $name;
2759: }
2760:
2761: # -------------------------------------------------------------------- Nickname
2762: =pod
2763:
2764: =item * &nickname($uname,$udom)
2765:
2766: Gets a users name and returns it as a string as
2767:
2768: ""nickname""
2769:
2770: if the user has a nickname or
2771:
2772: "first middle last generation"
2773:
2774: if the user does not
2775:
2776: =cut
2777:
2778: sub nickname {
2779: my ($uname,$udom)=@_;
2780: return if (!defined($uname) || !defined($udom));
2781: my %names=&getnames($uname,$udom);
2782: my $name=$names{'nickname'};
2783: if ($name) {
2784: $name='"'.$name.'"';
2785: } else {
2786: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2787: $names{'lastname'}.' '.$names{'generation'};
2788: $name=~s/\s+$//;
2789: $name=~s/\s+/ /g;
2790: }
2791: return $name;
2792: }
2793:
2794: sub getnames {
2795: my ($uname,$udom)=@_;
2796: return if (!defined($uname) || !defined($udom));
2797: if ($udom eq 'public' && $uname eq 'public') {
2798: return ('lastname' => &mt('Public'));
2799: }
2800: my $id=$uname.':'.$udom;
2801: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2802: if ($cached) {
2803: return %{$names};
2804: } else {
2805: my %loadnames=&Apache::lonnet::get('environment',
2806: ['firstname','middlename','lastname','generation','nickname'],
2807: $udom,$uname);
2808: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2809: return %loadnames;
2810: }
2811: }
2812:
2813: # -------------------------------------------------------------------- getemails
2814:
2815: =pod
2816:
2817: =item * &getemails($uname,$udom)
2818:
2819: Gets a user's email information and returns it as a hash with keys:
2820: notification, critnotification, permanentemail
2821:
2822: For notification and critnotification, values are comma-separated lists
2823: of e-mail addresses; for permanentemail, value is a single e-mail address.
2824:
2825:
2826: =cut
2827:
2828:
2829: sub getemails {
2830: my ($uname,$udom)=@_;
2831: if ($udom eq 'public' && $uname eq 'public') {
2832: return;
2833: }
2834: if (!$udom) { $udom=$env{'user.domain'}; }
2835: if (!$uname) { $uname=$env{'user.name'}; }
2836: my $id=$uname.':'.$udom;
2837: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2838: if ($cached) {
2839: return %{$names};
2840: } else {
2841: my %loadnames=&Apache::lonnet::get('environment',
2842: ['notification','critnotification',
2843: 'permanentemail'],
2844: $udom,$uname);
2845: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2846: return %loadnames;
2847: }
2848: }
2849:
2850: sub flush_email_cache {
2851: my ($uname,$udom)=@_;
2852: if (!$udom) { $udom =$env{'user.domain'}; }
2853: if (!$uname) { $uname=$env{'user.name'}; }
2854: return if ($udom eq 'public' && $uname eq 'public');
2855: my $id=$uname.':'.$udom;
2856: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2857: }
2858:
2859: # -------------------------------------------------------------------- getlangs
2860:
2861: =pod
2862:
2863: =item * &getlangs($uname,$udom)
2864:
2865: Gets a user's language preference and returns it as a hash with key:
2866: language.
2867:
2868: =cut
2869:
2870:
2871: sub getlangs {
2872: my ($uname,$udom) = @_;
2873: if (!$udom) { $udom =$env{'user.domain'}; }
2874: if (!$uname) { $uname=$env{'user.name'}; }
2875: my $id=$uname.':'.$udom;
2876: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
2877: if ($cached) {
2878: return %{$langs};
2879: } else {
2880: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
2881: $udom,$uname);
2882: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
2883: return %loadlangs;
2884: }
2885: }
2886:
2887: sub flush_langs_cache {
2888: my ($uname,$udom)=@_;
2889: if (!$udom) { $udom =$env{'user.domain'}; }
2890: if (!$uname) { $uname=$env{'user.name'}; }
2891: return if ($udom eq 'public' && $uname eq 'public');
2892: my $id=$uname.':'.$udom;
2893: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
2894: }
2895:
2896: # ------------------------------------------------------------------ Screenname
2897:
2898: =pod
2899:
2900: =item * &screenname($uname,$udom)
2901:
2902: Gets a users screenname and returns it as a string
2903:
2904: =cut
2905:
2906: sub screenname {
2907: my ($uname,$udom)=@_;
2908: if ($uname eq $env{'user.name'} &&
2909: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2910: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2911: return $names{'screenname'};
2912: }
2913:
2914: # ------------------------------------------------------------- Confirm Wrapper
2915: =pod
2916:
2917: =item confirmwrapper
2918:
2919: Wrap messages about completion of operation in box
2920:
2921: =cut
2922:
2923: sub confirmwrapper {
2924: my ($message)=@_;
2925: if ($message) {
2926: return "\n".'<div class="LC_confirm_box">'."\n"
2927: .$message."\n"
2928: .'</div>'."\n";
2929: } else {
2930: return $message;
2931: }
2932: }
2933:
2934: # ------------------------------------------------------------- Message Wrapper
2935:
2936: sub messagewrapper {
2937: my ($link,$username,$domain,$subject,$text)=@_;
2938: return
2939: '<a href="/adm/email?compose=individual&'.
2940: 'recname='.$username.'&recdom='.$domain.
2941: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2942: 'title="'.&mt('Send message').'">'.$link.'</a>';
2943: }
2944: # --------------------------------------------------------------- Notes Wrapper
2945:
2946: sub noteswrapper {
2947: my ($link,$un,$do)=@_;
2948: return
2949: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2950: }
2951: # ------------------------------------------------------------- Aboutme Wrapper
2952:
2953: sub aboutmewrapper {
2954: my ($link,$username,$domain,$target)=@_;
2955: if (!defined($username) && !defined($domain)) {
2956: return;
2957: }
2958: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2959: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
2960: }
2961:
2962: # ------------------------------------------------------------ Syllabus Wrapper
2963:
2964:
2965: sub syllabuswrapper {
2966: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2967: if ($fontcolor) {
2968: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2969: }
2970: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2971: }
2972:
2973: sub track_student_link {
2974: my ($linktext,$sname,$sdom,$target,$start) = @_;
2975: my $link ="/adm/trackstudent?";
2976: my $title = 'View recent activity';
2977: if (defined($sname) && $sname !~ /^\s*$/ &&
2978: defined($sdom) && $sdom !~ /^\s*$/) {
2979: $link .= "selected_student=$sname:$sdom";
2980: $title .= ' of this student';
2981: }
2982: if (defined($target) && $target !~ /^\s*$/) {
2983: $target = qq{target="$target"};
2984: } else {
2985: $target = '';
2986: }
2987: if ($start) { $link.='&start='.$start; }
2988: $title = &mt($title);
2989: $linktext = &mt($linktext);
2990: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2991: &help_open_topic('View_recent_activity');
2992: }
2993:
2994: sub slot_reservations_link {
2995: my ($linktext,$sname,$sdom,$target) = @_;
2996: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
2997: my $title = 'View slot reservation history';
2998: if (defined($sname) && $sname !~ /^\s*$/ &&
2999: defined($sdom) && $sdom !~ /^\s*$/) {
3000: $link .= "&uname=$sname&udom=$sdom";
3001: $title .= ' of this student';
3002: }
3003: if (defined($target) && $target !~ /^\s*$/) {
3004: $target = qq{target="$target"};
3005: } else {
3006: $target = '';
3007: }
3008: $title = &mt($title);
3009: $linktext = &mt($linktext);
3010: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3011: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3012:
3013: }
3014:
3015: # ===================================================== Display a student photo
3016:
3017:
3018: sub student_image_tag {
3019: my ($domain,$user)=@_;
3020: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3021: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3022: return '<img src="'.$imgsrc.'" align="right" />';
3023: } else {
3024: return '';
3025: }
3026: }
3027:
3028: =pod
3029:
3030: =back
3031:
3032: =head1 Access .tab File Data
3033:
3034: =over 4
3035:
3036: =item * &languageids()
3037:
3038: returns list of all language ids
3039:
3040: =cut
3041:
3042: sub languageids {
3043: return sort(keys(%language));
3044: }
3045:
3046: =pod
3047:
3048: =item * &languagedescription()
3049:
3050: returns description of a specified language id
3051:
3052: =cut
3053:
3054: sub languagedescription {
3055: my $code=shift;
3056: return ($supported_language{$code}?'* ':'').
3057: $language{$code}.
3058: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3059: }
3060:
3061: sub plainlanguagedescription {
3062: my $code=shift;
3063: return $language{$code};
3064: }
3065:
3066: sub supportedlanguagecode {
3067: my $code=shift;
3068: return $supported_language{$code};
3069: }
3070:
3071: =pod
3072:
3073: =item * ©rightids()
3074:
3075: returns list of all copyrights
3076:
3077: =cut
3078:
3079: sub copyrightids {
3080: return sort(keys(%cprtag));
3081: }
3082:
3083: =pod
3084:
3085: =item * ©rightdescription()
3086:
3087: returns description of a specified copyright id
3088:
3089: =cut
3090:
3091: sub copyrightdescription {
3092: return &mt($cprtag{shift(@_)});
3093: }
3094:
3095: =pod
3096:
3097: =item * &source_copyrightids()
3098:
3099: returns list of all source copyrights
3100:
3101: =cut
3102:
3103: sub source_copyrightids {
3104: return sort(keys(%scprtag));
3105: }
3106:
3107: =pod
3108:
3109: =item * &source_copyrightdescription()
3110:
3111: returns description of a specified source copyright id
3112:
3113: =cut
3114:
3115: sub source_copyrightdescription {
3116: return &mt($scprtag{shift(@_)});
3117: }
3118:
3119: =pod
3120:
3121: =item * &filecategories()
3122:
3123: returns list of all file categories
3124:
3125: =cut
3126:
3127: sub filecategories {
3128: return sort(keys(%category_extensions));
3129: }
3130:
3131: =pod
3132:
3133: =item * &filecategorytypes()
3134:
3135: returns list of file types belonging to a given file
3136: category
3137:
3138: =cut
3139:
3140: sub filecategorytypes {
3141: my ($cat) = @_;
3142: return @{$category_extensions{lc($cat)}};
3143: }
3144:
3145: =pod
3146:
3147: =item * &fileembstyle()
3148:
3149: returns embedding style for a specified file type
3150:
3151: =cut
3152:
3153: sub fileembstyle {
3154: return $fe{lc(shift(@_))};
3155: }
3156:
3157: sub filemimetype {
3158: return $fm{lc(shift(@_))};
3159: }
3160:
3161:
3162: sub filecategoryselect {
3163: my ($name,$value)=@_;
3164: return &select_form($value,$name,
3165: '' => &mt('Any category'),
3166: map { $_,$_ } sort(keys(%category_extensions)));
3167: }
3168:
3169: =pod
3170:
3171: =item * &filedescription()
3172:
3173: returns description for a specified file type
3174:
3175: =cut
3176:
3177: sub filedescription {
3178: my $file_description = $fd{lc(shift())};
3179: $file_description =~ s:([\[\]]):~$1:g;
3180: return &mt($file_description);
3181: }
3182:
3183: =pod
3184:
3185: =item * &filedescriptionex()
3186:
3187: returns description for a specified file type with
3188: extra formatting
3189:
3190: =cut
3191:
3192: sub filedescriptionex {
3193: my $ex=shift;
3194: my $file_description = $fd{lc($ex)};
3195: $file_description =~ s:([\[\]]):~$1:g;
3196: return '.'.$ex.' '.&mt($file_description);
3197: }
3198:
3199: # End of .tab access
3200: =pod
3201:
3202: =back
3203:
3204: =cut
3205:
3206: # ------------------------------------------------------------------ File Types
3207: sub fileextensions {
3208: return sort(keys(%fe));
3209: }
3210:
3211: # ----------------------------------------------------------- Display Languages
3212: # returns a hash with all desired display languages
3213: #
3214:
3215: sub display_languages {
3216: my %languages=();
3217: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3218: $languages{$lang}=1;
3219: }
3220: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3221: if ($env{'form.displaylanguage'}) {
3222: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3223: $languages{$lang}=1;
3224: }
3225: }
3226: return %languages;
3227: }
3228:
3229: sub languages {
3230: my ($possible_langs) = @_;
3231: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3232: if (!ref($possible_langs)) {
3233: if( wantarray ) {
3234: return @preferred_langs;
3235: } else {
3236: return $preferred_langs[0];
3237: }
3238: }
3239: my %possibilities = map { $_ => 1 } (@$possible_langs);
3240: my @preferred_possibilities;
3241: foreach my $preferred_lang (@preferred_langs) {
3242: if (exists($possibilities{$preferred_lang})) {
3243: push(@preferred_possibilities, $preferred_lang);
3244: }
3245: }
3246: if( wantarray ) {
3247: return @preferred_possibilities;
3248: }
3249: return $preferred_possibilities[0];
3250: }
3251:
3252: sub user_lang {
3253: my ($touname,$toudom,$fromcid) = @_;
3254: my @userlangs;
3255: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3256: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3257: $env{'course.'.$fromcid.'.languages'}));
3258: } else {
3259: my %langhash = &getlangs($touname,$toudom);
3260: if ($langhash{'languages'} ne '') {
3261: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3262: } else {
3263: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3264: if ($domdefs{'lang_def'} ne '') {
3265: @userlangs = ($domdefs{'lang_def'});
3266: }
3267: }
3268: }
3269: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3270: my $user_lh = Apache::localize->get_handle(@languages);
3271: return $user_lh;
3272: }
3273:
3274: ###############################################################
3275: ## Student Answer Attempts ##
3276: ###############################################################
3277:
3278: =pod
3279:
3280: =head1 Alternate Problem Views
3281:
3282: =over 4
3283:
3284: =item * &get_previous_attempt($symb, $username, $domain, $course,
3285: $getattempt, $regexp, $gradesub)
3286:
3287: Return string with previous attempt on problem. Arguments:
3288:
3289: =over 4
3290:
3291: =item * $symb: Problem, including path
3292:
3293: =item * $username: username of the desired student
3294:
3295: =item * $domain: domain of the desired student
3296:
3297: =item * $course: Course ID
3298:
3299: =item * $getattempt: Leave blank for all attempts, otherwise put
3300: something
3301:
3302: =item * $regexp: if string matches this regexp, the string will be
3303: sent to $gradesub
3304:
3305: =item * $gradesub: routine that processes the string if it matches $regexp
3306:
3307: =back
3308:
3309: The output string is a table containing all desired attempts, if any.
3310:
3311: =cut
3312:
3313: sub get_previous_attempt {
3314: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3315: my $prevattempts='';
3316: no strict 'refs';
3317: if ($symb) {
3318: my (%returnhash)=
3319: &Apache::lonnet::restore($symb,$course,$domain,$username);
3320: if ($returnhash{'version'}) {
3321: my %lasthash=();
3322: my $version;
3323: for ($version=1;$version<=$returnhash{'version'};$version++) {
3324: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3325: $lasthash{$key}=$returnhash{$version.':'.$key};
3326: }
3327: }
3328: $prevattempts=&start_data_table().&start_data_table_header_row();
3329: $prevattempts.='<th>'.&mt('History').'</th>';
3330: foreach my $key (sort(keys(%lasthash))) {
3331: my ($ign,@parts) = split(/\./,$key);
3332: if ($#parts > 0) {
3333: my $data=$parts[-1];
3334: pop(@parts);
3335: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3336: } else {
3337: if ($#parts == 0) {
3338: $prevattempts.='<th>'.$parts[0].'</th>';
3339: } else {
3340: $prevattempts.='<th>'.$ign.'</th>';
3341: }
3342: }
3343: }
3344: $prevattempts.=&end_data_table_header_row();
3345: if ($getattempt eq '') {
3346: for ($version=1;$version<=$returnhash{'version'};$version++) {
3347: $prevattempts.=&start_data_table_row().
3348: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3349: foreach my $key (sort(keys(%lasthash))) {
3350: my $value = &format_previous_attempt_value($key,
3351: $returnhash{$version.':'.$key});
3352: $prevattempts.='<td>'.$value.' </td>';
3353: }
3354: $prevattempts.=&end_data_table_row();
3355: }
3356: }
3357: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3358: foreach my $key (sort(keys(%lasthash))) {
3359: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3360: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3361: $prevattempts.='<td>'.$value.' </td>';
3362: }
3363: $prevattempts.= &end_data_table_row().&end_data_table();
3364: } else {
3365: $prevattempts=
3366: &start_data_table().&start_data_table_row().
3367: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3368: &end_data_table_row().&end_data_table();
3369: }
3370: } else {
3371: $prevattempts=
3372: &start_data_table().&start_data_table_row().
3373: '<td>'.&mt('No data.').'</td>'.
3374: &end_data_table_row().&end_data_table();
3375: }
3376: }
3377:
3378: sub format_previous_attempt_value {
3379: my ($key,$value) = @_;
3380: if ($key =~ /timestamp/) {
3381: $value = &Apache::lonlocal::locallocaltime($value);
3382: } elsif (ref($value) eq 'ARRAY') {
3383: $value = '('.join(', ', @{ $value }).')';
3384: } else {
3385: $value = &unescape($value);
3386: }
3387: return $value;
3388: }
3389:
3390:
3391: sub relative_to_absolute {
3392: my ($url,$output)=@_;
3393: my $parser=HTML::TokeParser->new(\$output);
3394: my $token;
3395: my $thisdir=$url;
3396: my @rlinks=();
3397: while ($token=$parser->get_token) {
3398: if ($token->[0] eq 'S') {
3399: if ($token->[1] eq 'a') {
3400: if ($token->[2]->{'href'}) {
3401: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3402: }
3403: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3404: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3405: } elsif ($token->[1] eq 'base') {
3406: $thisdir=$token->[2]->{'href'};
3407: }
3408: }
3409: }
3410: $thisdir=~s-/[^/]*$--;
3411: foreach my $link (@rlinks) {
3412: unless (($link=~/^https?\:\/\//i) ||
3413: ($link=~/^\//) ||
3414: ($link=~/^javascript:/i) ||
3415: ($link=~/^mailto:/i) ||
3416: ($link=~/^\#/)) {
3417: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3418: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3419: }
3420: }
3421: # -------------------------------------------------- Deal with Applet codebases
3422: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3423: return $output;
3424: }
3425:
3426: =pod
3427:
3428: =item * &get_student_view()
3429:
3430: show a snapshot of what student was looking at
3431:
3432: =cut
3433:
3434: sub get_student_view {
3435: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3436: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3437: my (%form);
3438: my @elements=('symb','courseid','domain','username');
3439: foreach my $element (@elements) {
3440: $form{'grade_'.$element}=eval '$'.$element #'
3441: }
3442: if (defined($moreenv)) {
3443: %form=(%form,%{$moreenv});
3444: }
3445: if (defined($target)) { $form{'grade_target'} = $target; }
3446: $feedurl=&Apache::lonnet::clutter($feedurl);
3447: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3448: $userview=~s/\<body[^\>]*\>//gi;
3449: $userview=~s/\<\/body\>//gi;
3450: $userview=~s/\<html\>//gi;
3451: $userview=~s/\<\/html\>//gi;
3452: $userview=~s/\<head\>//gi;
3453: $userview=~s/\<\/head\>//gi;
3454: $userview=~s/action\s*\=/would_be_action\=/gi;
3455: $userview=&relative_to_absolute($feedurl,$userview);
3456: if (wantarray) {
3457: return ($userview,$response);
3458: } else {
3459: return $userview;
3460: }
3461: }
3462:
3463: sub get_student_view_with_retries {
3464: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3465:
3466: my $ok = 0; # True if we got a good response.
3467: my $content;
3468: my $response;
3469:
3470: # Try to get the student_view done. within the retries count:
3471:
3472: do {
3473: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3474: $ok = $response->is_success;
3475: if (!$ok) {
3476: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3477: }
3478: $retries--;
3479: } while (!$ok && ($retries > 0));
3480:
3481: if (!$ok) {
3482: $content = ''; # On error return an empty content.
3483: }
3484: if (wantarray) {
3485: return ($content, $response);
3486: } else {
3487: return $content;
3488: }
3489: }
3490:
3491: =pod
3492:
3493: =item * &get_student_answers()
3494:
3495: show a snapshot of how student was answering problem
3496:
3497: =cut
3498:
3499: sub get_student_answers {
3500: my ($symb,$username,$domain,$courseid,%form) = @_;
3501: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3502: my (%moreenv);
3503: my @elements=('symb','courseid','domain','username');
3504: foreach my $element (@elements) {
3505: $moreenv{'grade_'.$element}=eval '$'.$element #'
3506: }
3507: $moreenv{'grade_target'}='answer';
3508: %moreenv=(%form,%moreenv);
3509: $feedurl = &Apache::lonnet::clutter($feedurl);
3510: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3511: return $userview;
3512: }
3513:
3514: =pod
3515:
3516: =item * &submlink()
3517:
3518: Inputs: $text $uname $udom $symb $target
3519:
3520: Returns: A link to grades.pm such as to see the SUBM view of a student
3521:
3522: =cut
3523:
3524: ###############################################
3525: sub submlink {
3526: my ($text,$uname,$udom,$symb,$target)=@_;
3527: if (!($uname && $udom)) {
3528: (my $cursymb, my $courseid,$udom,$uname)=
3529: &Apache::lonnet::whichuser($symb);
3530: if (!$symb) { $symb=$cursymb; }
3531: }
3532: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3533: $symb=&escape($symb);
3534: if ($target) { $target="target=\"$target\""; }
3535: return '<a href="/adm/grades?&command=submission&'.
3536: 'symb='.$symb.'&student='.$uname.
3537: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3538: }
3539: ##############################################
3540:
3541: =pod
3542:
3543: =item * &pgrdlink()
3544:
3545: Inputs: $text $uname $udom $symb $target
3546:
3547: Returns: A link to grades.pm such as to see the PGRD view of a student
3548:
3549: =cut
3550:
3551: ###############################################
3552: sub pgrdlink {
3553: my $link=&submlink(@_);
3554: $link=~s/(&command=submission)/$1&showgrading=yes/;
3555: return $link;
3556: }
3557: ##############################################
3558:
3559: =pod
3560:
3561: =item * &pprmlink()
3562:
3563: Inputs: $text $uname $udom $symb $target
3564:
3565: Returns: A link to parmset.pm such as to see the PPRM view of a
3566: student and a specific resource
3567:
3568: =cut
3569:
3570: ###############################################
3571: sub pprmlink {
3572: my ($text,$uname,$udom,$symb,$target)=@_;
3573: if (!($uname && $udom)) {
3574: (my $cursymb, my $courseid,$udom,$uname)=
3575: &Apache::lonnet::whichuser($symb);
3576: if (!$symb) { $symb=$cursymb; }
3577: }
3578: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3579: $symb=&escape($symb);
3580: if ($target) { $target="target=\"$target\""; }
3581: return '<a href="/adm/parmset?command=set&'.
3582: 'symb='.$symb.'&uname='.$uname.
3583: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3584: }
3585: ##############################################
3586:
3587: =pod
3588:
3589: =back
3590:
3591: =cut
3592:
3593: ###############################################
3594:
3595:
3596: sub timehash {
3597: my ($thistime) = @_;
3598: my $timezone = &Apache::lonlocal::gettimezone();
3599: my $dt = DateTime->from_epoch(epoch => $thistime)
3600: ->set_time_zone($timezone);
3601: my $wday = $dt->day_of_week();
3602: if ($wday == 7) { $wday = 0; }
3603: return ( 'second' => $dt->second(),
3604: 'minute' => $dt->minute(),
3605: 'hour' => $dt->hour(),
3606: 'day' => $dt->day_of_month(),
3607: 'month' => $dt->month(),
3608: 'year' => $dt->year(),
3609: 'weekday' => $wday,
3610: 'dayyear' => $dt->day_of_year(),
3611: 'dlsav' => $dt->is_dst() );
3612: }
3613:
3614: sub utc_string {
3615: my ($date)=@_;
3616: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3617: }
3618:
3619: sub maketime {
3620: my %th=@_;
3621: my ($epoch_time,$timezone,$dt);
3622: $timezone = &Apache::lonlocal::gettimezone();
3623: eval {
3624: $dt = DateTime->new( year => $th{'year'},
3625: month => $th{'month'},
3626: day => $th{'day'},
3627: hour => $th{'hour'},
3628: minute => $th{'minute'},
3629: second => $th{'second'},
3630: time_zone => $timezone,
3631: );
3632: };
3633: if (!$@) {
3634: $epoch_time = $dt->epoch;
3635: if ($epoch_time) {
3636: return $epoch_time;
3637: }
3638: }
3639: return POSIX::mktime(
3640: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3641: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3642: }
3643:
3644: #########################################
3645:
3646: sub findallcourses {
3647: my ($roles,$uname,$udom) = @_;
3648: my %roles;
3649: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3650: my %courses;
3651: my $now=time;
3652: if (!defined($uname)) {
3653: $uname = $env{'user.name'};
3654: }
3655: if (!defined($udom)) {
3656: $udom = $env{'user.domain'};
3657: }
3658: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3659: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3660: if (!%roles) {
3661: %roles = (
3662: cc => 1,
3663: in => 1,
3664: ep => 1,
3665: ta => 1,
3666: cr => 1,
3667: st => 1,
3668: );
3669: }
3670: foreach my $entry (keys(%roleshash)) {
3671: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3672: if ($trole =~ /^cr/) {
3673: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3674: } else {
3675: next if (!exists($roles{$trole}));
3676: }
3677: if ($tend) {
3678: next if ($tend < $now);
3679: }
3680: if ($tstart) {
3681: next if ($tstart > $now);
3682: }
3683: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3684: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3685: if ($secpart eq '') {
3686: ($cnum,$role) = split(/_/,$cnumpart);
3687: $sec = 'none';
3688: $realsec = '';
3689: } else {
3690: $cnum = $cnumpart;
3691: ($sec,$role) = split(/_/,$secpart);
3692: $realsec = $sec;
3693: }
3694: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3695: }
3696: } else {
3697: foreach my $key (keys(%env)) {
3698: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3699: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3700: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3701: next if ($role eq 'ca' || $role eq 'aa');
3702: next if (%roles && !exists($roles{$role}));
3703: my ($starttime,$endtime)=split(/\./,$env{$key});
3704: my $active=1;
3705: if ($starttime) {
3706: if ($now<$starttime) { $active=0; }
3707: }
3708: if ($endtime) {
3709: if ($now>$endtime) { $active=0; }
3710: }
3711: if ($active) {
3712: if ($sec eq '') {
3713: $sec = 'none';
3714: }
3715: $courses{$cdom.'_'.$cnum}{$sec} =
3716: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3717: }
3718: }
3719: }
3720: }
3721: return %courses;
3722: }
3723:
3724: ###############################################
3725:
3726: sub blockcheck {
3727: my ($setters,$activity,$uname,$udom) = @_;
3728:
3729: if (!defined($udom)) {
3730: $udom = $env{'user.domain'};
3731: }
3732: if (!defined($uname)) {
3733: $uname = $env{'user.name'};
3734: }
3735:
3736: # If uname and udom are for a course, check for blocks in the course.
3737:
3738: if (&Apache::lonnet::is_course($udom,$uname)) {
3739: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3740: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3741: return ($startblock,$endblock);
3742: }
3743:
3744: my $startblock = 0;
3745: my $endblock = 0;
3746: my %live_courses = &findallcourses(undef,$uname,$udom);
3747:
3748: # If uname is for a user, and activity is course-specific, i.e.,
3749: # boards, chat or groups, check for blocking in current course only.
3750:
3751: if (($activity eq 'boards' || $activity eq 'chat' ||
3752: $activity eq 'groups') && ($env{'request.course.id'})) {
3753: foreach my $key (keys(%live_courses)) {
3754: if ($key ne $env{'request.course.id'}) {
3755: delete($live_courses{$key});
3756: }
3757: }
3758: }
3759:
3760: my $otheruser = 0;
3761: my %own_courses;
3762: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3763: # Resource belongs to user other than current user.
3764: $otheruser = 1;
3765: # Gather courses for current user
3766: %own_courses =
3767: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3768: }
3769:
3770: # Gather active course roles - course coordinator, instructor,
3771: # exam proctor, ta, student, or custom role.
3772:
3773: foreach my $course (keys(%live_courses)) {
3774: my ($cdom,$cnum);
3775: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3776: $cdom = $env{'course.'.$course.'.domain'};
3777: $cnum = $env{'course.'.$course.'.num'};
3778: } else {
3779: ($cdom,$cnum) = split(/_/,$course);
3780: }
3781: my $no_ownblock = 0;
3782: my $no_userblock = 0;
3783: if ($otheruser && $activity ne 'com') {
3784: # Check if current user has 'evb' priv for this
3785: if (defined($own_courses{$course})) {
3786: foreach my $sec (keys(%{$own_courses{$course}})) {
3787: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3788: if ($sec ne 'none') {
3789: $checkrole .= '/'.$sec;
3790: }
3791: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3792: $no_ownblock = 1;
3793: last;
3794: }
3795: }
3796: }
3797: # if they have 'evb' priv and are currently not playing student
3798: next if (($no_ownblock) &&
3799: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3800: }
3801: foreach my $sec (keys(%{$live_courses{$course}})) {
3802: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3803: if ($sec ne 'none') {
3804: $checkrole .= '/'.$sec;
3805: }
3806: if ($otheruser) {
3807: # Resource belongs to user other than current user.
3808: # Assemble privs for that user, and check for 'evb' priv.
3809: my ($trole,$tdom,$tnum,$tsec);
3810: my $entry = $live_courses{$course}{$sec};
3811: if ($entry =~ /^cr/) {
3812: ($trole,$tdom,$tnum,$tsec) =
3813: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3814: } else {
3815: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3816: }
3817: my ($spec,$area,$trest,%allroles,%userroles);
3818: $area = '/'.$tdom.'/'.$tnum;
3819: $trest = $tnum;
3820: if ($tsec ne '') {
3821: $area .= '/'.$tsec;
3822: $trest .= '/'.$tsec;
3823: }
3824: $spec = $trole.'.'.$area;
3825: if ($trole =~ /^cr/) {
3826: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3827: $tdom,$spec,$trest,$area);
3828: } else {
3829: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3830: $tdom,$spec,$trest,$area);
3831: }
3832: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3833: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3834: if ($1) {
3835: $no_userblock = 1;
3836: last;
3837: }
3838: }
3839: } else {
3840: # Resource belongs to current user
3841: # Check for 'evb' priv via lonnet::allowed().
3842: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3843: $no_ownblock = 1;
3844: last;
3845: }
3846: }
3847: }
3848: # if they have the evb priv and are currently not playing student
3849: next if (($no_ownblock) &&
3850: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3851: next if ($no_userblock);
3852:
3853: # Retrieve blocking times and identity of blocker for course
3854: # of specified user, unless user has 'evb' privilege.
3855:
3856: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3857: if (($start != 0) &&
3858: (($startblock == 0) || ($startblock > $start))) {
3859: $startblock = $start;
3860: }
3861: if (($end != 0) &&
3862: (($endblock == 0) || ($endblock < $end))) {
3863: $endblock = $end;
3864: }
3865: }
3866: return ($startblock,$endblock);
3867: }
3868:
3869: sub get_blocks {
3870: my ($setters,$activity,$cdom,$cnum) = @_;
3871: my $startblock = 0;
3872: my $endblock = 0;
3873: my $course = $cdom.'_'.$cnum;
3874: $setters->{$course} = {};
3875: $setters->{$course}{'staff'} = [];
3876: $setters->{$course}{'times'} = [];
3877: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3878: foreach my $record (keys(%records)) {
3879: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3880: if ($start <= time && $end >= time) {
3881: my ($staff_name,$staff_dom,$title,$blocks) =
3882: &parse_block_record($records{$record});
3883: if ($blocks->{$activity} eq 'on') {
3884: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3885: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3886: if ( ($startblock == 0) || ($startblock > $start) ) {
3887: $startblock = $start;
3888: }
3889: if ( ($endblock == 0) || ($endblock < $end) ) {
3890: $endblock = $end;
3891: }
3892: }
3893: }
3894: }
3895: return ($startblock,$endblock);
3896: }
3897:
3898: sub parse_block_record {
3899: my ($record) = @_;
3900: my ($setuname,$setudom,$title,$blocks);
3901: if (ref($record) eq 'HASH') {
3902: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3903: $title = &unescape($record->{'event'});
3904: $blocks = $record->{'blocks'};
3905: } else {
3906: my @data = split(/:/,$record,3);
3907: if (scalar(@data) eq 2) {
3908: $title = $data[1];
3909: ($setuname,$setudom) = split(/@/,$data[0]);
3910: } else {
3911: ($setuname,$setudom,$title) = @data;
3912: }
3913: $blocks = { 'com' => 'on' };
3914: }
3915: return ($setuname,$setudom,$title,$blocks);
3916: }
3917:
3918: sub build_block_table {
3919: my ($startblock,$endblock,$setters) = @_;
3920: my %lt = &Apache::lonlocal::texthash(
3921: 'cacb' => 'Currently active communication blocks',
3922: 'cour' => 'Course',
3923: 'dura' => 'Duration',
3924: 'blse' => 'Block set by'
3925: );
3926: my $output;
3927: $output = '<br />'.$lt{'cacb'}.':<br />';
3928: $output .= &start_data_table();
3929: $output .= '
3930: <tr>
3931: <th>'.$lt{'cour'}.'</th>
3932: <th>'.$lt{'dura'}.'</th>
3933: <th>'.$lt{'blse'}.'</th>
3934: </tr>
3935: ';
3936: foreach my $course (keys(%{$setters})) {
3937: my %courseinfo=&Apache::lonnet::coursedescription($course);
3938: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3939: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3940: my $fullname = &plainname($uname,$udom);
3941: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3942: && $env{'user.name'} ne 'public'
3943: && $env{'user.domain'} ne 'public') {
3944: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3945: }
3946: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3947: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3948: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3949: $output .= &Apache::loncommon::start_data_table_row().
3950: '<td>'.$courseinfo{'description'}.'</td>'.
3951: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3952: '<td>'.$fullname.'</td>'.
3953: &Apache::loncommon::end_data_table_row();
3954: }
3955: }
3956: $output .= &end_data_table();
3957: }
3958:
3959: sub blocking_status {
3960: my ($activity,$uname,$udom) = @_;
3961: my %setters;
3962: my ($blocked,$output,$ownitem,$is_course);
3963: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3964: if ($startblock && $endblock) {
3965: $blocked = 1;
3966: if (wantarray) {
3967: my $category;
3968: if ($activity eq 'boards') {
3969: $category = 'Discussion posts in this course';
3970: } elsif ($activity eq 'blogs') {
3971: $category = 'Blogs';
3972: } elsif ($activity eq 'port') {
3973: if (defined($uname) && defined($udom)) {
3974: if ($uname eq $env{'user.name'} &&
3975: $udom eq $env{'user.domain'}) {
3976: $ownitem = 1;
3977: }
3978: }
3979: $is_course = &Apache::lonnet::is_course($udom,$uname);
3980: if ($ownitem) {
3981: $category = 'Your portfolio files';
3982: } elsif ($is_course) {
3983: my $coursedesc;
3984: foreach my $course (keys(%setters)) {
3985: my %courseinfo =
3986: &Apache::lonnet::coursedescription($course);
3987: $coursedesc = $courseinfo{'description'};
3988: }
3989: $category = "Group portfolio files in the course '$coursedesc'";
3990: } else {
3991: $category = 'Portfolio files belonging to ';
3992: if ($env{'user.name'} eq 'public' &&
3993: $env{'user.domain'} eq 'public') {
3994: $category .= &plainname($uname,$udom);
3995: } else {
3996: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3997: }
3998: }
3999: } elsif ($activity eq 'groups') {
4000: $category = 'Groups in this course';
4001: }
4002: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
4003: my $showend = &Apache::lonlocal::locallocaltime($endblock);
4004: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
4005: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
4006: $output .= &build_block_table($startblock,$endblock,\%setters);
4007: }
4008: }
4009: }
4010: if (wantarray) {
4011: return ($blocked,$output);
4012: } else {
4013: return $blocked;
4014: }
4015: }
4016:
4017: ###############################################
4018:
4019: sub check_ip_acc {
4020: my ($acc)=@_;
4021: &Apache::lonxml::debug("acc is $acc");
4022: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4023: return 1;
4024: }
4025: my $allowed=0;
4026: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4027:
4028: my $name;
4029: foreach my $pattern (split(',',$acc)) {
4030: $pattern =~ s/^\s*//;
4031: $pattern =~ s/\s*$//;
4032: if ($pattern =~ /\*$/) {
4033: #35.8.*
4034: $pattern=~s/\*//;
4035: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4036: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4037: #35.8.3.[34-56]
4038: my $low=$2;
4039: my $high=$3;
4040: $pattern=$1;
4041: if ($ip =~ /^\Q$pattern\E/) {
4042: my $last=(split(/\./,$ip))[3];
4043: if ($last <=$high && $last >=$low) { $allowed=1; }
4044: }
4045: } elsif ($pattern =~ /^\*/) {
4046: #*.msu.edu
4047: $pattern=~s/\*//;
4048: if (!defined($name)) {
4049: use Socket;
4050: my $netaddr=inet_aton($ip);
4051: ($name)=gethostbyaddr($netaddr,AF_INET);
4052: }
4053: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4054: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4055: #127.0.0.1
4056: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4057: } else {
4058: #some.name.com
4059: if (!defined($name)) {
4060: use Socket;
4061: my $netaddr=inet_aton($ip);
4062: ($name)=gethostbyaddr($netaddr,AF_INET);
4063: }
4064: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4065: }
4066: if ($allowed) { last; }
4067: }
4068: return $allowed;
4069: }
4070:
4071: ###############################################
4072:
4073: =pod
4074:
4075: =head1 Domain Template Functions
4076:
4077: =over 4
4078:
4079: =item * &determinedomain()
4080:
4081: Inputs: $domain (usually will be undef)
4082:
4083: Returns: Determines which domain should be used for designs
4084:
4085: =cut
4086:
4087: ###############################################
4088: sub determinedomain {
4089: my $domain=shift;
4090: if (! $domain) {
4091: # Determine domain if we have not been given one
4092: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
4093: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4094: if ($env{'request.role.domain'}) {
4095: $domain=$env{'request.role.domain'};
4096: }
4097: }
4098: return $domain;
4099: }
4100: ###############################################
4101:
4102: sub devalidate_domconfig_cache {
4103: my ($udom)=@_;
4104: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4105: }
4106:
4107: # ---------------------- Get domain configuration for a domain
4108: sub get_domainconf {
4109: my ($udom) = @_;
4110: my $cachetime=1800;
4111: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4112: if (defined($cached)) { return %{$result}; }
4113:
4114: my %domconfig = &Apache::lonnet::get_dom('configuration',
4115: ['login','rolecolors'],$udom);
4116: my (%designhash,%legacy);
4117: if (keys(%domconfig) > 0) {
4118: if (ref($domconfig{'login'}) eq 'HASH') {
4119: if (keys(%{$domconfig{'login'}})) {
4120: foreach my $key (keys(%{$domconfig{'login'}})) {
4121: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4122: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4123: $designhash{$udom.'.login.'.$key.'_'.$img} =
4124: $domconfig{'login'}{$key}{$img};
4125: }
4126: } else {
4127: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4128: }
4129: }
4130: } else {
4131: $legacy{'login'} = 1;
4132: }
4133: } else {
4134: $legacy{'login'} = 1;
4135: }
4136: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4137: if (keys(%{$domconfig{'rolecolors'}})) {
4138: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4139: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4140: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4141: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4142: }
4143: }
4144: }
4145: } else {
4146: $legacy{'rolecolors'} = 1;
4147: }
4148: } else {
4149: $legacy{'rolecolors'} = 1;
4150: }
4151: if (keys(%legacy) > 0) {
4152: my %legacyhash = &get_legacy_domconf($udom);
4153: foreach my $item (keys(%legacyhash)) {
4154: if ($item =~ /^\Q$udom\E\.login/) {
4155: if ($legacy{'login'}) {
4156: $designhash{$item} = $legacyhash{$item};
4157: }
4158: } else {
4159: if ($legacy{'rolecolors'}) {
4160: $designhash{$item} = $legacyhash{$item};
4161: }
4162: }
4163: }
4164: }
4165: } else {
4166: %designhash = &get_legacy_domconf($udom);
4167: }
4168: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4169: $cachetime);
4170: return %designhash;
4171: }
4172:
4173: sub get_legacy_domconf {
4174: my ($udom) = @_;
4175: my %legacyhash;
4176: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4177: my $designfile = $designdir.'/'.$udom.'.tab';
4178: if (-e $designfile) {
4179: if ( open (my $fh,"<$designfile") ) {
4180: while (my $line = <$fh>) {
4181: next if ($line =~ /^\#/);
4182: chomp($line);
4183: my ($key,$val)=(split(/\=/,$line));
4184: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4185: }
4186: close($fh);
4187: }
4188: }
4189: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
4190: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4191: }
4192: return %legacyhash;
4193: }
4194:
4195: =pod
4196:
4197: =item * &domainlogo()
4198:
4199: Inputs: $domain (usually will be undef)
4200:
4201: Returns: A link to a domain logo, if the domain logo exists.
4202: If the domain logo does not exist, a description of the domain.
4203:
4204: =cut
4205:
4206: ###############################################
4207: sub domainlogo {
4208: my $domain = &determinedomain(shift);
4209: my %designhash = &get_domainconf($domain);
4210: # See if there is a logo
4211: if ($designhash{$domain.'.login.domlogo'} ne '') {
4212: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4213: if ($imgsrc =~ m{^/(adm|res)/}) {
4214: if ($imgsrc =~ m{^/res/}) {
4215: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4216: &Apache::lonnet::repcopy($local_name);
4217: }
4218: $imgsrc = &lonhttpdurl($imgsrc);
4219: }
4220: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4221: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4222: return &Apache::lonnet::domain($domain,'description');
4223: } else {
4224: return '';
4225: }
4226: }
4227: ##############################################
4228:
4229: =pod
4230:
4231: =item * &designparm()
4232:
4233: Inputs: $which parameter; $domain (usually will be undef)
4234:
4235: Returns: value of designparamter $which
4236:
4237: =cut
4238:
4239:
4240: ##############################################
4241: sub designparm {
4242: my ($which,$domain)=@_;
4243: if ($env{'browser.blackwhite'} eq 'on') {
4244: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
4245: return '#000000';
4246: }
4247: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
4248: return '#FFFFFF';
4249: }
4250: if ($which=~/\.tabbg$/) {
4251: return '#CCCCCC';
4252: }
4253: }
4254: if (exists($env{'environment.color.'.$which})) {
4255: return $env{'environment.color.'.$which};
4256: }
4257: $domain=&determinedomain($domain);
4258: my %domdesign = &get_domainconf($domain);
4259: my $output;
4260: if ($domdesign{$domain.'.'.$which} ne '') {
4261: $output = $domdesign{$domain.'.'.$which};
4262: } else {
4263: $output = $defaultdesign{$which};
4264: }
4265: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4266: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4267: if ($output =~ m{^/(adm|res)/}) {
4268: if ($output =~ m{^/res/}) {
4269: my $local_name = &Apache::lonnet::filelocation('',$output);
4270: &Apache::lonnet::repcopy($local_name);
4271: }
4272: $output = &lonhttpdurl($output);
4273: }
4274: }
4275: return $output;
4276: }
4277:
4278: ###############################################
4279: ###############################################
4280:
4281: =pod
4282:
4283: =back
4284:
4285: =head1 HTML Helpers
4286:
4287: =over 4
4288:
4289: =item * &bodytag()
4290:
4291: Returns a uniform header for LON-CAPA web pages.
4292:
4293: Inputs:
4294:
4295: =over 4
4296:
4297: =item * $title, A title to be displayed on the page.
4298:
4299: =item * $function, the current role (can be undef).
4300:
4301: =item * $addentries, extra parameters for the <body> tag.
4302:
4303: =item * $bodyonly, if defined, only return the <body> tag.
4304:
4305: =item * $domain, if defined, force a given domain.
4306:
4307: =item * $forcereg, if page should register as content page (relevant for
4308: text interface only)
4309:
4310: =item * $customtitle, alternate text to use instead of $title
4311: in the title box that appears, this text
4312: is not auto translated like the $title is
4313:
4314: =item * $notopbar, if true, keep the 'what is this' info but remove the
4315: navigational links
4316:
4317: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4318:
4319: =item * $notitle, if true keep the nav controls, but remove the title bar
4320:
4321: =item * $no_inline_link, if true and in remote mode, don't show the
4322: 'Switch To Inline Menu' link
4323:
4324: =item * $args, optional argument valid values are
4325: no_auto_mt_title -> prevents &mt()ing the title arg
4326: inherit_jsmath -> when creating popup window in a page,
4327: should it have jsmath forced on by the
4328: current page
4329:
4330: =back
4331:
4332: Returns: A uniform header for LON-CAPA web pages.
4333: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4334: If $bodyonly is undef or zero, an html string containing a <body> tag and
4335: other decorations will be returned.
4336:
4337: =cut
4338:
4339: sub bodytag {
4340: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
4341: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
4342:
4343: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4344:
4345: $function = &get_users_function() if (!$function);
4346: my $img = &designparm($function.'.img',$domain);
4347: my $font = &designparm($function.'.font',$domain);
4348: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4349:
4350: my %design = ( 'style' => 'margin-top: 0',
4351: 'bgcolor' => $pgbg,
4352: 'text' => $font,
4353: 'alink' => &designparm($function.'.alink',$domain),
4354: 'vlink' => &designparm($function.'.vlink',$domain),
4355: 'link' => &designparm($function.'.link',$domain),);
4356: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4357:
4358: # role and realm
4359: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4360: if ($role eq 'ca') {
4361: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4362: $realm = &plainname($rname,$rdom);
4363: }
4364: # realm
4365: if ($env{'request.course.id'}) {
4366: if ($env{'request.role'} !~ /^cr/) {
4367: $role = &Apache::lonnet::plaintext($role,&course_type());
4368: }
4369: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4370: } else {
4371: $role = &Apache::lonnet::plaintext($role);
4372: }
4373:
4374: if (!$realm) { $realm=' '; }
4375: # Set messages
4376: my $messages=&domainlogo($domain);
4377:
4378: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4379:
4380: # construct main body tag
4381: my $bodytag = "<body $extra_body_attr>".
4382: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4383:
4384: if ($bodyonly) {
4385: return $bodytag;
4386: } elsif ($env{'browser.interface'} eq 'textual') {
4387: # Accessibility
4388:
4389: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4390: if (!$notitle) {
4391: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4392: }
4393: return $bodytag;
4394: }
4395:
4396: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4397: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4398: undef($role);
4399: } else {
4400: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4401: }
4402:
4403: my $roleinfo=(<<ENDROLE);
4404: <td class="LC_title_bar_who">
4405: <div class="LC_title_bar_name">
4406: $name
4407:
4408: </div>
4409: <div class="LC_title_bar_role">
4410: $role
4411: </div>
4412: <div class="LC_title_bar_realm">
4413: $realm
4414: </div>
4415: </td>
4416: ENDROLE
4417:
4418: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4419: if ($customtitle) {
4420: $titleinfo = $customtitle;
4421: }
4422: #
4423: # Extra info if you are the DC
4424: my $dc_info = '';
4425: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4426: $env{'course.'.$env{'request.course.id'}.
4427: '.domain'}.'/'})) {
4428: my $cid = $env{'request.course.id'};
4429: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4430: $dc_info =~ s/\s+$//;
4431: $dc_info = '('.$dc_info.')';
4432: }
4433:
4434: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4435: # No Remote
4436: if ($env{'request.state'} eq 'construct') {
4437: $forcereg=1;
4438: }
4439:
4440: if (!$customtitle && $env{'request.state'} eq 'construct') {
4441: # this is for resources; directories have customtitle, and crumbs
4442: # and select recent are created in lonpubdir.pm
4443: my ($uname,$thisdisfn)=
4444: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4445: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4446: $formaction=~s/\/+/\//g;
4447:
4448: my $parentpath = '';
4449: my $lastitem = '';
4450: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4451: $parentpath = $1;
4452: $lastitem = $2;
4453: } else {
4454: $lastitem = $thisdisfn;
4455: }
4456: $titleinfo =
4457: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4458: .'<b>'.&mt('Construction Space').'</b>: '
4459: .'<form name="dirs" method="post" action="'.$formaction
4460: .'" target="_top"><tt><b>'
4461: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
4462: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4463: .'</form>'
4464: .&Apache::lonmenu::constspaceform();
4465: }
4466:
4467: my $titletable;
4468: if (!$notitle) {
4469: $titletable =
4470: '<table id="LC_title_bar">'.
4471: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4472: '</tr></table>';
4473: }
4474: if ($notopbar) {
4475: $bodytag .= $titletable;
4476: } else {
4477: if ($env{'request.state'} eq 'construct') {
4478: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4479: $titletable);
4480: } else {
4481: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4482: $titletable;
4483: }
4484: }
4485: return $bodytag;
4486: }
4487:
4488: #
4489: # Top frame rendering, Remote is up
4490: #
4491:
4492: my $imgsrc = $img;
4493: if ($img =~ /^\/adm/) {
4494: $imgsrc = &lonhttpdurl($img);
4495: }
4496: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4497:
4498: # Explicit link to get inline menu
4499: my $menu= ($no_inline_link?''
4500: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4501: #
4502: if ($notitle) {
4503: return $bodytag;
4504: }
4505: return(<<ENDBODY);
4506: $bodytag
4507: <table id="LC_title_bar" class="LC_with_remote">
4508: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4509: <td class="LC_title_bar_domain_logo">$messages </td>
4510: </tr>
4511: <tr><td>$titleinfo $dc_info $menu</td>
4512: $roleinfo
4513: </tr>
4514: </table>
4515: ENDBODY
4516: }
4517:
4518: sub make_attr_string {
4519: my ($register,$attr_ref) = @_;
4520:
4521: if ($attr_ref && !ref($attr_ref)) {
4522: die("addentries Must be a hash ref ".
4523: join(':',caller(1))." ".
4524: join(':',caller(0))." ");
4525: }
4526:
4527: if ($register) {
4528: my ($on_load,$on_unload);
4529: foreach my $key (keys(%{$attr_ref})) {
4530: if (lc($key) eq 'onload') {
4531: $on_load.=$attr_ref->{$key}.';';
4532: delete($attr_ref->{$key});
4533:
4534: } elsif (lc($key) eq 'onunload') {
4535: $on_unload.=$attr_ref->{$key}.';';
4536: delete($attr_ref->{$key});
4537: }
4538: }
4539: $attr_ref->{'onload'} =
4540: &Apache::lonmenu::loadevents(). $on_load;
4541: $attr_ref->{'onunload'}=
4542: &Apache::lonmenu::unloadevents().$on_unload;
4543: }
4544:
4545: # Accessibility font enhance
4546: if ($env{'browser.fontenhance'} eq 'on') {
4547: my $style;
4548: foreach my $key (keys(%{$attr_ref})) {
4549: if (lc($key) eq 'style') {
4550: $style.=$attr_ref->{$key}.';';
4551: delete($attr_ref->{$key});
4552: }
4553: }
4554: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4555: }
4556:
4557: if ($env{'browser.blackwhite'} eq 'on') {
4558: delete($attr_ref->{'font'});
4559: delete($attr_ref->{'link'});
4560: delete($attr_ref->{'alink'});
4561: delete($attr_ref->{'vlink'});
4562: delete($attr_ref->{'bgcolor'});
4563: delete($attr_ref->{'background'});
4564: }
4565:
4566: my $attr_string;
4567: foreach my $attr (keys(%$attr_ref)) {
4568: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4569: }
4570: return $attr_string;
4571: }
4572:
4573:
4574: ###############################################
4575: ###############################################
4576:
4577: =pod
4578:
4579: =item * &endbodytag()
4580:
4581: Returns a uniform footer for LON-CAPA web pages.
4582:
4583: Inputs: 1 - optional reference to an args hash
4584: If in the hash, key for noredirectlink has a value which evaluates to true,
4585: a 'Continue' link is not displayed if the page contains an
4586: internal redirect in the <head></head> section,
4587: i.e., $env{'internal.head.redirect'} exists
4588:
4589: =cut
4590:
4591: sub endbodytag {
4592: my ($args) = @_;
4593: my $endbodytag='</body>';
4594: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4595: if ( exists( $env{'internal.head.redirect'} ) ) {
4596: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4597: $endbodytag=
4598: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4599: &mt('Continue').'</a>'.
4600: $endbodytag;
4601: }
4602: }
4603: return $endbodytag;
4604: }
4605:
4606: =pod
4607:
4608: =item * &standard_css()
4609:
4610: Returns a style sheet
4611:
4612: Inputs: (all optional)
4613: domain -> force to color decorate a page for a specific
4614: domain
4615: function -> force usage of a specific rolish color scheme
4616: bgcolor -> override the default page bgcolor
4617:
4618: =cut
4619:
4620: sub standard_css {
4621: my ($function,$domain,$bgcolor) = @_;
4622: $function = &get_users_function() if (!$function);
4623: my $img = &designparm($function.'.img', $domain);
4624: my $tabbg = &designparm($function.'.tabbg', $domain);
4625: my $font = &designparm($function.'.font', $domain);
4626: my $sidebg = &designparm($function.'.sidebg',$domain);
4627: my $pgbg_or_bgcolor =
4628: $bgcolor ||
4629: &designparm($function.'.pgbg', $domain);
4630: my $pgbg = &designparm($function.'.pgbg', $domain);
4631: my $alink = &designparm($function.'.alink', $domain);
4632: my $vlink = &designparm($function.'.vlink', $domain);
4633: my $link = &designparm($function.'.link', $domain);
4634:
4635: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4636: my $mono = 'monospace';
4637: my $data_table_head = $sidebg;
4638: my $data_table_light = '#FAFAFA';
4639: my $data_table_dark = '#F0F0F0';
4640: my $data_table_darker = '#CCCCCC';
4641: my $data_table_highlight = '#FFFF00';
4642: my $mail_new = '#FFBB77';
4643: my $mail_new_hover = '#DD9955';
4644: my $mail_read = '#BBBB77';
4645: my $mail_read_hover = '#999944';
4646: my $mail_replied = '#AAAA88';
4647: my $mail_replied_hover = '#888855';
4648: my $mail_other = '#99BBBB';
4649: my $mail_other_hover = '#669999';
4650: my $table_header = '#DDDDDD';
4651: my $feedback_link_bg = '#BBBBBB';
4652: my $lg_border_color = '#C8C8C8';
4653:
4654: my $border = ($env{'browser.type'} eq 'explorer' ||
4655: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
4656: : '0 3px 0 4px';
4657:
4658:
4659: return <<END;
4660: h1, h2, h3, th { font-family: $sans }
4661: a:focus { color: red; background: yellow }
4662:
4663: hr {
4664: clear: both;
4665: color: $tabbg;
4666: background-color: $tabbg;
4667: height: 3px;
4668: border: none;
4669: }
4670:
4671: table.thinborder,
4672:
4673: table.thinborder tr th {
4674: border-style: solid;
4675: border-width: 1px;
4676: background: $tabbg;
4677: }
4678: table.thinborder tr td {
4679: border-style: solid;
4680: border-width: 1px
4681: }
4682:
4683: form, .inline { display: inline; }
4684: .center { text-align: center; }
4685: .LC_filename {font-family: $mono; white-space:pre;}
4686: .LC_error {
4687: color: red;
4688: font-size: larger;
4689: }
4690: .LC_warning,
4691: .LC_diff_removed {
4692: color: red;
4693: }
4694:
4695: .LC_info,
4696: .LC_success,
4697: .LC_diff_added {
4698: color: green;
4699: }
4700:
4701: div.LC_confirm_box {
4702: background-color: #FAFAFA;
4703: border: 1px solid $lg_border_color;
4704: margin-right: 0;
4705: padding: 5px;
4706: }
4707:
4708: div.LC_confirm_box .LC_error img,
4709: div.LC_confirm_box .LC_success img {
4710: vertical-align: middle;
4711: }
4712:
4713: .LC_icon {
4714: border: none;
4715: }
4716: .LC_indexer_icon {
4717: border: 0;
4718: height: 22px;
4719: }
4720: .LC_docs_spacer {
4721: width: 25px;
4722: height: 1px;
4723: border: none;
4724: }
4725:
4726: .LC_internal_info {
4727: color: #999999;
4728: }
4729:
4730: table.LC_pastsubmission {
4731: border: 1px solid black;
4732: margin: 2px;
4733: }
4734:
4735: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4736: width: 100%;
4737: background: $pgbg;
4738: border: 2px;
4739: border-collapse: separate;
4740: padding: 0;
4741: }
4742:
4743: table#LC_title_bar, table.LC_breadcrumbs,
4744: table#LC_title_bar.LC_with_remote {
4745: width: 100%;
4746: border-color: $pgbg;
4747: border-style: solid;
4748: border-width: $border;
4749:
4750: background: $pgbg;
4751: font-family: $sans;
4752: border-collapse: collapse;
4753: padding: 0;
4754: }
4755:
4756: table.LC_docs_path {
4757: width: 100%;
4758: border: 0;
4759: background: $pgbg;
4760: font-family: $sans;
4761: border-collapse: collapse;
4762: padding: 0;
4763: }
4764:
4765: table#LC_title_bar td {
4766: background: $tabbg;
4767: }
4768: table#LC_title_bar td.LC_title_bar_who {
4769: background: $tabbg;
4770: color: $font;
4771: font: small $sans;
4772: text-align: right;
4773: }
4774: span.LC_metadata {
4775: font-family: $sans;
4776: }
4777: span.LC_title_bar_title {
4778: font: bold x-large $sans;
4779: }
4780: table#LC_title_bar td.LC_title_bar_domain_logo {
4781: background: $sidebg;
4782: text-align: right;
4783: padding: 0;
4784: }
4785: table#LC_title_bar td.LC_title_bar_role_logo {
4786: background: $sidebg;
4787: padding: 0;
4788: }
4789:
4790: table#LC_menubuttons_mainmenu {
4791: width: 100%;
4792: border: 0;
4793: border-spacing: 1px;
4794: padding: 0 1px;
4795: margin: 0;
4796: border-collapse: separate;
4797: }
4798: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
4799: border: none;
4800: }
4801: table#LC_top_nav td {
4802: background: $tabbg;
4803: border: none;
4804: font-size: small;
4805: }
4806: table#LC_top_nav td a, div#LC_top_nav a {
4807: color: $font;
4808: font-family: $sans;
4809: }
4810: table#LC_top_nav td.LC_top_nav_logo {
4811: background: $tabbg;
4812: text-align: left;
4813: white-space: nowrap;
4814: width: 31px;
4815: }
4816: table#LC_top_nav td.LC_top_nav_logo img {
4817: border: none;
4818: vertical-align: bottom;
4819: }
4820: table#LC_top_nav td.LC_top_nav_exit,
4821: table#LC_top_nav td.LC_top_nav_help {
4822: width: 2.0em;
4823: }
4824: table#LC_top_nav td.LC_top_nav_login {
4825: width: 4.0em;
4826: text-align: center;
4827: }
4828: table.LC_breadcrumbs td, table.LC_docs_path td {
4829: background: $tabbg;
4830: color: $font;
4831: font-family: $sans;
4832: font-size: smaller;
4833: }
4834: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4835: table.LC_docs_path td.LC_docs_path_component {
4836: background: $tabbg;
4837: color: $font;
4838: font-family: $sans;
4839: font-size: larger;
4840: text-align: right;
4841: }
4842: td.LC_table_cell_checkbox {
4843: text-align: center;
4844: }
4845: table#LC_mainmenu td.LC_mainmenu_column {
4846: vertical-align: top;
4847: }
4848:
4849: .LC_menubuttons_inline_text {
4850: color: $font;
4851: font-family: $sans;
4852: font-size: smaller;
4853: }
4854:
4855: .LC_menubuttons_link {
4856: text-decoration: none;
4857: }
4858: /*2008--9-5: new menu style sheet.Changed category*/
4859: .LC_menubuttons_category {
4860: color: $font;
4861: background: $pgbg;
4862: font-family: $sans;
4863: font-size: larger;
4864: font-weight: bold;
4865: }
4866:
4867: td.LC_menubuttons_text {
4868: width: 90%;
4869: color: $font;
4870: font-family: $sans;
4871: }
4872:
4873: td.LC_menubuttons_img {
4874: }
4875:
4876: .LC_current_location {
4877: font-family: $sans;
4878: background: $tabbg;
4879: }
4880: .LC_new_mail {
4881: font-family: $sans;
4882: background: $tabbg;
4883: font-weight: bold;
4884: }
4885:
4886: .LC_dropadd_labeltext {
4887: font-family: $sans;
4888: text-align: right;
4889: }
4890:
4891: .LC_preferences_labeltext {
4892: font-family: $sans;
4893: text-align: right;
4894: }
4895:
4896: .LC_roleslog_note {
4897: font-size: smaller;
4898: }
4899:
4900: .LC_mail_functions {
4901: font-weight: bold;
4902: }
4903:
4904: table.LC_aboutme_port {
4905: border: none;
4906: border-collapse: collapse;
4907: border-spacing: 0;
4908: }
4909: table.LC_data_table, table.LC_mail_list {
4910: border: 1px solid #000000;
4911: border-collapse: separate;
4912: border-spacing: 1px;
4913: background: $pgbg;
4914: }
4915: .LC_data_table_dense {
4916: font-size: small;
4917: }
4918: table.LC_nested_outer {
4919: border: 1px solid #000000;
4920: border-collapse: collapse;
4921: border-spacing: 0;
4922: width: 100%;
4923: }
4924: table.LC_innerpickbox,
4925: table.LC_nested {
4926: border: none;
4927: border-collapse: collapse;
4928: border-spacing: 0;
4929: width: 100%;
4930: }
4931: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
4932: table.LC_prior_tries tr th,
4933: table.LC_innerpickbox tr th {
4934: font-weight: bold;
4935: background-color: $data_table_head;
4936: font-size: smaller;
4937: }
4938: table.LC_innerpickbox tr th,
4939: table.LC_innerpickbox tr td {
4940: vertical-align: top;
4941: }
4942: table.LC_data_table tr.LC_info_row > td {
4943: background-color: #CCCCCC;
4944: font-weight: bold;
4945: text-align: left;
4946: }
4947: table.LC_data_table tr.LC_odd_row > td,
4948: table.LC_pick_box tr > td.LC_odd_row,
4949: table.LC_aboutme_port tr td {
4950: background-color: $data_table_light;
4951: padding: 2px;
4952: }
4953: table.LC_data_table tr.LC_even_row > td,
4954: table.LC_pick_box tr > td.LC_even_row,
4955: table.LC_aboutme_port tr.LC_even_row td {
4956: background-color: $data_table_dark;
4957: padding: 2px;
4958: }
4959: table.LC_data_table tr.LC_data_table_highlight td {
4960: background-color: $data_table_darker;
4961: }
4962: table.LC_data_table tr td.LC_leftcol_header {
4963: background-color: $data_table_head;
4964: font-weight: bold;
4965: }
4966: table.LC_data_table tr.LC_empty_row td,
4967: table.LC_nested tr.LC_empty_row td {
4968: background-color: #FFFFFF;
4969: font-weight: bold;
4970: font-style: italic;
4971: text-align: center;
4972: padding: 8px;
4973: }
4974: table.LC_nested tr.LC_empty_row td {
4975: padding: 4ex
4976: }
4977: table.LC_nested_outer tr th {
4978: font-weight: bold;
4979: background-color: $data_table_head;
4980: font-size: smaller;
4981: border-bottom: 1px solid #000000;
4982: }
4983: table.LC_nested_outer tr td.LC_subheader {
4984: background-color: $data_table_head;
4985: font-weight: bold;
4986: font-size: small;
4987: border-bottom: 1px solid #000000;
4988: text-align: right;
4989: }
4990: table.LC_nested tr.LC_info_row td {
4991: background-color: #CCCCCC;
4992: font-weight: bold;
4993: font-size: small;
4994: text-align: center;
4995: }
4996: table.LC_nested tr.LC_info_row td.LC_left_item,
4997: table.LC_nested_outer tr th.LC_left_item {
4998: text-align: left;
4999: }
5000: table.LC_nested td {
5001: background-color: #FFFFFF;
5002: font-size: small;
5003: }
5004: table.LC_nested_outer tr th.LC_right_item,
5005: table.LC_nested tr.LC_info_row td.LC_right_item,
5006: table.LC_nested tr.LC_odd_row td.LC_right_item,
5007: table.LC_nested tr td.LC_right_item {
5008: text-align: right;
5009: }
5010:
5011: table.LC_nested tr.LC_odd_row td {
5012: background-color: #EEEEEE;
5013: }
5014:
5015: table.LC_createuser {
5016: }
5017:
5018: table.LC_createuser tr.LC_section_row td {
5019: font-size: smaller;
5020: }
5021:
5022: table.LC_createuser tr.LC_info_row td {
5023: background-color: #CCCCCC;
5024: font-weight: bold;
5025: text-align: center;
5026: }
5027:
5028: table.LC_calendar {
5029: border: 1px solid #000000;
5030: border-collapse: collapse;
5031: }
5032: table.LC_calendar_pickdate {
5033: font-size: xx-small;
5034: }
5035: table.LC_calendar tr td {
5036: border: 1px solid #000000;
5037: vertical-align: top;
5038: }
5039: table.LC_calendar tr td.LC_calendar_day_empty {
5040: background-color: $data_table_dark;
5041: }
5042: table.LC_calendar tr td.LC_calendar_day_current {
5043: background-color: $data_table_highlight;
5044: }
5045:
5046: table.LC_mail_list tr.LC_mail_new {
5047: background-color: $mail_new;
5048: }
5049: table.LC_mail_list tr.LC_mail_new:hover {
5050: background-color: $mail_new_hover;
5051: }
5052: table.LC_mail_list tr.LC_mail_read {
5053: background-color: $mail_read;
5054: }
5055: table.LC_mail_list tr.LC_mail_read:hover {
5056: background-color: $mail_read_hover;
5057: }
5058: table.LC_mail_list tr.LC_mail_replied {
5059: background-color: $mail_replied;
5060: }
5061: table.LC_mail_list tr.LC_mail_replied:hover {
5062: background-color: $mail_replied_hover;
5063: }
5064: table.LC_mail_list tr.LC_mail_other {
5065: background-color: $mail_other;
5066: }
5067: table.LC_mail_list tr.LC_mail_other:hover {
5068: background-color: $mail_other_hover;
5069: }
5070: table.LC_mail_list tr.LC_mail_even {
5071: }
5072: table.LC_mail_list tr.LC_mail_odd {
5073: }
5074:
5075:
5076: table#LC_portfolio_actions {
5077: width: auto;
5078: background: $pgbg;
5079: border: none;
5080: border-spacing: 2px 2px;
5081: padding: 0;
5082: margin: 0;
5083: border-collapse: separate;
5084: }
5085: table#LC_portfolio_actions td.LC_label {
5086: background: $tabbg;
5087: text-align: right;
5088: }
5089: table#LC_portfolio_actions td.LC_value {
5090: background: $tabbg;
5091: }
5092:
5093: table#LC_cstr_controls {
5094: width: 100%;
5095: border-collapse: collapse;
5096: }
5097: table#LC_cstr_controls tr td {
5098: border: 4px solid $pgbg;
5099: padding: 4px;
5100: text-align: center;
5101: background: $tabbg;
5102: }
5103: table#LC_cstr_controls tr th {
5104: border: 4px solid $pgbg;
5105: background: $table_header;
5106: text-align: center;
5107: font-family: $sans;
5108: font-size: smaller;
5109: }
5110:
5111: table#LC_browser {
5112:
5113: }
5114: table#LC_browser tr th {
5115: background: $table_header;
5116: }
5117: table#LC_browser tr td {
5118: padding: 2px;
5119: }
5120: table#LC_browser tr.LC_browser_file,
5121: table#LC_browser tr.LC_browser_file_published {
5122: background: #CCFF88;
5123: }
5124: table#LC_browser tr.LC_browser_file_locked,
5125: table#LC_browser tr.LC_browser_file_unpublished {
5126: background: #FFAA99;
5127: }
5128: table#LC_browser tr.LC_browser_file_obsolete {
5129: background: #AAAAAA;
5130: }
5131: table#LC_browser tr.LC_browser_file_modified,
5132: table#LC_browser tr.LC_browser_file_metamodified {
5133: background: #FFFF77;
5134: }
5135: table#LC_browser tr.LC_browser_folder {
5136: background: #CCCCFF;
5137: }
5138:
5139: table.LC_data_table tr > td.LC_roles_is {
5140: /* background: #77FF77; */
5141: }
5142: table.LC_data_table tr > td.LC_roles_future {
5143: background: #FFFF77;
5144: }
5145: table.LC_data_table tr > td.LC_roles_will {
5146: background: #FFAA77;
5147: }
5148: table.LC_data_table tr > td.LC_roles_expired {
5149: background: #FF7777;
5150: }
5151: table.LC_data_table tr > td.LC_roles_will_not {
5152: background: #AAFF77;
5153: }
5154: table.LC_data_table tr > td.LC_roles_selected {
5155: background: #11CC55;
5156: }
5157:
5158: span.LC_current_location {
5159: font-size: x-large;
5160: background: $pgbg;
5161: }
5162:
5163: span.LC_parm_menu_item {
5164: font-size: larger;
5165: font-family: $sans;
5166: }
5167: span.LC_parm_scope_all {
5168: color: red;
5169: }
5170: span.LC_parm_scope_folder {
5171: color: green;
5172: }
5173: span.LC_parm_scope_resource {
5174: color: orange;
5175: }
5176: span.LC_parm_part {
5177: color: blue;
5178: }
5179: span.LC_parm_folder, span.LC_parm_symb {
5180: font-size: x-small;
5181: font-family: $mono;
5182: color: #AAAAAA;
5183: }
5184:
5185: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
5186: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
5187: border: 1px solid black;
5188: border-collapse: collapse;
5189: }
5190: table.LC_parm_overview_restrictions td {
5191: border-width: 1px 4px 1px 4px;
5192: border-style: solid;
5193: border-color: $pgbg;
5194: text-align: center;
5195: }
5196: table.LC_parm_overview_restrictions th {
5197: background: $tabbg;
5198: border-width: 1px 4px 1px 4px;
5199: border-style: solid;
5200: border-color: $pgbg;
5201: }
5202: table#LC_helpmenu {
5203: border: none;
5204: height: 55px;
5205: border-spacing: 0;
5206: }
5207:
5208: table#LC_helpmenu fieldset legend {
5209: font-size: larger;
5210: font-weight: bold;
5211: }
5212: table#LC_helpmenu_links {
5213: width: 100%;
5214: border: 1px solid black;
5215: background: $pgbg;
5216: padding: 0;
5217: border-spacing: 1px;
5218: }
5219: table#LC_helpmenu_links tr td {
5220: padding: 1px;
5221: background: $tabbg;
5222: text-align: center;
5223: font-weight: bold;
5224: }
5225:
5226: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
5227: table#LC_helpmenu_links a:active {
5228: text-decoration: none;
5229: color: $font;
5230: }
5231: table#LC_helpmenu_links a:hover {
5232: text-decoration: underline;
5233: color: $vlink;
5234: }
5235:
5236: .LC_chrt_popup_exists {
5237: border: 1px solid #339933;
5238: margin: -1px;
5239: }
5240: .LC_chrt_popup_up {
5241: border: 1px solid yellow;
5242: margin: -1px;
5243: }
5244: .LC_chrt_popup {
5245: border: 1px solid #8888FF;
5246: background: #CCCCFF;
5247: }
5248: table.LC_pick_box {
5249: border-collapse: separate;
5250: background: white;
5251: border: 1px solid black;
5252: border-spacing: 1px;
5253: }
5254: table.LC_pick_box td.LC_pick_box_title {
5255: background: $sidebg;
5256: font-weight: bold;
5257: text-align: right;
5258: vertical-align: top;
5259: width: 184px;
5260: padding: 8px;
5261: }
5262: table.LC_pick_box td.LC_selfenroll_pick_box_title {
5263: background: $sidebg;
5264: font-weight: bold;
5265: text-align: right;
5266: width: 350px;
5267: padding: 8px;
5268: }
5269:
5270: table.LC_pick_box td.LC_pick_box_value {
5271: text-align: left;
5272: padding: 8px;
5273: }
5274: table.LC_pick_box td.LC_pick_box_select {
5275: text-align: left;
5276: padding: 8px;
5277: }
5278: table.LC_pick_box td.LC_pick_box_separator {
5279: padding: 0;
5280: height: 1px;
5281: background: black;
5282: }
5283: table.LC_pick_box td.LC_pick_box_submit {
5284: text-align: right;
5285: }
5286: table.LC_pick_box td.LC_evenrow_value {
5287: text-align: left;
5288: padding: 8px;
5289: background-color: $data_table_light;
5290: }
5291: table.LC_pick_box td.LC_oddrow_value {
5292: text-align: left;
5293: padding: 8px;
5294: background-color: $data_table_light;
5295: }
5296: table.LC_helpform_receipt {
5297: width: 620px;
5298: border-collapse: separate;
5299: background: white;
5300: border: 1px solid black;
5301: border-spacing: 1px;
5302: }
5303: table.LC_helpform_receipt td.LC_pick_box_title {
5304: background: $tabbg;
5305: font-weight: bold;
5306: text-align: right;
5307: width: 184px;
5308: padding: 8px;
5309: }
5310: table.LC_helpform_receipt td.LC_evenrow_value {
5311: text-align: left;
5312: padding: 8px;
5313: background-color: $data_table_light;
5314: }
5315: table.LC_helpform_receipt td.LC_oddrow_value {
5316: text-align: left;
5317: padding: 8px;
5318: background-color: $data_table_light;
5319: }
5320: table.LC_helpform_receipt td.LC_pick_box_separator {
5321: padding: 0;
5322: height: 1px;
5323: background: black;
5324: }
5325: span.LC_helpform_receipt_cat {
5326: font-weight: bold;
5327: }
5328: table.LC_group_priv_box {
5329: background: white;
5330: border: 1px solid black;
5331: border-spacing: 1px;
5332: }
5333: table.LC_group_priv_box td.LC_pick_box_title {
5334: background: $tabbg;
5335: font-weight: bold;
5336: text-align: right;
5337: width: 184px;
5338: }
5339: table.LC_group_priv_box td.LC_groups_fixed {
5340: background: $data_table_light;
5341: text-align: center;
5342: }
5343: table.LC_group_priv_box td.LC_groups_optional {
5344: background: $data_table_dark;
5345: text-align: center;
5346: }
5347: table.LC_group_priv_box td.LC_groups_functionality {
5348: background: $data_table_darker;
5349: text-align: center;
5350: font-weight: bold;
5351: }
5352: table.LC_group_priv td {
5353: text-align: left;
5354: padding: 0;
5355: }
5356:
5357: table.LC_notify_front_page {
5358: background: white;
5359: border: 1px solid black;
5360: padding: 8px;
5361: }
5362: table.LC_notify_front_page td {
5363: padding: 8px;
5364: }
5365: .LC_navbuttons {
5366: margin: 2ex 0ex 2ex 0ex;
5367: }
5368: .LC_topic_bar {
5369: font-family: $sans;
5370: font-weight: bold;
5371: width: 100%;
5372: background: $tabbg;
5373: vertical-align: middle;
5374: margin: 2ex 0ex 2ex 0ex;
5375: padding: 3px;
5376: }
5377: .LC_topic_bar span {
5378: vertical-align: middle;
5379: }
5380: .LC_topic_bar img {
5381: vertical-align: bottom;
5382: }
5383: table.LC_course_group_status {
5384: margin: 20px;
5385: }
5386: table.LC_status_selector td {
5387: vertical-align: top;
5388: text-align: center;
5389: padding: 4px;
5390: }
5391: table.LC_descriptive_input td.LC_description {
5392: vertical-align: top;
5393: text-align: right;
5394: font-weight: bold;
5395: }
5396: div.LC_feedback_link {
5397: clear: both;
5398: background: white;
5399: width: 100%;
5400: }
5401: span.LC_feedback_link {
5402: background: $feedback_link_bg;
5403: font-size: larger;
5404: }
5405: span.LC_message_link {
5406: background: $feedback_link_bg;
5407: font-size: larger;
5408: position: absolute;
5409: right: 1em;
5410: }
5411:
5412: table.LC_prior_tries {
5413: border: 1px solid #000000;
5414: border-collapse: separate;
5415: border-spacing: 1px;
5416: }
5417:
5418: table.LC_prior_tries td {
5419: padding: 2px;
5420: }
5421:
5422: .LC_answer_correct {
5423: background: #AAFFAA;
5424: color: black;
5425: }
5426: .LC_answer_charged_try {
5427: background: #FFAAAA ! important;
5428: color: black;
5429: }
5430: .LC_answer_not_charged_try,
5431: .LC_answer_no_grade,
5432: .LC_answer_late {
5433: background: #FFFFAA;
5434: color: black;
5435: }
5436: .LC_answer_previous {
5437: background: #AAAAFF;
5438: color: black;
5439: }
5440: .LC_answer_no_message {
5441: background: #FFFFFF;
5442: color: black;
5443: }
5444: .LC_answer_unknown {
5445: background: orange;
5446: color: black;
5447: }
5448:
5449:
5450: span.LC_prior_numerical,
5451: span.LC_prior_string,
5452: span.LC_prior_custom,
5453: span.LC_prior_reaction,
5454: span.LC_prior_math {
5455: font-family: monospace;
5456: white-space: pre;
5457: }
5458:
5459: span.LC_prior_string {
5460: font-family: monospace;
5461: white-space: pre;
5462: }
5463:
5464: table.LC_prior_option {
5465: width: 100%;
5466: border-collapse: collapse;
5467: }
5468: table.LC_prior_rank, table.LC_prior_match {
5469: border-collapse: collapse;
5470: }
5471: table.LC_prior_option tr td,
5472: table.LC_prior_rank tr td,
5473: table.LC_prior_match tr td {
5474: border: 1px solid #000000;
5475: }
5476:
5477: span.LC_nobreak {
5478: white-space: nowrap;
5479: }
5480:
5481: span.LC_cusr_emph {
5482: font-style: italic;
5483: }
5484:
5485: span.LC_cusr_subheading {
5486: font-weight: normal;
5487: font-size: 85%;
5488: }
5489:
5490: table.LC_docs_documents {
5491: background: #BBBBBB;
5492: border-width: 0;
5493: border-collapse: collapse;
5494: }
5495:
5496: table.LC_docs_documents td.LC_docs_document {
5497: border: 2px solid black;
5498: padding: 4px;
5499: }
5500:
5501: .LC_docs_course_commands div {
5502: float: left;
5503: border: 4px solid #AAAAAA;
5504: padding: 4px;
5505: background: #DDDDCC;
5506: }
5507:
5508: .LC_docs_entry_move {
5509: border: none;
5510: border-collapse: collapse;
5511: }
5512:
5513: .LC_docs_entry_move td {
5514: border: 2px solid #BBBBBB;
5515: background: #DDDDDD;
5516: }
5517:
5518: .LC_docs_editor td.LC_docs_entry_commands {
5519: background: #DDDDDD;
5520: font-size: x-small;
5521: }
5522: .LC_docs_copy {
5523: color: #000099;
5524: }
5525: .LC_docs_cut {
5526: color: #550044;
5527: }
5528: .LC_docs_rename {
5529: color: #009900;
5530: }
5531: .LC_docs_remove {
5532: color: #990000;
5533: }
5534:
5535: .LC_docs_reinit_warn,
5536: .LC_docs_ext_edit {
5537: font-size: x-small;
5538: }
5539:
5540: .LC_docs_editor td.LC_docs_entry_title,
5541: .LC_docs_editor td.LC_docs_entry_icon {
5542: background: #FFFFBB;
5543: }
5544: .LC_docs_editor td.LC_docs_entry_parameter {
5545: background: #BBBBFF;
5546: font-size: x-small;
5547: white-space: nowrap;
5548: }
5549:
5550: table.LC_docs_adddocs td,
5551: table.LC_docs_adddocs th {
5552: border: 1px solid #BBBBBB;
5553: padding: 4px;
5554: background: #DDDDDD;
5555: }
5556:
5557: table.LC_sty_begin {
5558: background: #BBFFBB;
5559: }
5560: table.LC_sty_end {
5561: background: #FFBBBB;
5562: }
5563:
5564: table.LC_double_column {
5565: border-width: 0;
5566: border-collapse: collapse;
5567: width: 100%;
5568: padding: 2px;
5569: }
5570:
5571: table.LC_double_column tr td.LC_left_col {
5572: top: 2px;
5573: left: 2px;
5574: width: 47%;
5575: vertical-align: top;
5576: }
5577:
5578: table.LC_double_column tr td.LC_right_col {
5579: top: 2px;
5580: right: 2px;
5581: width: 47%;
5582: vertical-align: top;
5583: }
5584:
5585: span.LC_role_level {
5586: font-weight: bold;
5587: }
5588:
5589: div.LC_left_float {
5590: float: left;
5591: padding-right: 5%;
5592: padding-bottom: 4px;
5593: }
5594:
5595: div.LC_clear_float_header {
5596: padding-bottom: 2px;
5597: }
5598:
5599: div.LC_clear_float_footer {
5600: padding-top: 10px;
5601: clear: both;
5602: }
5603:
5604:
5605: div.LC_grade_select_mode {
5606: font-family: $sans;
5607: }
5608: div.LC_grade_select_mode div div {
5609: margin: 5px;
5610: }
5611: div.LC_grade_select_mode_selector {
5612: margin: 5px;
5613: float: left;
5614: }
5615: div.LC_grade_select_mode_selector_header {
5616: font: bold medium $sans;
5617: }
5618: div.LC_grade_select_mode_type {
5619: clear: left;
5620: }
5621:
5622: div.LC_grade_show_user {
5623: margin-top: 20px;
5624: border: 1px solid black;
5625: }
5626: div.LC_grade_user_name {
5627: background: #DDDDEE;
5628: border-bottom: 1px solid black;
5629: font: bold large $sans;
5630: }
5631: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5632: background: #DDEEDD;
5633: }
5634:
5635: div.LC_grade_show_problem,
5636: div.LC_grade_submissions,
5637: div.LC_grade_message_center,
5638: div.LC_grade_info_links,
5639: div.LC_grade_assign {
5640: margin: 5px;
5641: width: 99%;
5642: background: #FFFFFF;
5643: }
5644: div.LC_grade_show_problem_header,
5645: div.LC_grade_submissions_header,
5646: div.LC_grade_message_center_header,
5647: div.LC_grade_assign_header {
5648: font: bold large $sans;
5649: }
5650: div.LC_grade_show_problem_problem,
5651: div.LC_grade_submissions_body,
5652: div.LC_grade_message_center_body,
5653: div.LC_grade_assign_body {
5654: border: 1px solid black;
5655: width: 99%;
5656: background: #FFFFFF;
5657: }
5658: span.LC_grade_check_note {
5659: font: normal medium $sans;
5660: display: inline;
5661: position: absolute;
5662: right: 1em;
5663: }
5664:
5665: table.LC_scantron_action {
5666: width: 100%;
5667: }
5668: table.LC_scantron_action tr th {
5669: font: normal bold $sans;
5670: }
5671:
5672: div.LC_edit_problem_header,
5673: div.LC_edit_problem_footer {
5674: font: normal medium $sans;
5675: margin: 2px;
5676: }
5677: div.LC_edit_problem_header,
5678: div.LC_edit_problem_header div,
5679: div.LC_edit_problem_footer,
5680: div.LC_edit_problem_footer div,
5681: div.LC_edit_problem_editxml_header,
5682: div.LC_edit_problem_editxml_header div {
5683: margin-top: 5px;
5684: }
5685: div.LC_edit_problem_header_edit_row {
5686: background: $tabbg;
5687: padding: 3px;
5688: margin-bottom: 5px;
5689: }
5690: div.LC_edit_problem_header_title {
5691: font: larger bold $sans;
5692: background: $tabbg;
5693: padding: 3px;
5694: }
5695: table.LC_edit_problem_header_title {
5696: font: larger bold $sans;
5697: width: 100%;
5698: border-color: $pgbg;
5699: border-style: solid;
5700: border-width: $border;
5701:
5702: background: $tabbg;
5703: border-collapse: collapse;
5704: padding: 0;
5705: }
5706:
5707: div.LC_edit_problem_discards {
5708: float: left;
5709: padding-bottom: 5px;
5710: }
5711: div.LC_edit_problem_saves {
5712: float: right;
5713: padding-bottom: 5px;
5714: }
5715: hr.LC_edit_problem_divide {
5716: clear: both;
5717: color: $tabbg;
5718: background-color: $tabbg;
5719: height: 3px;
5720: border: none;
5721: }
5722: img.stift{
5723: border-width:0;
5724: vertical-align:middle;
5725: }
5726:
5727: table#LC_mainmenu{
5728: margin-top:10px;
5729: width:80%;
5730:
5731: }
5732:
5733: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5734: vertical-align: top;
5735: width: 45%;
5736: }
5737: .LC_mainmenu_fieldset_category {
5738: color: $font;
5739: background: $pgbg;
5740: font-family: $sans;
5741: font-size: small;
5742: font-weight: bold;
5743: }
5744: fieldset#LC_mainmenu_fieldset {
5745: margin:0 10px 10px 0;
5746:
5747: }
5748:
5749: div.LC_createcourse {
5750: margin: 10px 10px 10px 10px;
5751: }
5752:
5753: END
5754: }
5755:
5756: =pod
5757:
5758: =item * &headtag()
5759:
5760: Returns a uniform footer for LON-CAPA web pages.
5761:
5762: Inputs: $title - optional title for the head
5763: $head_extra - optional extra HTML to put inside the <head>
5764: $args - optional arguments
5765: force_register - if is true call registerurl so the remote is
5766: informed
5767: redirect -> array ref of
5768: 1- seconds before redirect occurs
5769: 2- url to redirect to
5770: 3- whether the side effect should occur
5771: (side effect of setting
5772: $env{'internal.head.redirect'} to the url
5773: redirected too)
5774: domain -> force to color decorate a page for a specific
5775: domain
5776: function -> force usage of a specific rolish color scheme
5777: bgcolor -> override the default page bgcolor
5778: no_auto_mt_title
5779: -> prevent &mt()ing the title arg
5780:
5781: =cut
5782:
5783: sub headtag {
5784: my ($title,$head_extra,$args) = @_;
5785:
5786: my $function = $args->{'function'} || &get_users_function();
5787: my $domain = $args->{'domain'} || &determinedomain();
5788: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5789: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5790: $Apache::lonnet::perlvar{'lonVersion'},
5791: #time(),
5792: $env{'environment.color.timestamp'},
5793: $function,$domain,$bgcolor);
5794:
5795: $url = '/adm/css/'.&escape($url).'.css';
5796:
5797: my $result =
5798: '<head>'.
5799: &font_settings();
5800:
5801: if (!$args->{'frameset'}) {
5802: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5803: }
5804: if ($args->{'force_register'}) {
5805: $result .= &Apache::lonmenu::registerurl(1);
5806: }
5807: if (!$args->{'no_nav_bar'}
5808: && !$args->{'only_body'}
5809: && !$args->{'frameset'}) {
5810: $result .= &help_menu_js();
5811: }
5812:
5813: if (ref($args->{'redirect'})) {
5814: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5815: $url = &Apache::lonenc::check_encrypt($url);
5816: if (!$inhibit_continue) {
5817: $env{'internal.head.redirect'} = $url;
5818: }
5819: $result.=<<ADDMETA
5820: <meta http-equiv="pragma" content="no-cache" />
5821: <meta http-equiv="Refresh" content="$time; url=$url" />
5822: ADDMETA
5823: }
5824: if (!defined($title)) {
5825: $title = 'The LearningOnline Network with CAPA';
5826: }
5827: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5828: $result .= '<title> LON-CAPA '.$title.'</title>'
5829: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5830: .$head_extra;
5831: return $result;
5832: }
5833:
5834: =pod
5835:
5836: =item * &font_settings()
5837:
5838: Returns neccessary <meta> to set the proper encoding
5839:
5840: Inputs: none
5841:
5842: =cut
5843:
5844: sub font_settings {
5845: my $headerstring='';
5846: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5847: $headerstring.=
5848: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5849: }
5850: return $headerstring;
5851: }
5852:
5853: =pod
5854:
5855: =item * &xml_begin()
5856:
5857: Returns the needed doctype and <html>
5858:
5859: Inputs: none
5860:
5861: =cut
5862:
5863: sub xml_begin {
5864: my $output='';
5865:
5866: if ($env{'internal.start_page'}==1) {
5867: &Apache::lonhtmlcommon::init_htmlareafields();
5868: }
5869:
5870: if ($env{'browser.mathml'}) {
5871: $output='<?xml version="1.0"?>'
5872: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5873: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5874:
5875: # .'<!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">] >'
5876: .'<!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">'
5877: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5878: .'xmlns="http://www.w3.org/1999/xhtml">';
5879: } else {
5880: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
5881: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
5882: }
5883: return $output;
5884: }
5885:
5886: =pod
5887:
5888: =item * &endheadtag()
5889:
5890: Returns a uniform </head> for LON-CAPA web pages.
5891:
5892: Inputs: none
5893:
5894: =cut
5895:
5896: sub endheadtag {
5897: return '</head>';
5898: }
5899:
5900: =pod
5901:
5902: =item * &head()
5903:
5904: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
5905:
5906: Inputs:
5907:
5908: =over 4
5909:
5910: $title - optional title for the page
5911:
5912: $head_extra - optional extra HTML to put inside the <head>
5913:
5914: =back
5915:
5916: =cut
5917:
5918: sub head {
5919: my ($title,$head_extra,$args) = @_;
5920: return &headtag($title,$head_extra,$args).&endheadtag();
5921: }
5922:
5923: =pod
5924:
5925: =item * &start_page()
5926:
5927: Returns a complete <html> .. <body> section for LON-CAPA web pages.
5928:
5929: Inputs:
5930:
5931: =over 4
5932:
5933: $title - optional title for the page
5934:
5935: $head_extra - optional extra HTML to incude inside the <head>
5936:
5937: $args - additional optional args supported are:
5938:
5939: =over 8
5940:
5941: only_body -> is true will set &bodytag() onlybodytag
5942: arg on
5943: no_nav_bar -> is true will set &bodytag() notopbar arg on
5944: add_entries -> additional attributes to add to the <body>
5945: domain -> force to color decorate a page for a
5946: specific domain
5947: function -> force usage of a specific rolish color
5948: scheme
5949: redirect -> see &headtag()
5950: bgcolor -> override the default page bg color
5951: js_ready -> return a string ready for being used in
5952: a javascript writeln
5953: html_encode -> return a string ready for being used in
5954: a html attribute
5955: force_register -> if is true will turn on the &bodytag()
5956: $forcereg arg
5957: body_title -> alternate text to use instead of $title
5958: in the title box that appears, this text
5959: is not auto translated like the $title is
5960: frameset -> if true will start with a <frameset>
5961: rather than <body>
5962: no_title -> if true the title bar won't be shown
5963: skip_phases -> hash ref of
5964: head -> skip the <html><head> generation
5965: body -> skip all <body> generation
5966: no_inline_link -> if true and in remote mode, don't show the
5967: 'Switch To Inline Menu' link
5968: no_auto_mt_title -> prevent &mt()ing the title arg
5969: inherit_jsmath -> when creating popup window in a page,
5970: should it have jsmath forced on by the
5971: current page
5972:
5973: =back
5974:
5975: =back
5976:
5977: =cut
5978:
5979: sub start_page {
5980: my ($title,$head_extra,$args) = @_;
5981: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
5982: my %head_args;
5983: foreach my $arg ('redirect','force_register','domain','function',
5984: 'bgcolor','frameset','no_nav_bar','only_body',
5985: 'no_auto_mt_title') {
5986: if (defined($args->{$arg})) {
5987: $head_args{$arg} = $args->{$arg};
5988: }
5989: }
5990:
5991: $env{'internal.start_page'}++;
5992: my $result;
5993: if (! exists($args->{'skip_phases'}{'head'}) ) {
5994: $result.=
5995: &xml_begin().
5996: &headtag($title,$head_extra,\%head_args).&endheadtag();
5997: }
5998:
5999: if (! exists($args->{'skip_phases'}{'body'}) ) {
6000: if ($args->{'frameset'}) {
6001: my $attr_string = &make_attr_string($args->{'force_register'},
6002: $args->{'add_entries'});
6003: $result .= "\n<frameset $attr_string>\n";
6004: } else {
6005: $result .=
6006: &bodytag($title,
6007: $args->{'function'}, $args->{'add_entries'},
6008: $args->{'only_body'}, $args->{'domain'},
6009: $args->{'force_register'}, $args->{'body_title'},
6010: $args->{'no_nav_bar'}, $args->{'bgcolor'},
6011: $args->{'no_title'}, $args->{'no_inline_link'},
6012: $args);
6013: }
6014: }
6015:
6016: if ($args->{'js_ready'}) {
6017: $result = &js_ready($result);
6018: }
6019: if ($args->{'html_encode'}) {
6020: $result = &html_encode($result);
6021: }
6022: #Breadcrumbs
6023: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
6024: &Apache::lonhtmlcommon::clear_breadcrumbs();
6025: #if any br links exists, add them to the breadcrumbs
6026: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6027: foreach my $crumb (@{$args->{'bread_crumbs'}}){
6028: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
6029: }
6030: }
6031:
6032: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
6033: if (exists($args->{'bread_crumbs_component'})){
6034: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
6035: } else {
6036: $result .= &Apache::lonhtmlcommon::breadcrumbs();
6037: }
6038: }
6039: return $result;
6040: }
6041:
6042: =pod
6043:
6044: =item * &head()
6045:
6046: Returns a complete </body></html> section for LON-CAPA web pages.
6047:
6048: Inputs: $args - additional optional args supported are:
6049: js_ready -> return a string ready for being used in
6050: a javascript writeln
6051: html_encode -> return a string ready for being used in
6052: a html attribute
6053: frameset -> if true will start with a <frameset>
6054: rather than <body>
6055: dicsussion -> if true will get discussion from
6056: lonxml::xmlend
6057: (you can pass the target and parser arguments
6058: through optional 'target' and 'parser' args
6059: to this routine)
6060:
6061: =cut
6062:
6063: sub end_page {
6064: my ($args) = @_;
6065: $env{'internal.end_page'}++;
6066: my $result;
6067: if ($args->{'discussion'}) {
6068: my ($target,$parser);
6069: if (ref($args->{'discussion'})) {
6070: ($target,$parser) =($args->{'discussion'}{'target'},
6071: $args->{'discussion'}{'parser'});
6072: }
6073: $result .= &Apache::lonxml::xmlend($target,$parser);
6074: }
6075:
6076: if ($args->{'frameset'}) {
6077: $result .= '</frameset>';
6078: } else {
6079: $result .= &endbodytag($args);
6080: }
6081: $result .= "\n</html>";
6082:
6083: if ($args->{'js_ready'}) {
6084: $result = &js_ready($result);
6085: }
6086:
6087: if ($args->{'html_encode'}) {
6088: $result = &html_encode($result);
6089: }
6090:
6091: return $result;
6092: }
6093:
6094: sub html_encode {
6095: my ($result) = @_;
6096:
6097: $result = &HTML::Entities::encode($result,'<>&"');
6098:
6099: return $result;
6100: }
6101: sub js_ready {
6102: my ($result) = @_;
6103:
6104: $result =~ s/[\n\r]/ /xmsg;
6105: $result =~ s/\\/\\\\/xmsg;
6106: $result =~ s/'/\\'/xmsg;
6107: $result =~ s{</}{<\\/}xmsg;
6108:
6109: return $result;
6110: }
6111:
6112: sub validate_page {
6113: if ( exists($env{'internal.start_page'})
6114: && $env{'internal.start_page'} > 1) {
6115: &Apache::lonnet::logthis('start_page called multiple times '.
6116: $env{'internal.start_page'}.' '.
6117: $ENV{'request.filename'});
6118: }
6119: if ( exists($env{'internal.end_page'})
6120: && $env{'internal.end_page'} > 1) {
6121: &Apache::lonnet::logthis('end_page called multiple times '.
6122: $env{'internal.end_page'}.' '.
6123: $env{'request.filename'});
6124: }
6125: if ( exists($env{'internal.start_page'})
6126: && ! exists($env{'internal.end_page'})) {
6127: &Apache::lonnet::logthis('start_page called without end_page '.
6128: $env{'request.filename'});
6129: }
6130: if ( ! exists($env{'internal.start_page'})
6131: && exists($env{'internal.end_page'})) {
6132: &Apache::lonnet::logthis('end_page called without start_page'.
6133: $env{'request.filename'});
6134: }
6135: }
6136:
6137: sub simple_error_page {
6138: my ($r,$title,$msg) = @_;
6139: my $page =
6140: &Apache::loncommon::start_page($title).
6141: &mt($msg).
6142: &Apache::loncommon::end_page();
6143: if (ref($r)) {
6144: $r->print($page);
6145: return;
6146: }
6147: return $page;
6148: }
6149:
6150: {
6151: my @row_count;
6152: sub start_data_table {
6153: my ($add_class) = @_;
6154: my $css_class = (join(' ','LC_data_table',$add_class));
6155: unshift(@row_count,0);
6156: return '<table class="'.$css_class.'">'."\n";
6157: }
6158:
6159: sub end_data_table {
6160: shift(@row_count);
6161: return '</table>'."\n";;
6162: }
6163:
6164: sub start_data_table_row {
6165: my ($add_class) = @_;
6166: $row_count[0]++;
6167: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6168: $css_class = (join(' ',$css_class,$add_class));
6169: return '<tr class="'.$css_class.'">'."\n";;
6170: }
6171:
6172: sub continue_data_table_row {
6173: my ($add_class) = @_;
6174: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6175: $css_class = (join(' ',$css_class,$add_class));
6176: return '<tr class="'.$css_class.'">'."\n";;
6177: }
6178:
6179: sub end_data_table_row {
6180: return '</tr>'."\n";;
6181: }
6182:
6183: sub start_data_table_empty_row {
6184: $row_count[0]++;
6185: return '<tr class="LC_empty_row" >'."\n";;
6186: }
6187:
6188: sub end_data_table_empty_row {
6189: return '</tr>'."\n";;
6190: }
6191:
6192: sub start_data_table_header_row {
6193: return '<tr class="LC_header_row">'."\n";;
6194: }
6195:
6196: sub end_data_table_header_row {
6197: return '</tr>'."\n";;
6198: }
6199: }
6200:
6201: =pod
6202:
6203: =item * &inhibit_menu_check($arg)
6204:
6205: Checks for a inhibitmenu state and generates output to preserve it
6206:
6207: Inputs: $arg - can be any of
6208: - undef - in which case the return value is a string
6209: to add into arguments list of a uri
6210: - 'input' - in which case the return value is a HTML
6211: <form> <input> field of type hidden to
6212: preserve the value
6213: - a url - in which case the return value is the url with
6214: the neccesary cgi args added to preserve the
6215: inhibitmenu state
6216: - a ref to a url - no return value, but the string is
6217: updated to include the neccessary cgi
6218: args to preserve the inhibitmenu state
6219:
6220: =cut
6221:
6222: sub inhibit_menu_check {
6223: my ($arg) = @_;
6224: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6225: if ($arg eq 'input') {
6226: if ($env{'form.inhibitmenu'}) {
6227: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6228: } else {
6229: return
6230: }
6231: }
6232: if ($env{'form.inhibitmenu'}) {
6233: if (ref($arg)) {
6234: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6235: } elsif ($arg eq '') {
6236: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6237: } else {
6238: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6239: }
6240: }
6241: if (!ref($arg)) {
6242: return $arg;
6243: }
6244: }
6245:
6246: ###############################################
6247:
6248: =pod
6249:
6250: =back
6251:
6252: =head1 User Information Routines
6253:
6254: =over 4
6255:
6256: =item * &get_users_function()
6257:
6258: Used by &bodytag to determine the current users primary role.
6259: Returns either 'student','coordinator','admin', or 'author'.
6260:
6261: =cut
6262:
6263: ###############################################
6264: sub get_users_function {
6265: my $function = 'student';
6266: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
6267: $function='coordinator';
6268: }
6269: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6270: $function='admin';
6271: }
6272: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
6273: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6274: $function='author';
6275: }
6276: return $function;
6277: }
6278:
6279: ###############################################
6280:
6281: =pod
6282:
6283: =item * &show_course()
6284:
6285: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
6286: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
6287: Inputs:
6288: None
6289:
6290: Outputs:
6291: Scalar: 1 if 'Course' to be used, 0 otherwise.
6292:
6293: =cut
6294:
6295: ###############################################
6296: sub show_course {
6297: my $course = !$env{'user.adv'};
6298: if (!$env{'user.adv'}) {
6299: foreach my $env (keys(%env)) {
6300: next if ($env !~ m/^user\.priv\./);
6301: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
6302: $course = 0;
6303: last;
6304: }
6305: }
6306: }
6307: return $course;
6308: }
6309:
6310: ###############################################
6311:
6312: =pod
6313:
6314: =item * &check_user_status()
6315:
6316: Determines current status of supplied role for a
6317: specific user. Roles can be active, previous or future.
6318:
6319: Inputs:
6320: user's domain, user's username, course's domain,
6321: course's number, optional section ID.
6322:
6323: Outputs:
6324: role status: active, previous or future.
6325:
6326: =cut
6327:
6328: sub check_user_status {
6329: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6330: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6331: my @uroles = keys %userinfo;
6332: my $srchstr;
6333: my $active_chk = 'none';
6334: my $now = time;
6335: if (@uroles > 0) {
6336: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
6337: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6338: } else {
6339: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6340: }
6341: if (grep/^\Q$srchstr\E$/,@uroles) {
6342: my $role_end = 0;
6343: my $role_start = 0;
6344: $active_chk = 'active';
6345: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6346: $role_end = $1;
6347: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6348: $role_start = $1;
6349: }
6350: }
6351: if ($role_start > 0) {
6352: if ($now < $role_start) {
6353: $active_chk = 'future';
6354: }
6355: }
6356: if ($role_end > 0) {
6357: if ($now > $role_end) {
6358: $active_chk = 'previous';
6359: }
6360: }
6361: }
6362: }
6363: return $active_chk;
6364: }
6365:
6366: ###############################################
6367:
6368: =pod
6369:
6370: =item * &get_sections()
6371:
6372: Determines all the sections for a course including
6373: sections with students and sections containing other roles.
6374: Incoming parameters:
6375:
6376: 1. domain
6377: 2. course number
6378: 3. reference to array containing roles for which sections should
6379: be gathered (optional).
6380: 4. reference to array containing status types for which sections
6381: should be gathered (optional).
6382:
6383: If the third argument is undefined, sections are gathered for any role.
6384: If the fourth argument is undefined, sections are gathered for any status.
6385: Permissible values are 'active' or 'future' or 'previous'.
6386:
6387: Returns section hash (keys are section IDs, values are
6388: number of users in each section), subject to the
6389: optional roles filter, optional status filter
6390:
6391: =cut
6392:
6393: ###############################################
6394: sub get_sections {
6395: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6396: if (!defined($cdom) || !defined($cnum)) {
6397: my $cid = $env{'request.course.id'};
6398:
6399: return if (!defined($cid));
6400:
6401: $cdom = $env{'course.'.$cid.'.domain'};
6402: $cnum = $env{'course.'.$cid.'.num'};
6403: }
6404:
6405: my %sectioncount;
6406: my $now = time;
6407:
6408: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6409: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6410: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6411: my $status_index = &Apache::loncoursedata::CL_STATUS();
6412: my $start_index = &Apache::loncoursedata::CL_START();
6413: my $end_index = &Apache::loncoursedata::CL_END();
6414: my $status;
6415: while (my ($student,$data) = each(%$classlist)) {
6416: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6417: $data->[$status_index],
6418: $data->[$start_index],
6419: $data->[$end_index]);
6420: if ($stu_status eq 'Active') {
6421: $status = 'active';
6422: } elsif ($end < $now) {
6423: $status = 'previous';
6424: } elsif ($start > $now) {
6425: $status = 'future';
6426: }
6427: if ($section ne '-1' && $section !~ /^\s*$/) {
6428: if ((!defined($possible_status)) || (($status ne '') &&
6429: (grep/^\Q$status\E$/,@{$possible_status}))) {
6430: $sectioncount{$section}++;
6431: }
6432: }
6433: }
6434: }
6435: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6436: foreach my $user (sort(keys(%courseroles))) {
6437: if ($user !~ /^(\w{2})/) { next; }
6438: my ($role) = ($user =~ /^(\w{2})/);
6439: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6440: my ($section,$status);
6441: if ($role eq 'cr' &&
6442: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6443: $section=$1;
6444: }
6445: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6446: if (!defined($section) || $section eq '-1') { next; }
6447: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6448: if ($end == -1 && $start == -1) {
6449: next; #deleted role
6450: }
6451: if (!defined($possible_status)) {
6452: $sectioncount{$section}++;
6453: } else {
6454: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6455: $status = 'active';
6456: } elsif ($end < $now) {
6457: $status = 'future';
6458: } elsif ($start > $now) {
6459: $status = 'previous';
6460: }
6461: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6462: $sectioncount{$section}++;
6463: }
6464: }
6465: }
6466: return %sectioncount;
6467: }
6468:
6469: ###############################################
6470:
6471: =pod
6472:
6473: =item * &get_course_users()
6474:
6475: Retrieves usernames:domains for users in the specified course
6476: with specific role(s), and access status.
6477:
6478: Incoming parameters:
6479: 1. course domain
6480: 2. course number
6481: 3. access status: users must have - either active,
6482: previous, future, or all.
6483: 4. reference to array of permissible roles
6484: 5. reference to array of section restrictions (optional)
6485: 6. reference to results object (hash of hashes).
6486: 7. reference to optional userdata hash
6487: 8. reference to optional statushash
6488: 9. flag if privileged users (except those set to unhide in
6489: course settings) should be excluded
6490: Keys of top level results hash are roles.
6491: Keys of inner hashes are username:domain, with
6492: values set to access type.
6493: Optional userdata hash returns an array with arguments in the
6494: same order as loncoursedata::get_classlist() for student data.
6495:
6496: Optional statushash returns
6497:
6498: Entries for end, start, section and status are blank because
6499: of the possibility of multiple values for non-student roles.
6500:
6501: =cut
6502:
6503: ###############################################
6504:
6505: sub get_course_users {
6506: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6507: my %idx = ();
6508: my %seclists;
6509:
6510: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6511: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6512: $idx{end} = &Apache::loncoursedata::CL_END();
6513: $idx{start} = &Apache::loncoursedata::CL_START();
6514: $idx{id} = &Apache::loncoursedata::CL_ID();
6515: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6516: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6517: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6518:
6519: if (grep(/^st$/,@{$roles})) {
6520: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6521: my $now = time;
6522: foreach my $student (keys(%{$classlist})) {
6523: my $match = 0;
6524: my $secmatch = 0;
6525: my $section = $$classlist{$student}[$idx{section}];
6526: my $status = $$classlist{$student}[$idx{status}];
6527: if ($section eq '') {
6528: $section = 'none';
6529: }
6530: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6531: if (grep(/^all$/,@{$sections})) {
6532: $secmatch = 1;
6533: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6534: if (grep(/^none$/,@{$sections})) {
6535: $secmatch = 1;
6536: }
6537: } else {
6538: if (grep(/^\Q$section\E$/,@{$sections})) {
6539: $secmatch = 1;
6540: }
6541: }
6542: if (!$secmatch) {
6543: next;
6544: }
6545: }
6546: if (defined($$types{'active'})) {
6547: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6548: push(@{$$users{st}{$student}},'active');
6549: $match = 1;
6550: }
6551: }
6552: if (defined($$types{'previous'})) {
6553: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6554: push(@{$$users{st}{$student}},'previous');
6555: $match = 1;
6556: }
6557: }
6558: if (defined($$types{'future'})) {
6559: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6560: push(@{$$users{st}{$student}},'future');
6561: $match = 1;
6562: }
6563: }
6564: if ($match) {
6565: push(@{$seclists{$student}},$section);
6566: if (ref($userdata) eq 'HASH') {
6567: $$userdata{$student} = $$classlist{$student};
6568: }
6569: if (ref($statushash) eq 'HASH') {
6570: $statushash->{$student}{'st'}{$section} = $status;
6571: }
6572: }
6573: }
6574: }
6575: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6576: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6577: my $now = time;
6578: my %displaystatus = ( previous => 'Expired',
6579: active => 'Active',
6580: future => 'Future',
6581: );
6582: my %nothide;
6583: if ($hidepriv) {
6584: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6585: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6586: if ($user !~ /:/) {
6587: $nothide{join(':',split(/[\@]/,$user))}=1;
6588: } else {
6589: $nothide{$user} = 1;
6590: }
6591: }
6592: }
6593: foreach my $person (sort(keys(%coursepersonnel))) {
6594: my $match = 0;
6595: my $secmatch = 0;
6596: my $status;
6597: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6598: $user =~ s/:$//;
6599: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6600: if ($end == -1 || $start == -1) {
6601: next;
6602: }
6603: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6604: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6605: my ($uname,$udom) = split(/:/,$user);
6606: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6607: if (grep(/^all$/,@{$sections})) {
6608: $secmatch = 1;
6609: } elsif ($usec eq '') {
6610: if (grep(/^none$/,@{$sections})) {
6611: $secmatch = 1;
6612: }
6613: } else {
6614: if (grep(/^\Q$usec\E$/,@{$sections})) {
6615: $secmatch = 1;
6616: }
6617: }
6618: if (!$secmatch) {
6619: next;
6620: }
6621: }
6622: if ($usec eq '') {
6623: $usec = 'none';
6624: }
6625: if ($uname ne '' && $udom ne '') {
6626: if ($hidepriv) {
6627: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6628: (!$nothide{$uname.':'.$udom})) {
6629: next;
6630: }
6631: }
6632: if ($end > 0 && $end < $now) {
6633: $status = 'previous';
6634: } elsif ($start > $now) {
6635: $status = 'future';
6636: } else {
6637: $status = 'active';
6638: }
6639: foreach my $type (keys(%{$types})) {
6640: if ($status eq $type) {
6641: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6642: push(@{$$users{$role}{$user}},$type);
6643: }
6644: $match = 1;
6645: }
6646: }
6647: if (($match) && (ref($userdata) eq 'HASH')) {
6648: if (!exists($$userdata{$uname.':'.$udom})) {
6649: &get_user_info($udom,$uname,\%idx,$userdata);
6650: }
6651: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6652: push(@{$seclists{$uname.':'.$udom}},$usec);
6653: }
6654: if (ref($statushash) eq 'HASH') {
6655: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6656: }
6657: }
6658: }
6659: }
6660: }
6661: if (grep(/^ow$/,@{$roles})) {
6662: if ((defined($cdom)) && (defined($cnum))) {
6663: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6664: if ( defined($csettings{'internal.courseowner'}) ) {
6665: my $owner = $csettings{'internal.courseowner'};
6666: next if ($owner eq '');
6667: my ($ownername,$ownerdom);
6668: if ($owner =~ /^([^:]+):([^:]+)$/) {
6669: $ownername = $1;
6670: $ownerdom = $2;
6671: } else {
6672: $ownername = $owner;
6673: $ownerdom = $cdom;
6674: $owner = $ownername.':'.$ownerdom;
6675: }
6676: @{$$users{'ow'}{$owner}} = 'any';
6677: if (defined($userdata) &&
6678: !exists($$userdata{$owner})) {
6679: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6680: if (!grep(/^none$/,@{$seclists{$owner}})) {
6681: push(@{$seclists{$owner}},'none');
6682: }
6683: if (ref($statushash) eq 'HASH') {
6684: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6685: }
6686: }
6687: }
6688: }
6689: }
6690: foreach my $user (keys(%seclists)) {
6691: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6692: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6693: }
6694: }
6695: return;
6696: }
6697:
6698: sub get_user_info {
6699: my ($udom,$uname,$idx,$userdata) = @_;
6700: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6701: &plainname($uname,$udom,'lastname');
6702: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6703: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6704: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6705: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6706: return;
6707: }
6708:
6709: ###############################################
6710:
6711: =pod
6712:
6713: =item * &get_user_quota()
6714:
6715: Retrieves quota assigned for storage of portfolio files for a user
6716:
6717: Incoming parameters:
6718: 1. user's username
6719: 2. user's domain
6720:
6721: Returns:
6722: 1. Disk quota (in Mb) assigned to student.
6723: 2. (Optional) Type of setting: custom or default
6724: (individually assigned or default for user's
6725: institutional status).
6726: 3. (Optional) - User's institutional status (e.g., faculty, staff
6727: or student - types as defined in localenroll::inst_usertypes
6728: for user's domain, which determines default quota for user.
6729: 4. (Optional) - Default quota which would apply to the user.
6730:
6731: If a value has been stored in the user's environment,
6732: it will return that, otherwise it returns the maximal default
6733: defined for the user's instituional status(es) in the domain.
6734:
6735: =cut
6736:
6737: ###############################################
6738:
6739:
6740: sub get_user_quota {
6741: my ($uname,$udom) = @_;
6742: my ($quota,$quotatype,$settingstatus,$defquota);
6743: if (!defined($udom)) {
6744: $udom = $env{'user.domain'};
6745: }
6746: if (!defined($uname)) {
6747: $uname = $env{'user.name'};
6748: }
6749: if (($udom eq '' || $uname eq '') ||
6750: ($udom eq 'public') && ($uname eq 'public')) {
6751: $quota = 0;
6752: $quotatype = 'default';
6753: $defquota = 0;
6754: } else {
6755: my $inststatus;
6756: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6757: $quota = $env{'environment.portfolioquota'};
6758: $inststatus = $env{'environment.inststatus'};
6759: } else {
6760: my %userenv =
6761: &Apache::lonnet::get('environment',['portfolioquota',
6762: 'inststatus'],$udom,$uname);
6763: my ($tmp) = keys(%userenv);
6764: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6765: $quota = $userenv{'portfolioquota'};
6766: $inststatus = $userenv{'inststatus'};
6767: } else {
6768: undef(%userenv);
6769: }
6770: }
6771: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6772: if ($quota eq '') {
6773: $quota = $defquota;
6774: $quotatype = 'default';
6775: } else {
6776: $quotatype = 'custom';
6777: }
6778: }
6779: if (wantarray) {
6780: return ($quota,$quotatype,$settingstatus,$defquota);
6781: } else {
6782: return $quota;
6783: }
6784: }
6785:
6786: ###############################################
6787:
6788: =pod
6789:
6790: =item * &default_quota()
6791:
6792: Retrieves default quota assigned for storage of user portfolio files,
6793: given an (optional) user's institutional status.
6794:
6795: Incoming parameters:
6796: 1. domain
6797: 2. (Optional) institutional status(es). This is a : separated list of
6798: status types (e.g., faculty, staff, student etc.)
6799: which apply to the user for whom the default is being retrieved.
6800: If the institutional status string in undefined, the domain
6801: default quota will be returned.
6802:
6803: Returns:
6804: 1. Default disk quota (in Mb) for user portfolios in the domain.
6805: 2. (Optional) institutional type which determined the value of the
6806: default quota.
6807:
6808: If a value has been stored in the domain's configuration db,
6809: it will return that, otherwise it returns 20 (for backwards
6810: compatibility with domains which have not set up a configuration
6811: db file; the original statically defined portfolio quota was 20 Mb).
6812:
6813: If the user's status includes multiple types (e.g., staff and student),
6814: the largest default quota which applies to the user determines the
6815: default quota returned.
6816:
6817: =cut
6818:
6819: ###############################################
6820:
6821:
6822: sub default_quota {
6823: my ($udom,$inststatus) = @_;
6824: my ($defquota,$settingstatus);
6825: my %quotahash = &Apache::lonnet::get_dom('configuration',
6826: ['quotas'],$udom);
6827: if (ref($quotahash{'quotas'}) eq 'HASH') {
6828: if ($inststatus ne '') {
6829: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
6830: foreach my $item (@statuses) {
6831: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
6832: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
6833: if ($defquota eq '') {
6834: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
6835: $settingstatus = $item;
6836: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
6837: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
6838: $settingstatus = $item;
6839: }
6840: }
6841: } else {
6842: if ($quotahash{'quotas'}{$item} ne '') {
6843: if ($defquota eq '') {
6844: $defquota = $quotahash{'quotas'}{$item};
6845: $settingstatus = $item;
6846: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6847: $defquota = $quotahash{'quotas'}{$item};
6848: $settingstatus = $item;
6849: }
6850: }
6851: }
6852: }
6853: }
6854: if ($defquota eq '') {
6855: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
6856: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
6857: } else {
6858: $defquota = $quotahash{'quotas'}{'default'};
6859: }
6860: $settingstatus = 'default';
6861: }
6862: } else {
6863: $settingstatus = 'default';
6864: $defquota = 20;
6865: }
6866: if (wantarray) {
6867: return ($defquota,$settingstatus);
6868: } else {
6869: return $defquota;
6870: }
6871: }
6872:
6873: sub get_secgrprole_info {
6874: my ($cdom,$cnum,$needroles,$type) = @_;
6875: my %sections_count = &get_sections($cdom,$cnum);
6876: my @sections = (sort {$a <=> $b} keys(%sections_count));
6877: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6878: my @groups = sort(keys(%curr_groups));
6879: my $allroles = [];
6880: my $rolehash;
6881: my $accesshash = {
6882: active => 'Currently has access',
6883: future => 'Will have future access',
6884: previous => 'Previously had access',
6885: };
6886: if ($needroles) {
6887: $rolehash = {'all' => 'all'};
6888: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6889: if (&Apache::lonnet::error(%user_roles)) {
6890: undef(%user_roles);
6891: }
6892: foreach my $item (keys(%user_roles)) {
6893: my ($role)=split(/\:/,$item,2);
6894: if ($role eq 'cr') { next; }
6895: if ($role =~ /^cr/) {
6896: $$rolehash{$role} = (split('/',$role))[3];
6897: } else {
6898: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
6899: }
6900: }
6901: foreach my $key (sort(keys(%{$rolehash}))) {
6902: push(@{$allroles},$key);
6903: }
6904: push (@{$allroles},'st');
6905: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
6906: }
6907: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
6908: }
6909:
6910: sub user_picker {
6911: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
6912: my $currdom = $dom;
6913: my %curr_selected = (
6914: srchin => 'dom',
6915: srchby => 'lastname',
6916: );
6917: my $srchterm;
6918: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
6919: if ($srch->{'srchby'} ne '') {
6920: $curr_selected{'srchby'} = $srch->{'srchby'};
6921: }
6922: if ($srch->{'srchin'} ne '') {
6923: $curr_selected{'srchin'} = $srch->{'srchin'};
6924: }
6925: if ($srch->{'srchtype'} ne '') {
6926: $curr_selected{'srchtype'} = $srch->{'srchtype'};
6927: }
6928: if ($srch->{'srchdomain'} ne '') {
6929: $currdom = $srch->{'srchdomain'};
6930: }
6931: $srchterm = $srch->{'srchterm'};
6932: }
6933: my %lt=&Apache::lonlocal::texthash(
6934: 'usr' => 'Search criteria',
6935: 'doma' => 'Domain/institution to search',
6936: 'uname' => 'username',
6937: 'lastname' => 'last name',
6938: 'lastfirst' => 'last name, first name',
6939: 'crs' => 'in this course',
6940: 'dom' => 'in selected LON-CAPA domain',
6941: 'alc' => 'all LON-CAPA',
6942: 'instd' => 'in institutional directory for selected domain',
6943: 'exact' => 'is',
6944: 'contains' => 'contains',
6945: 'begins' => 'begins with',
6946: 'youm' => "You must include some text to search for.",
6947: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
6948: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
6949: 'yomc' => "You must choose a domain when using an institutional directory search.",
6950: 'ymcd' => "You must choose a domain when using a domain search.",
6951: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
6952: 'whse' => "When searching by last,first you must include at least one character in the first name.",
6953: 'thfo' => "The following need to be corrected before the search can be run:",
6954: );
6955: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
6956: my $srchinsel = ' <select name="srchin">';
6957:
6958: my @srchins = ('crs','dom','alc','instd');
6959:
6960: foreach my $option (@srchins) {
6961: # FIXME 'alc' option unavailable until
6962: # loncreateuser::print_user_query_page()
6963: # has been completed.
6964: next if ($option eq 'alc');
6965: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
6966: next if ($option eq 'crs' && !$env{'request.course.id'});
6967: if ($curr_selected{'srchin'} eq $option) {
6968: $srchinsel .= '
6969: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6970: } else {
6971: $srchinsel .= '
6972: <option value="'.$option.'">'.$lt{$option}.'</option>';
6973: }
6974: }
6975: $srchinsel .= "\n </select>\n";
6976:
6977: my $srchbysel = ' <select name="srchby">';
6978: foreach my $option ('lastname','lastfirst','uname') {
6979: if ($curr_selected{'srchby'} eq $option) {
6980: $srchbysel .= '
6981: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6982: } else {
6983: $srchbysel .= '
6984: <option value="'.$option.'">'.$lt{$option}.'</option>';
6985: }
6986: }
6987: $srchbysel .= "\n </select>\n";
6988:
6989: my $srchtypesel = ' <select name="srchtype">';
6990: foreach my $option ('begins','contains','exact') {
6991: if ($curr_selected{'srchtype'} eq $option) {
6992: $srchtypesel .= '
6993: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6994: } else {
6995: $srchtypesel .= '
6996: <option value="'.$option.'">'.$lt{$option}.'</option>';
6997: }
6998: }
6999: $srchtypesel .= "\n </select>\n";
7000:
7001: my ($newuserscript,$new_user_create);
7002:
7003: if ($forcenewuser) {
7004: if (ref($srch) eq 'HASH') {
7005: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
7006: if ($cancreate) {
7007: $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>';
7008: } else {
7009: my $helplink = 'javascript:helpMenu('."'display'".')';
7010: my %usertypetext = (
7011: official => 'institutional',
7012: unofficial => 'non-institutional',
7013: );
7014: $new_user_create = '<p class="LC_warning">'.
7015: &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
7016: &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
7017: }
7018: }
7019: }
7020:
7021: $newuserscript = <<"ENDSCRIPT";
7022:
7023: function setSearch(createnew,callingForm) {
7024: if (createnew == 1) {
7025: for (var i=0; i<callingForm.srchby.length; i++) {
7026: if (callingForm.srchby.options[i].value == 'uname') {
7027: callingForm.srchby.selectedIndex = i;
7028: }
7029: }
7030: for (var i=0; i<callingForm.srchin.length; i++) {
7031: if ( callingForm.srchin.options[i].value == 'dom') {
7032: callingForm.srchin.selectedIndex = i;
7033: }
7034: }
7035: for (var i=0; i<callingForm.srchtype.length; i++) {
7036: if (callingForm.srchtype.options[i].value == 'exact') {
7037: callingForm.srchtype.selectedIndex = i;
7038: }
7039: }
7040: for (var i=0; i<callingForm.srchdomain.length; i++) {
7041: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
7042: callingForm.srchdomain.selectedIndex = i;
7043: }
7044: }
7045: }
7046: }
7047: ENDSCRIPT
7048:
7049: }
7050:
7051: my $output = <<"END_BLOCK";
7052: <script type="text/javascript">
7053: // <![CDATA[
7054: function validateEntry(callingForm) {
7055:
7056: var checkok = 1;
7057: var srchin;
7058: for (var i=0; i<callingForm.srchin.length; i++) {
7059: if ( callingForm.srchin[i].checked ) {
7060: srchin = callingForm.srchin[i].value;
7061: }
7062: }
7063:
7064: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7065: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7066: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7067: var srchterm = callingForm.srchterm.value;
7068: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7069: var msg = "";
7070:
7071: if (srchterm == "") {
7072: checkok = 0;
7073: msg += "$lt{'youm'}\\n";
7074: }
7075:
7076: if (srchtype== 'begins') {
7077: if (srchterm.length < 2) {
7078: checkok = 0;
7079: msg += "$lt{'thte'}\\n";
7080: }
7081: }
7082:
7083: if (srchtype== 'contains') {
7084: if (srchterm.length < 3) {
7085: checkok = 0;
7086: msg += "$lt{'thet'}\\n";
7087: }
7088: }
7089: if (srchin == 'instd') {
7090: if (srchdomain == '') {
7091: checkok = 0;
7092: msg += "$lt{'yomc'}\\n";
7093: }
7094: }
7095: if (srchin == 'dom') {
7096: if (srchdomain == '') {
7097: checkok = 0;
7098: msg += "$lt{'ymcd'}\\n";
7099: }
7100: }
7101: if (srchby == 'lastfirst') {
7102: if (srchterm.indexOf(",") == -1) {
7103: checkok = 0;
7104: msg += "$lt{'whus'}\\n";
7105: }
7106: if (srchterm.indexOf(",") == srchterm.length -1) {
7107: checkok = 0;
7108: msg += "$lt{'whse'}\\n";
7109: }
7110: }
7111: if (checkok == 0) {
7112: alert("$lt{'thfo'}\\n"+msg);
7113: return;
7114: }
7115: if (checkok == 1) {
7116: callingForm.submit();
7117: }
7118: }
7119:
7120: $newuserscript
7121:
7122: // ]]>
7123: </script>
7124:
7125: $new_user_create
7126:
7127: END_BLOCK
7128:
7129: $output .= &Apache::lonhtmlcommon::start_pick_box().
7130: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
7131: $domform.
7132: &Apache::lonhtmlcommon::row_closure().
7133: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
7134: $srchbysel.
7135: $srchtypesel.
7136: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
7137: $srchinsel.
7138: &Apache::lonhtmlcommon::row_closure(1).
7139: &Apache::lonhtmlcommon::end_pick_box().
7140: '<br />';
7141: return $output;
7142: }
7143:
7144: sub user_rule_check {
7145: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7146: my $response;
7147: if (ref($usershash) eq 'HASH') {
7148: foreach my $user (keys(%{$usershash})) {
7149: my ($uname,$udom) = split(/:/,$user);
7150: next if ($udom eq '' || $uname eq '');
7151: my ($id,$newuser);
7152: if (ref($usershash->{$user}) eq 'HASH') {
7153: $newuser = $usershash->{$user}->{'newuser'};
7154: $id = $usershash->{$user}->{'id'};
7155: }
7156: my $inst_response;
7157: if (ref($checks) eq 'HASH') {
7158: if (defined($checks->{'username'})) {
7159: ($inst_response,%{$inst_results->{$user}}) =
7160: &Apache::lonnet::get_instuser($udom,$uname);
7161: } elsif (defined($checks->{'id'})) {
7162: ($inst_response,%{$inst_results->{$user}}) =
7163: &Apache::lonnet::get_instuser($udom,undef,$id);
7164: }
7165: } else {
7166: ($inst_response,%{$inst_results->{$user}}) =
7167: &Apache::lonnet::get_instuser($udom,$uname);
7168: return;
7169: }
7170: if (!$got_rules->{$udom}) {
7171: my %domconfig = &Apache::lonnet::get_dom('configuration',
7172: ['usercreation'],$udom);
7173: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7174: foreach my $item ('username','id') {
7175: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7176: $$curr_rules{$udom}{$item} =
7177: $domconfig{'usercreation'}{$item.'_rule'};
7178: }
7179: }
7180: }
7181: $got_rules->{$udom} = 1;
7182: }
7183: foreach my $item (keys(%{$checks})) {
7184: if (ref($$curr_rules{$udom}) eq 'HASH') {
7185: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7186: if (@{$$curr_rules{$udom}{$item}} > 0) {
7187: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7188: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7189: if ($rule_check{$rule}) {
7190: $$rulematch{$user}{$item} = $rule;
7191: if ($inst_response eq 'ok') {
7192: if (ref($inst_results) eq 'HASH') {
7193: if (ref($inst_results->{$user}) eq 'HASH') {
7194: if (keys(%{$inst_results->{$user}}) == 0) {
7195: $$alerts{$item}{$udom}{$uname} = 1;
7196: }
7197: }
7198: }
7199: }
7200: last;
7201: }
7202: }
7203: }
7204: }
7205: }
7206: }
7207: }
7208: }
7209: return;
7210: }
7211:
7212: sub user_rule_formats {
7213: my ($domain,$domdesc,$curr_rules,$check) = @_;
7214: my %text = (
7215: 'username' => 'Usernames',
7216: 'id' => 'IDs',
7217: );
7218: my $output;
7219: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7220: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7221: if (@{$ruleorder} > 0) {
7222: $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>';
7223: foreach my $rule (@{$ruleorder}) {
7224: if (ref($curr_rules) eq 'ARRAY') {
7225: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7226: if (ref($rules->{$rule}) eq 'HASH') {
7227: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7228: $rules->{$rule}{'desc'}.'</li>';
7229: }
7230: }
7231: }
7232: }
7233: $output .= '</ul>';
7234: }
7235: }
7236: return $output;
7237: }
7238:
7239: sub instrule_disallow_msg {
7240: my ($checkitem,$domdesc,$count,$mode) = @_;
7241: my $response;
7242: my %text = (
7243: item => 'username',
7244: items => 'usernames',
7245: match => 'matches',
7246: do => 'does',
7247: action => 'a username',
7248: one => 'one',
7249: );
7250: if ($count > 1) {
7251: $text{'item'} = 'usernames';
7252: $text{'match'} ='match';
7253: $text{'do'} = 'do';
7254: $text{'action'} = 'usernames',
7255: $text{'one'} = 'ones';
7256: }
7257: if ($checkitem eq 'id') {
7258: $text{'items'} = 'IDs';
7259: $text{'item'} = 'ID';
7260: $text{'action'} = 'an ID';
7261: if ($count > 1) {
7262: $text{'item'} = 'IDs';
7263: $text{'action'} = 'IDs';
7264: }
7265: }
7266: $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 />';
7267: if ($mode eq 'upload') {
7268: if ($checkitem eq 'username') {
7269: $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'}.");
7270: } elsif ($checkitem eq 'id') {
7271: $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.");
7272: }
7273: } elsif ($mode eq 'selfcreate') {
7274: if ($checkitem eq 'id') {
7275: $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.");
7276: }
7277: } else {
7278: if ($checkitem eq 'username') {
7279: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7280: } elsif ($checkitem eq 'id') {
7281: $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.");
7282: }
7283: }
7284: return $response;
7285: }
7286:
7287: sub personal_data_fieldtitles {
7288: my %fieldtitles = &Apache::lonlocal::texthash (
7289: id => 'Student/Employee ID',
7290: permanentemail => 'E-mail address',
7291: lastname => 'Last Name',
7292: firstname => 'First Name',
7293: middlename => 'Middle Name',
7294: generation => 'Generation',
7295: gen => 'Generation',
7296: inststatus => 'Affiliation',
7297: );
7298: return %fieldtitles;
7299: }
7300:
7301: sub sorted_inst_types {
7302: my ($dom) = @_;
7303: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7304: my $othertitle = &mt('All users');
7305: if ($env{'request.course.id'}) {
7306: $othertitle = &mt('Any users');
7307: }
7308: my @types;
7309: if (ref($order) eq 'ARRAY') {
7310: @types = @{$order};
7311: }
7312: if (@types == 0) {
7313: if (ref($usertypes) eq 'HASH') {
7314: @types = sort(keys(%{$usertypes}));
7315: }
7316: }
7317: if (keys(%{$usertypes}) > 0) {
7318: $othertitle = &mt('Other users');
7319: }
7320: return ($othertitle,$usertypes,\@types);
7321: }
7322:
7323: sub get_institutional_codes {
7324: my ($settings,$allcourses,$LC_code) = @_;
7325: # Get complete list of course sections to update
7326: my @currsections = ();
7327: my @currxlists = ();
7328: my $coursecode = $$settings{'internal.coursecode'};
7329:
7330: if ($$settings{'internal.sectionnums'} ne '') {
7331: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7332: }
7333:
7334: if ($$settings{'internal.crosslistings'} ne '') {
7335: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7336: }
7337:
7338: if (@currxlists > 0) {
7339: foreach (@currxlists) {
7340: if (m/^([^:]+):(\w*)$/) {
7341: unless (grep/^$1$/,@{$allcourses}) {
7342: push @{$allcourses},$1;
7343: $$LC_code{$1} = $2;
7344: }
7345: }
7346: }
7347: }
7348:
7349: if (@currsections > 0) {
7350: foreach (@currsections) {
7351: if (m/^(\w+):(\w*)$/) {
7352: my $sec = $coursecode.$1;
7353: my $lc_sec = $2;
7354: unless (grep/^$sec$/,@{$allcourses}) {
7355: push @{$allcourses},$sec;
7356: $$LC_code{$sec} = $lc_sec;
7357: }
7358: }
7359: }
7360: }
7361: return;
7362: }
7363:
7364: =pod
7365:
7366: =head1 Slot Helpers
7367:
7368: =over 4
7369:
7370: =item * sorted_slots()
7371:
7372: Sorts an array of slot names in order of slot start time (earliest first).
7373:
7374: Inputs:
7375:
7376: =over 4
7377:
7378: slotsarr - Reference to array of unsorted slot names.
7379:
7380: slots - Reference to hash of hash, where outer hash keys are slot names.
7381:
7382: =back
7383:
7384: Returns:
7385:
7386: =over 4
7387:
7388: sorted - An array of slot names sorted by the start time of the slot.
7389:
7390: =back
7391:
7392: =back
7393:
7394: =cut
7395:
7396:
7397: sub sorted_slots {
7398: my ($slotsarr,$slots) = @_;
7399: my @sorted;
7400: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
7401: @sorted =
7402: sort {
7403: if (ref($slots->{$a}) && ref($slots->{$b})) {
7404: return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
7405: }
7406: if (ref($slots->{$a})) { return -1;}
7407: if (ref($slots->{$b})) { return 1;}
7408: return 0;
7409: } @{$slotsarr};
7410: }
7411: return @sorted;
7412: }
7413:
7414: =pod
7415:
7416: =back
7417:
7418: =head1 HTTP Helpers
7419:
7420: =over 4
7421:
7422: =item * &get_unprocessed_cgi($query,$possible_names)
7423:
7424: Modify the %env hash to contain unprocessed CGI form parameters held in
7425: $query. The parameters listed in $possible_names (an array reference),
7426: will be set in $env{'form.name'} if they do not already exist.
7427:
7428: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7429: $possible_names is an ref to an array of form element names. As an example:
7430: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7431: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7432:
7433: =cut
7434:
7435: sub get_unprocessed_cgi {
7436: my ($query,$possible_names)= @_;
7437: # $Apache::lonxml::debug=1;
7438: foreach my $pair (split(/&/,$query)) {
7439: my ($name, $value) = split(/=/,$pair);
7440: $name = &unescape($name);
7441: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7442: $value =~ tr/+/ /;
7443: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7444: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7445: }
7446: }
7447: }
7448:
7449: =pod
7450:
7451: =item * &cacheheader()
7452:
7453: returns cache-controlling header code
7454:
7455: =cut
7456:
7457: sub cacheheader {
7458: unless ($env{'request.method'} eq 'GET') { return ''; }
7459: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7460: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7461: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7462: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7463: return $output;
7464: }
7465:
7466: =pod
7467:
7468: =item * &no_cache($r)
7469:
7470: specifies header code to not have cache
7471:
7472: =cut
7473:
7474: sub no_cache {
7475: my ($r) = @_;
7476: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7477: $env{'request.method'} ne 'GET') { return ''; }
7478: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7479: $r->no_cache(1);
7480: $r->header_out("Expires" => $date);
7481: $r->header_out("Pragma" => "no-cache");
7482: }
7483:
7484: sub content_type {
7485: my ($r,$type,$charset) = @_;
7486: if ($r) {
7487: # Note that printout.pl calls this with undef for $r.
7488: &no_cache($r);
7489: }
7490: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7491: unless ($charset) {
7492: $charset=&Apache::lonlocal::current_encoding;
7493: }
7494: if ($charset) { $type.='; charset='.$charset; }
7495: if ($r) {
7496: $r->content_type($type);
7497: } else {
7498: print("Content-type: $type\n\n");
7499: }
7500: }
7501:
7502: =pod
7503:
7504: =item * &add_to_env($name,$value)
7505:
7506: adds $name to the %env hash with value
7507: $value, if $name already exists, the entry is converted to an array
7508: reference and $value is added to the array.
7509:
7510: =cut
7511:
7512: sub add_to_env {
7513: my ($name,$value)=@_;
7514: if (defined($env{$name})) {
7515: if (ref($env{$name})) {
7516: #already have multiple values
7517: push(@{ $env{$name} },$value);
7518: } else {
7519: #first time seeing multiple values, convert hash entry to an arrayref
7520: my $first=$env{$name};
7521: undef($env{$name});
7522: push(@{ $env{$name} },$first,$value);
7523: }
7524: } else {
7525: $env{$name}=$value;
7526: }
7527: }
7528:
7529: =pod
7530:
7531: =item * &get_env_multiple($name)
7532:
7533: gets $name from the %env hash, it seemlessly handles the cases where multiple
7534: values may be defined and end up as an array ref.
7535:
7536: returns an array of values
7537:
7538: =cut
7539:
7540: sub get_env_multiple {
7541: my ($name) = @_;
7542: my @values;
7543: if (defined($env{$name})) {
7544: # exists is it an array
7545: if (ref($env{$name})) {
7546: @values=@{ $env{$name} };
7547: } else {
7548: $values[0]=$env{$name};
7549: }
7550: }
7551: return(@values);
7552: }
7553:
7554: sub ask_for_embedded_content {
7555: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
7556: my $upload_output = '
7557: <form name="upload_embedded" action="'.$actionurl.'"
7558: method="post" enctype="multipart/form-data">';
7559: $upload_output .= $state;
7560: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
7561:
7562: my $num = 0;
7563: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
7564: $upload_output .= &start_data_table_row().
7565: '<td>'.$embed_file.'</td><td>';
7566: if ($args->{'ignore_remote_references'}
7567: && $embed_file =~ m{^\w+://}) {
7568: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
7569: } elsif ($args->{'error_on_invalid_names'}
7570: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
7571:
7572: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
7573:
7574: } else {
7575: $upload_output .='
7576: <input name="embedded_item_'.$num.'" type="file" value="" />
7577: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
7578: my $attrib = join(':',@{$$allfiles{$embed_file}});
7579: $upload_output .=
7580: "\n\t\t".
7581: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
7582: $attrib.'" />';
7583: if (exists($$codebase{$embed_file})) {
7584: $upload_output .=
7585: "\n\t\t".
7586: '<input name="codebase_'.$num.'" type="hidden" value="'.
7587: &escape($$codebase{$embed_file}).'" />';
7588: }
7589: }
7590: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
7591: $num++;
7592: }
7593: $upload_output .= &Apache::loncommon::end_data_table().'<br />
7594: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
7595: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
7596: '.&mt('(only files for which a location has been provided will be uploaded)').'
7597: </form>';
7598: return $upload_output;
7599: }
7600:
7601: sub upload_embedded {
7602: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
7603: $current_disk_usage) = @_;
7604: my $output;
7605: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
7606: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
7607: my $orig_uploaded_filename =
7608: $env{'form.embedded_item_'.$i.'.filename'};
7609:
7610: $env{'form.embedded_orig_'.$i} =
7611: &unescape($env{'form.embedded_orig_'.$i});
7612: my ($path,$fname) =
7613: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
7614: # no path, whole string is fname
7615: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
7616:
7617: $path = $env{'form.currentpath'}.$path;
7618: $fname = &Apache::lonnet::clean_filename($fname);
7619: # See if there is anything left
7620: next if ($fname eq '');
7621:
7622: # Check if file already exists as a file or directory.
7623: my ($state,$msg);
7624: if ($context eq 'portfolio') {
7625: my $port_path = $dirpath;
7626: if ($group ne '') {
7627: $port_path = "groups/$group/$port_path";
7628: }
7629: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
7630: $dir_root,$port_path,$disk_quota,
7631: $current_disk_usage,$uname,$udom);
7632: if ($state eq 'will_exceed_quota'
7633: || $state eq 'file_locked'
7634: || $state eq 'file_exists' ) {
7635: $output .= $msg;
7636: next;
7637: }
7638: } elsif (($context eq 'author') || ($context eq 'testbank')) {
7639: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
7640: if ($state eq 'exists') {
7641: $output .= $msg;
7642: next;
7643: }
7644: }
7645: # Check if extension is valid
7646: if (($fname =~ /\.(\w+)$/) &&
7647: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
7648: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
7649: next;
7650: } elsif (($fname =~ /\.(\w+)$/) &&
7651: (!defined(&Apache::loncommon::fileembstyle($1)))) {
7652: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
7653: next;
7654: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
7655: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
7656: next;
7657: }
7658:
7659: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
7660: if ($context eq 'portfolio') {
7661: my $result=
7662: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
7663: $dirpath.$path);
7664: if ($result !~ m|^/uploaded/|) {
7665: $output .= '<span class="LC_error">'
7666: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
7667: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
7668: .'</span><br />';
7669: next;
7670: } else {
7671: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
7672: $path.$fname.'</span>').'</p>';
7673: }
7674: } else {
7675: # Save the file
7676: my $target = $env{'form.embedded_item_'.$i};
7677: my $fullpath = $dir_root.$dirpath.'/'.$path;
7678: my $dest = $fullpath.$fname;
7679: my $url = $url_root.$dirpath.'/'.$path.$fname;
7680: my @parts=split(/\//,$fullpath);
7681: my $count;
7682: my $filepath = $dir_root;
7683: for ($count=4;$count<=$#parts;$count++) {
7684: $filepath .= "/$parts[$count]";
7685: if ((-e $filepath)!=1) {
7686: mkdir($filepath,0770);
7687: }
7688: }
7689: my $fh;
7690: if (!open($fh,'>'.$dest)) {
7691: &Apache::lonnet::logthis('Failed to create '.$dest);
7692: $output .= '<span class="LC_error">'.
7693: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7694: '</span><br />';
7695: } else {
7696: if (!print $fh $env{'form.embedded_item_'.$i}) {
7697: &Apache::lonnet::logthis('Failed to write to '.$dest);
7698: $output .= '<span class="LC_error">'.
7699: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7700: '</span><br />';
7701: } else {
7702: if ($context eq 'testbank') {
7703: $output .= &mt('Embedded file uploaded successfully:').
7704: ' <a href="'.$url.'">'.
7705: $orig_uploaded_filename.'</a><br />';
7706: } else {
7707: $output .= '<font size="+2">'.
7708: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
7709: $orig_uploaded_filename.'</a>').'</font><br />';
7710: }
7711: }
7712: close($fh);
7713: }
7714: }
7715: }
7716: return $output;
7717: }
7718:
7719: sub check_for_existing {
7720: my ($path,$fname,$element) = @_;
7721: my ($state,$msg);
7722: if (-d $path.'/'.$fname) {
7723: $state = 'exists';
7724: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7725: } elsif (-e $path.'/'.$fname) {
7726: $state = 'exists';
7727: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7728: }
7729: if ($state eq 'exists') {
7730: $msg = '<span class="LC_error">'.$msg.'</span><br />';
7731: }
7732: return ($state,$msg);
7733: }
7734:
7735: sub check_for_upload {
7736: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
7737: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
7738: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
7739: my $getpropath = 1;
7740: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
7741: $getpropath);
7742: my $found_file = 0;
7743: my $locked_file = 0;
7744: foreach my $line (@dir_list) {
7745: my ($file_name)=split(/\&/,$line,2);
7746: if ($file_name eq $fname){
7747: $file_name = $path.$file_name;
7748: if ($group ne '') {
7749: $file_name = $group.$file_name;
7750: }
7751: $found_file = 1;
7752: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
7753: $locked_file = 1;
7754: }
7755: }
7756: }
7757: if (($current_disk_usage + $filesize) > $disk_quota){
7758: my $msg = '<span class="LC_error">'.
7759: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
7760: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
7761: return ('will_exceed_quota',$msg);
7762: } elsif ($found_file) {
7763: if ($locked_file) {
7764: my $msg = '<span class="LC_error">';
7765: $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>');
7766: $msg .= '</span><br />';
7767: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
7768: return ('file_locked',$msg);
7769: } else {
7770: my $msg = '<span class="LC_error">';
7771: $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'});
7772: $msg .= '</span>';
7773: $msg .= '<br />';
7774: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
7775: return ('file_exists',$msg);
7776: }
7777: }
7778: }
7779:
7780:
7781: =pod
7782:
7783: =back
7784:
7785: =head1 CSV Upload/Handling functions
7786:
7787: =over 4
7788:
7789: =item * &upfile_store($r)
7790:
7791: Store uploaded file, $r should be the HTTP Request object,
7792: needs $env{'form.upfile'}
7793: returns $datatoken to be put into hidden field
7794:
7795: =cut
7796:
7797: sub upfile_store {
7798: my $r=shift;
7799: $env{'form.upfile'}=~s/\r/\n/gs;
7800: $env{'form.upfile'}=~s/\f/\n/gs;
7801: $env{'form.upfile'}=~s/\n+/\n/gs;
7802: $env{'form.upfile'}=~s/\n+$//gs;
7803:
7804: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7805: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7806: {
7807: my $datafile = $r->dir_config('lonDaemons').
7808: '/tmp/'.$datatoken.'.tmp';
7809: if ( open(my $fh,">$datafile") ) {
7810: print $fh $env{'form.upfile'};
7811: close($fh);
7812: }
7813: }
7814: return $datatoken;
7815: }
7816:
7817: =pod
7818:
7819: =item * &load_tmp_file($r)
7820:
7821: Load uploaded file from tmp, $r should be the HTTP Request object,
7822: needs $env{'form.datatoken'},
7823: sets $env{'form.upfile'} to the contents of the file
7824:
7825: =cut
7826:
7827: sub load_tmp_file {
7828: my $r=shift;
7829: my @studentdata=();
7830: {
7831: my $studentfile = $r->dir_config('lonDaemons').
7832: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7833: if ( open(my $fh,"<$studentfile") ) {
7834: @studentdata=<$fh>;
7835: close($fh);
7836: }
7837: }
7838: $env{'form.upfile'}=join('',@studentdata);
7839: }
7840:
7841: =pod
7842:
7843: =item * &upfile_record_sep()
7844:
7845: Separate uploaded file into records
7846: returns array of records,
7847: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7848:
7849: =cut
7850:
7851: sub upfile_record_sep {
7852: if ($env{'form.upfiletype'} eq 'xml') {
7853: } else {
7854: my @records;
7855: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7856: if ($line=~/^\s*$/) { next; }
7857: push(@records,$line);
7858: }
7859: return @records;
7860: }
7861: }
7862:
7863: =pod
7864:
7865: =item * &record_sep($record)
7866:
7867: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7868:
7869: =cut
7870:
7871: sub takeleft {
7872: my $index=shift;
7873: return substr('0000'.$index,-4,4);
7874: }
7875:
7876: sub record_sep {
7877: my $record=shift;
7878: my %components=();
7879: if ($env{'form.upfiletype'} eq 'xml') {
7880: } elsif ($env{'form.upfiletype'} eq 'space') {
7881: my $i=0;
7882: foreach my $field (split(/\s+/,$record)) {
7883: $field=~s/^(\"|\')//;
7884: $field=~s/(\"|\')$//;
7885: $components{&takeleft($i)}=$field;
7886: $i++;
7887: }
7888: } elsif ($env{'form.upfiletype'} eq 'tab') {
7889: my $i=0;
7890: foreach my $field (split(/\t/,$record)) {
7891: $field=~s/^(\"|\')//;
7892: $field=~s/(\"|\')$//;
7893: $components{&takeleft($i)}=$field;
7894: $i++;
7895: }
7896: } else {
7897: my $separator=',';
7898: if ($env{'form.upfiletype'} eq 'semisv') {
7899: $separator=';';
7900: }
7901: my $i=0;
7902: # the character we are looking for to indicate the end of a quote or a record
7903: my $looking_for=$separator;
7904: # do not add the characters to the fields
7905: my $ignore=0;
7906: # we just encountered a separator (or the beginning of the record)
7907: my $just_found_separator=1;
7908: # store the field we are working on here
7909: my $field='';
7910: # work our way through all characters in record
7911: foreach my $character ($record=~/(.)/g) {
7912: if ($character eq $looking_for) {
7913: if ($character ne $separator) {
7914: # Found the end of a quote, again looking for separator
7915: $looking_for=$separator;
7916: $ignore=1;
7917: } else {
7918: # Found a separator, store away what we got
7919: $components{&takeleft($i)}=$field;
7920: $i++;
7921: $just_found_separator=1;
7922: $ignore=0;
7923: $field='';
7924: }
7925: next;
7926: }
7927: # single or double quotation marks after a separator indicate beginning of a quote
7928: # we are now looking for the end of the quote and need to ignore separators
7929: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
7930: $looking_for=$character;
7931: next;
7932: }
7933: # ignore would be true after we reached the end of a quote
7934: if ($ignore) { next; }
7935: if (($just_found_separator) && ($character=~/\s/)) { next; }
7936: $field.=$character;
7937: $just_found_separator=0;
7938: }
7939: # catch the very last entry, since we never encountered the separator
7940: $components{&takeleft($i)}=$field;
7941: }
7942: return %components;
7943: }
7944:
7945: ######################################################
7946: ######################################################
7947:
7948: =pod
7949:
7950: =item * &upfile_select_html()
7951:
7952: Return HTML code to select a file from the users machine and specify
7953: the file type.
7954:
7955: =cut
7956:
7957: ######################################################
7958: ######################################################
7959: sub upfile_select_html {
7960: my %Types = (
7961: csv => &mt('CSV (comma separated values, spreadsheet)'),
7962: semisv => &mt('Semicolon separated values'),
7963: space => &mt('Space separated'),
7964: tab => &mt('Tabulator separated'),
7965: # xml => &mt('HTML/XML'),
7966: );
7967: my $Str = '<input type="file" name="upfile" size="50" />'.
7968: '<br />'.&mt('Type').': <select name="upfiletype">';
7969: foreach my $type (sort(keys(%Types))) {
7970: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
7971: }
7972: $Str .= "</select>\n";
7973: return $Str;
7974: }
7975:
7976: sub get_samples {
7977: my ($records,$toget) = @_;
7978: my @samples=({});
7979: my $got=0;
7980: foreach my $rec (@$records) {
7981: my %temp = &record_sep($rec);
7982: if (! grep(/\S/, values(%temp))) { next; }
7983: if (%temp) {
7984: $samples[$got]=\%temp;
7985: $got++;
7986: if ($got == $toget) { last; }
7987: }
7988: }
7989: return \@samples;
7990: }
7991:
7992: ######################################################
7993: ######################################################
7994:
7995: =pod
7996:
7997: =item * &csv_print_samples($r,$records)
7998:
7999: Prints a table of sample values from each column uploaded $r is an
8000: Apache Request ref, $records is an arrayref from
8001: &Apache::loncommon::upfile_record_sep
8002:
8003: =cut
8004:
8005: ######################################################
8006: ######################################################
8007: sub csv_print_samples {
8008: my ($r,$records) = @_;
8009: my $samples = &get_samples($records,5);
8010:
8011: $r->print(&mt('Samples').'<br />'.&start_data_table().
8012: &start_data_table_header_row());
8013: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8014: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
8015: }
8016: $r->print(&end_data_table_header_row());
8017: foreach my $hash (@$samples) {
8018: $r->print(&start_data_table_row());
8019: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8020: $r->print('<td>');
8021: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
8022: $r->print('</td>');
8023: }
8024: $r->print(&end_data_table_row());
8025: }
8026: $r->print(&end_data_table().'<br />'."\n");
8027: }
8028:
8029: ######################################################
8030: ######################################################
8031:
8032: =pod
8033:
8034: =item * &csv_print_select_table($r,$records,$d)
8035:
8036: Prints a table to create associations between values and table columns.
8037:
8038: $r is an Apache Request ref,
8039: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8040: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
8041:
8042: =cut
8043:
8044: ######################################################
8045: ######################################################
8046: sub csv_print_select_table {
8047: my ($r,$records,$d) = @_;
8048: my $i=0;
8049: my $samples = &get_samples($records,1);
8050: $r->print(&mt('Associate columns with student attributes.')."\n".
8051: &start_data_table().&start_data_table_header_row().
8052: '<th>'.&mt('Attribute').'</th>'.
8053: '<th>'.&mt('Column').'</th>'.
8054: &end_data_table_header_row()."\n");
8055: foreach my $array_ref (@$d) {
8056: my ($value,$display,$defaultcol)=@{ $array_ref };
8057: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
8058:
8059: $r->print('<td><select name"f'.$i.'"'.
8060: ' onchange="javascript:flip(this.form,'.$i.');">');
8061: $r->print('<option value="none"></option>');
8062: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8063: $r->print('<option value="'.$sample.'"'.
8064: ($sample eq $defaultcol ? ' selected="selected" ' : '').
8065: '>'.&mt('Column [_1]',($sample+1)).'</option>');
8066: }
8067: $r->print('</select></td>'.&end_data_table_row()."\n");
8068: $i++;
8069: }
8070: $r->print(&end_data_table());
8071: $i--;
8072: return $i;
8073: }
8074:
8075: ######################################################
8076: ######################################################
8077:
8078: =pod
8079:
8080: =item * &csv_samples_select_table($r,$records,$d)
8081:
8082: Prints a table of sample values from the upload and can make associate samples to internal names.
8083:
8084: $r is an Apache Request ref,
8085: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8086: $d is an array of 2 element arrays (internal name, displayed name)
8087:
8088: =cut
8089:
8090: ######################################################
8091: ######################################################
8092: sub csv_samples_select_table {
8093: my ($r,$records,$d) = @_;
8094: my $i=0;
8095: #
8096: my $max_samples = 5;
8097: my $samples = &get_samples($records,$max_samples);
8098: $r->print(&start_data_table().
8099: &start_data_table_header_row().'<th>'.
8100: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8101: &end_data_table_header_row());
8102:
8103: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8104: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8105: ' onchange="javascript:flip(this.form,'.$i.');">');
8106: foreach my $option (@$d) {
8107: my ($value,$display,$defaultcol)=@{ $option };
8108: $r->print('<option value="'.$value.'"'.
8109: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8110: $display.'</option>');
8111: }
8112: $r->print('</select></td><td>');
8113: foreach my $line (0..($max_samples-1)) {
8114: if (defined($samples->[$line]{$key})) {
8115: $r->print($samples->[$line]{$key}."<br />\n");
8116: }
8117: }
8118: $r->print('</td>'.&end_data_table_row());
8119: $i++;
8120: }
8121: $r->print(&end_data_table());
8122: $i--;
8123: return($i);
8124: }
8125:
8126: ######################################################
8127: ######################################################
8128:
8129: =pod
8130:
8131: =item * &clean_excel_name($name)
8132:
8133: Returns a replacement for $name which does not contain any illegal characters.
8134:
8135: =cut
8136:
8137: ######################################################
8138: ######################################################
8139: sub clean_excel_name {
8140: my ($name) = @_;
8141: $name =~ s/[:\*\?\/\\]//g;
8142: if (length($name) > 31) {
8143: $name = substr($name,0,31);
8144: }
8145: return $name;
8146: }
8147:
8148: =pod
8149:
8150: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8151:
8152: Returns either 1 or undef
8153:
8154: 1 if the part is to be hidden, undef if it is to be shown
8155:
8156: Arguments are:
8157:
8158: $id the id of the part to be checked
8159: $symb, optional the symb of the resource to check
8160: $udom, optional the domain of the user to check for
8161: $uname, optional the username of the user to check for
8162:
8163: =cut
8164:
8165: sub check_if_partid_hidden {
8166: my ($id,$symb,$udom,$uname) = @_;
8167: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8168: $symb,$udom,$uname);
8169: my $truth=1;
8170: #if the string starts with !, then the list is the list to show not hide
8171: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8172: my @hiddenlist=split(/,/,$hiddenparts);
8173: foreach my $checkid (@hiddenlist) {
8174: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8175: }
8176: return !$truth;
8177: }
8178:
8179:
8180: ############################################################
8181: ############################################################
8182:
8183: =pod
8184:
8185: =back
8186:
8187: =head1 cgi-bin script and graphing routines
8188:
8189: =over 4
8190:
8191: =item * &get_cgi_id()
8192:
8193: Inputs: none
8194:
8195: Returns an id which can be used to pass environment variables
8196: to various cgi-bin scripts. These environment variables will
8197: be removed from the users environment after a given time by
8198: the routine &Apache::lonnet::transfer_profile_to_env.
8199:
8200: =cut
8201:
8202: ############################################################
8203: ############################################################
8204: my $uniq=0;
8205: sub get_cgi_id {
8206: $uniq=($uniq+1)%100000;
8207: return (time.'_'.$$.'_'.$uniq);
8208: }
8209:
8210: ############################################################
8211: ############################################################
8212:
8213: =pod
8214:
8215: =item * &DrawBarGraph()
8216:
8217: Facilitates the plotting of data in a (stacked) bar graph.
8218: Puts plot definition data into the users environment in order for
8219: graph.png to plot it. Returns an <img> tag for the plot.
8220: The bars on the plot are labeled '1','2',...,'n'.
8221:
8222: Inputs:
8223:
8224: =over 4
8225:
8226: =item $Title: string, the title of the plot
8227:
8228: =item $xlabel: string, text describing the X-axis of the plot
8229:
8230: =item $ylabel: string, text describing the Y-axis of the plot
8231:
8232: =item $Max: scalar, the maximum Y value to use in the plot
8233: If $Max is < any data point, the graph will not be rendered.
8234:
8235: =item $colors: array ref holding the colors to be used for the data sets when
8236: they are plotted. If undefined, default values will be used.
8237:
8238: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8239:
8240: =item @Values: An array of array references. Each array reference holds data
8241: to be plotted in a stacked bar chart.
8242:
8243: =item If the final element of @Values is a hash reference the key/value
8244: pairs will be added to the graph definition.
8245:
8246: =back
8247:
8248: Returns:
8249:
8250: An <img> tag which references graph.png and the appropriate identifying
8251: information for the plot.
8252:
8253: =cut
8254:
8255: ############################################################
8256: ############################################################
8257: sub DrawBarGraph {
8258: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8259: #
8260: if (! defined($colors)) {
8261: $colors = ['#33ff00',
8262: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8263: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8264: ];
8265: }
8266: my $extra_settings = {};
8267: if (ref($Values[-1]) eq 'HASH') {
8268: $extra_settings = pop(@Values);
8269: }
8270: #
8271: my $identifier = &get_cgi_id();
8272: my $id = 'cgi.'.$identifier;
8273: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8274: return '';
8275: }
8276: #
8277: my @Labels;
8278: if (defined($labels)) {
8279: @Labels = @$labels;
8280: } else {
8281: for (my $i=0;$i<@{$Values[0]};$i++) {
8282: push (@Labels,$i+1);
8283: }
8284: }
8285: #
8286: my $NumBars = scalar(@{$Values[0]});
8287: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8288: my %ValuesHash;
8289: my $NumSets=1;
8290: foreach my $array (@Values) {
8291: next if (! ref($array));
8292: $ValuesHash{$id.'.data.'.$NumSets++} =
8293: join(',',@$array);
8294: }
8295: #
8296: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8297: if ($NumBars < 3) {
8298: $width = 120+$NumBars*32;
8299: $xskip = 1;
8300: $bar_width = 30;
8301: } elsif ($NumBars < 5) {
8302: $width = 120+$NumBars*20;
8303: $xskip = 1;
8304: $bar_width = 20;
8305: } elsif ($NumBars < 10) {
8306: $width = 120+$NumBars*15;
8307: $xskip = 1;
8308: $bar_width = 15;
8309: } elsif ($NumBars <= 25) {
8310: $width = 120+$NumBars*11;
8311: $xskip = 5;
8312: $bar_width = 8;
8313: } elsif ($NumBars <= 50) {
8314: $width = 120+$NumBars*8;
8315: $xskip = 5;
8316: $bar_width = 4;
8317: } else {
8318: $width = 120+$NumBars*8;
8319: $xskip = 5;
8320: $bar_width = 4;
8321: }
8322: #
8323: $Max = 1 if ($Max < 1);
8324: if ( int($Max) < $Max ) {
8325: $Max++;
8326: $Max = int($Max);
8327: }
8328: $Title = '' if (! defined($Title));
8329: $xlabel = '' if (! defined($xlabel));
8330: $ylabel = '' if (! defined($ylabel));
8331: $ValuesHash{$id.'.title'} = &escape($Title);
8332: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8333: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8334: $ValuesHash{$id.'.y_max_value'} = $Max;
8335: $ValuesHash{$id.'.NumBars'} = $NumBars;
8336: $ValuesHash{$id.'.NumSets'} = $NumSets;
8337: $ValuesHash{$id.'.PlotType'} = 'bar';
8338: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8339: $ValuesHash{$id.'.height'} = $height;
8340: $ValuesHash{$id.'.width'} = $width;
8341: $ValuesHash{$id.'.xskip'} = $xskip;
8342: $ValuesHash{$id.'.bar_width'} = $bar_width;
8343: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8344: #
8345: # Deal with other parameters
8346: while (my ($key,$value) = each(%$extra_settings)) {
8347: $ValuesHash{$id.'.'.$key} = $value;
8348: }
8349: #
8350: &Apache::lonnet::appenv(\%ValuesHash);
8351: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8352: }
8353:
8354: ############################################################
8355: ############################################################
8356:
8357: =pod
8358:
8359: =item * &DrawXYGraph()
8360:
8361: Facilitates the plotting of data in an XY graph.
8362: Puts plot definition data into the users environment in order for
8363: graph.png to plot it. Returns an <img> tag for the plot.
8364:
8365: Inputs:
8366:
8367: =over 4
8368:
8369: =item $Title: string, the title of the plot
8370:
8371: =item $xlabel: string, text describing the X-axis of the plot
8372:
8373: =item $ylabel: string, text describing the Y-axis of the plot
8374:
8375: =item $Max: scalar, the maximum Y value to use in the plot
8376: If $Max is < any data point, the graph will not be rendered.
8377:
8378: =item $colors: Array ref containing the hex color codes for the data to be
8379: plotted in. If undefined, default values will be used.
8380:
8381: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8382:
8383: =item $Ydata: Array ref containing Array refs.
8384: Each of the contained arrays will be plotted as a separate curve.
8385:
8386: =item %Values: hash indicating or overriding any default values which are
8387: passed to graph.png.
8388: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8389:
8390: =back
8391:
8392: Returns:
8393:
8394: An <img> tag which references graph.png and the appropriate identifying
8395: information for the plot.
8396:
8397: =cut
8398:
8399: ############################################################
8400: ############################################################
8401: sub DrawXYGraph {
8402: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8403: #
8404: # Create the identifier for the graph
8405: my $identifier = &get_cgi_id();
8406: my $id = 'cgi.'.$identifier;
8407: #
8408: $Title = '' if (! defined($Title));
8409: $xlabel = '' if (! defined($xlabel));
8410: $ylabel = '' if (! defined($ylabel));
8411: my %ValuesHash =
8412: (
8413: $id.'.title' => &escape($Title),
8414: $id.'.xlabel' => &escape($xlabel),
8415: $id.'.ylabel' => &escape($ylabel),
8416: $id.'.y_max_value'=> $Max,
8417: $id.'.labels' => join(',',@$Xlabels),
8418: $id.'.PlotType' => 'XY',
8419: );
8420: #
8421: if (defined($colors) && ref($colors) eq 'ARRAY') {
8422: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8423: }
8424: #
8425: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8426: return '';
8427: }
8428: my $NumSets=1;
8429: foreach my $array (@{$Ydata}){
8430: next if (! ref($array));
8431: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8432: }
8433: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8434: #
8435: # Deal with other parameters
8436: while (my ($key,$value) = each(%Values)) {
8437: $ValuesHash{$id.'.'.$key} = $value;
8438: }
8439: #
8440: &Apache::lonnet::appenv(\%ValuesHash);
8441: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8442: }
8443:
8444: ############################################################
8445: ############################################################
8446:
8447: =pod
8448:
8449: =item * &DrawXYYGraph()
8450:
8451: Facilitates the plotting of data in an XY graph with two Y axes.
8452: Puts plot definition data into the users environment in order for
8453: graph.png to plot it. Returns an <img> tag for the plot.
8454:
8455: Inputs:
8456:
8457: =over 4
8458:
8459: =item $Title: string, the title of the plot
8460:
8461: =item $xlabel: string, text describing the X-axis of the plot
8462:
8463: =item $ylabel: string, text describing the Y-axis of the plot
8464:
8465: =item $colors: Array ref containing the hex color codes for the data to be
8466: plotted in. If undefined, default values will be used.
8467:
8468: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8469:
8470: =item $Ydata1: The first data set
8471:
8472: =item $Min1: The minimum value of the left Y-axis
8473:
8474: =item $Max1: The maximum value of the left Y-axis
8475:
8476: =item $Ydata2: The second data set
8477:
8478: =item $Min2: The minimum value of the right Y-axis
8479:
8480: =item $Max2: The maximum value of the left Y-axis
8481:
8482: =item %Values: hash indicating or overriding any default values which are
8483: passed to graph.png.
8484: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8485:
8486: =back
8487:
8488: Returns:
8489:
8490: An <img> tag which references graph.png and the appropriate identifying
8491: information for the plot.
8492:
8493: =cut
8494:
8495: ############################################################
8496: ############################################################
8497: sub DrawXYYGraph {
8498: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8499: $Ydata2,$Min2,$Max2,%Values)=@_;
8500: #
8501: # Create the identifier for the graph
8502: my $identifier = &get_cgi_id();
8503: my $id = 'cgi.'.$identifier;
8504: #
8505: $Title = '' if (! defined($Title));
8506: $xlabel = '' if (! defined($xlabel));
8507: $ylabel = '' if (! defined($ylabel));
8508: my %ValuesHash =
8509: (
8510: $id.'.title' => &escape($Title),
8511: $id.'.xlabel' => &escape($xlabel),
8512: $id.'.ylabel' => &escape($ylabel),
8513: $id.'.labels' => join(',',@$Xlabels),
8514: $id.'.PlotType' => 'XY',
8515: $id.'.NumSets' => 2,
8516: $id.'.two_axes' => 1,
8517: $id.'.y1_max_value' => $Max1,
8518: $id.'.y1_min_value' => $Min1,
8519: $id.'.y2_max_value' => $Max2,
8520: $id.'.y2_min_value' => $Min2,
8521: );
8522: #
8523: if (defined($colors) && ref($colors) eq 'ARRAY') {
8524: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8525: }
8526: #
8527: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
8528: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
8529: return '';
8530: }
8531: my $NumSets=1;
8532: foreach my $array ($Ydata1,$Ydata2){
8533: next if (! ref($array));
8534: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8535: }
8536: #
8537: # Deal with other parameters
8538: while (my ($key,$value) = each(%Values)) {
8539: $ValuesHash{$id.'.'.$key} = $value;
8540: }
8541: #
8542: &Apache::lonnet::appenv(\%ValuesHash);
8543: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8544: }
8545:
8546: ############################################################
8547: ############################################################
8548:
8549: =pod
8550:
8551: =back
8552:
8553: =head1 Statistics helper routines?
8554:
8555: Bad place for them but what the hell.
8556:
8557: =over 4
8558:
8559: =item * &chartlink()
8560:
8561: Returns a link to the chart for a specific student.
8562:
8563: Inputs:
8564:
8565: =over 4
8566:
8567: =item $linktext: The text of the link
8568:
8569: =item $sname: The students username
8570:
8571: =item $sdomain: The students domain
8572:
8573: =back
8574:
8575: =back
8576:
8577: =cut
8578:
8579: ############################################################
8580: ############################################################
8581: sub chartlink {
8582: my ($linktext, $sname, $sdomain) = @_;
8583: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
8584: '&SelectedStudent='.&escape($sname.':'.$sdomain).
8585: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
8586: '">'.$linktext.'</a>';
8587: }
8588:
8589: #######################################################
8590: #######################################################
8591:
8592: =pod
8593:
8594: =head1 Course Environment Routines
8595:
8596: =over 4
8597:
8598: =item * &restore_course_settings()
8599:
8600: =item * &store_course_settings()
8601:
8602: Restores/Store indicated form parameters from the course environment.
8603: Will not overwrite existing values of the form parameters.
8604:
8605: Inputs:
8606: a scalar describing the data (e.g. 'chart', 'problem_analysis')
8607:
8608: a hash ref describing the data to be stored. For example:
8609:
8610: %Save_Parameters = ('Status' => 'scalar',
8611: 'chartoutputmode' => 'scalar',
8612: 'chartoutputdata' => 'scalar',
8613: 'Section' => 'array',
8614: 'Group' => 'array',
8615: 'StudentData' => 'array',
8616: 'Maps' => 'array');
8617:
8618: Returns: both routines return nothing
8619:
8620: =back
8621:
8622: =cut
8623:
8624: #######################################################
8625: #######################################################
8626: sub store_course_settings {
8627: return &store_settings($env{'request.course.id'},@_);
8628: }
8629:
8630: sub store_settings {
8631: # save to the environment
8632: # appenv the same items, just to be safe
8633: my $udom = $env{'user.domain'};
8634: my $uname = $env{'user.name'};
8635: my ($context,$prefix,$Settings) = @_;
8636: my %SaveHash;
8637: my %AppHash;
8638: while (my ($setting,$type) = each(%$Settings)) {
8639: my $basename = join('.','internal',$context,$prefix,$setting);
8640: my $envname = 'environment.'.$basename;
8641: if (exists($env{'form.'.$setting})) {
8642: # Save this value away
8643: if ($type eq 'scalar' &&
8644: (! exists($env{$envname}) ||
8645: $env{$envname} ne $env{'form.'.$setting})) {
8646: $SaveHash{$basename} = $env{'form.'.$setting};
8647: $AppHash{$envname} = $env{'form.'.$setting};
8648: } elsif ($type eq 'array') {
8649: my $stored_form;
8650: if (ref($env{'form.'.$setting})) {
8651: $stored_form = join(',',
8652: map {
8653: &escape($_);
8654: } sort(@{$env{'form.'.$setting}}));
8655: } else {
8656: $stored_form =
8657: &escape($env{'form.'.$setting});
8658: }
8659: # Determine if the array contents are the same.
8660: if ($stored_form ne $env{$envname}) {
8661: $SaveHash{$basename} = $stored_form;
8662: $AppHash{$envname} = $stored_form;
8663: }
8664: }
8665: }
8666: }
8667: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
8668: $udom,$uname);
8669: if ($put_result !~ /^(ok|delayed)/) {
8670: &Apache::lonnet::logthis('unable to save form parameters, '.
8671: 'got error:'.$put_result);
8672: }
8673: # Make sure these settings stick around in this session, too
8674: &Apache::lonnet::appenv(\%AppHash);
8675: return;
8676: }
8677:
8678: sub restore_course_settings {
8679: return &restore_settings($env{'request.course.id'},@_);
8680: }
8681:
8682: sub restore_settings {
8683: my ($context,$prefix,$Settings) = @_;
8684: while (my ($setting,$type) = each(%$Settings)) {
8685: next if (exists($env{'form.'.$setting}));
8686: my $envname = 'environment.internal.'.$context.'.'.$prefix.
8687: '.'.$setting;
8688: if (exists($env{$envname})) {
8689: if ($type eq 'scalar') {
8690: $env{'form.'.$setting} = $env{$envname};
8691: } elsif ($type eq 'array') {
8692: $env{'form.'.$setting} = [
8693: map {
8694: &unescape($_);
8695: } split(',',$env{$envname})
8696: ];
8697: }
8698: }
8699: }
8700: }
8701:
8702: #######################################################
8703: #######################################################
8704:
8705: =pod
8706:
8707: =head1 Domain E-mail Routines
8708:
8709: =over 4
8710:
8711: =item * &build_recipient_list()
8712:
8713: Build recipient lists for four types of e-mail:
8714: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
8715: (d) Help requests, generated by
8716: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
8717:
8718: Inputs:
8719: defmail (scalar - email address of default recipient),
8720: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
8721: defdom (domain for which to retrieve configuration settings),
8722: origmail (scalar - email address of recipient from loncapa.conf,
8723: i.e., predates configuration by DC via domainprefs.pm
8724:
8725: Returns: comma separated list of addresses to which to send e-mail.
8726:
8727: =back
8728:
8729: =cut
8730:
8731: ############################################################
8732: ############################################################
8733: sub build_recipient_list {
8734: my ($defmail,$mailing,$defdom,$origmail) = @_;
8735: my @recipients;
8736: my $otheremails;
8737: my %domconfig =
8738: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
8739: if (ref($domconfig{'contacts'}) eq 'HASH') {
8740: if (exists($domconfig{'contacts'}{$mailing})) {
8741: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
8742: my @contacts = ('adminemail','supportemail');
8743: foreach my $item (@contacts) {
8744: if ($domconfig{'contacts'}{$mailing}{$item}) {
8745: my $addr = $domconfig{'contacts'}{$item};
8746: if (!grep(/^\Q$addr\E$/,@recipients)) {
8747: push(@recipients,$addr);
8748: }
8749: }
8750: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
8751: }
8752: }
8753: } elsif ($origmail ne '') {
8754: push(@recipients,$origmail);
8755: }
8756: } elsif ($origmail ne '') {
8757: push(@recipients,$origmail);
8758: }
8759: if (defined($defmail)) {
8760: if ($defmail ne '') {
8761: push(@recipients,$defmail);
8762: }
8763: }
8764: if ($otheremails) {
8765: my @others;
8766: if ($otheremails =~ /,/) {
8767: @others = split(/,/,$otheremails);
8768: } else {
8769: push(@others,$otheremails);
8770: }
8771: foreach my $addr (@others) {
8772: if (!grep(/^\Q$addr\E$/,@recipients)) {
8773: push(@recipients,$addr);
8774: }
8775: }
8776: }
8777: my $recipientlist = join(',',@recipients);
8778: return $recipientlist;
8779: }
8780:
8781: ############################################################
8782: ############################################################
8783:
8784: =pod
8785:
8786: =head1 Course Catalog Routines
8787:
8788: =over 4
8789:
8790: =item * &gather_categories()
8791:
8792: Converts category definitions - keys of categories hash stored in
8793: coursecategories in configuration.db on the primary library server in a
8794: domain - to an array. Also generates javascript and idx hash used to
8795: generate Domain Coordinator interface for editing Course Categories.
8796:
8797: Inputs:
8798:
8799: categories (reference to hash of category definitions).
8800:
8801: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8802: categories and subcategories).
8803:
8804: idx (reference to hash of counters used in Domain Coordinator interface for
8805: editing Course Categories).
8806:
8807: jsarray (reference to array of categories used to create Javascript arrays for
8808: Domain Coordinator interface for editing Course Categories).
8809:
8810: Returns: nothing
8811:
8812: Side effects: populates cats, idx and jsarray.
8813:
8814: =cut
8815:
8816: sub gather_categories {
8817: my ($categories,$cats,$idx,$jsarray) = @_;
8818: my %counters;
8819: my $num = 0;
8820: foreach my $item (keys(%{$categories})) {
8821: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
8822: if ($container eq '' && $depth == 0) {
8823: $cats->[$depth][$categories->{$item}] = $cat;
8824: } else {
8825: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
8826: }
8827: my ($escitem,$tail) = split(/:/,$item,2);
8828: if ($counters{$tail} eq '') {
8829: $counters{$tail} = $num;
8830: $num ++;
8831: }
8832: if (ref($idx) eq 'HASH') {
8833: $idx->{$item} = $counters{$tail};
8834: }
8835: if (ref($jsarray) eq 'ARRAY') {
8836: push(@{$jsarray->[$counters{$tail}]},$item);
8837: }
8838: }
8839: return;
8840: }
8841:
8842: =pod
8843:
8844: =item * &extract_categories()
8845:
8846: Used to generate breadcrumb trails for course categories.
8847:
8848: Inputs:
8849:
8850: categories (reference to hash of category definitions).
8851:
8852: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8853: categories and subcategories).
8854:
8855: trails (reference to array of breacrumb trails for each category).
8856:
8857: allitems (reference to hash - key is category key
8858: (format: escaped(name):escaped(parent category):depth in hierarchy).
8859:
8860: idx (reference to hash of counters used in Domain Coordinator interface for
8861: editing Course Categories).
8862:
8863: jsarray (reference to array of categories used to create Javascript arrays for
8864: Domain Coordinator interface for editing Course Categories).
8865:
8866: subcats (reference to hash of arrays containing all subcategories within each
8867: category, -recursive)
8868:
8869: Returns: nothing
8870:
8871: Side effects: populates trails and allitems hash references.
8872:
8873: =cut
8874:
8875: sub extract_categories {
8876: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
8877: if (ref($categories) eq 'HASH') {
8878: &gather_categories($categories,$cats,$idx,$jsarray);
8879: if (ref($cats->[0]) eq 'ARRAY') {
8880: for (my $i=0; $i<@{$cats->[0]}; $i++) {
8881: my $name = $cats->[0][$i];
8882: my $item = &escape($name).'::0';
8883: my $trailstr;
8884: if ($name eq 'instcode') {
8885: $trailstr = &mt('Official courses (with institutional codes)');
8886: } else {
8887: $trailstr = $name;
8888: }
8889: if ($allitems->{$item} eq '') {
8890: push(@{$trails},$trailstr);
8891: $allitems->{$item} = scalar(@{$trails})-1;
8892: }
8893: my @parents = ($name);
8894: if (ref($cats->[1]{$name}) eq 'ARRAY') {
8895: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
8896: my $category = $cats->[1]{$name}[$j];
8897: if (ref($subcats) eq 'HASH') {
8898: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
8899: }
8900: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
8901: }
8902: } else {
8903: if (ref($subcats) eq 'HASH') {
8904: $subcats->{$item} = [];
8905: }
8906: }
8907: }
8908: }
8909: }
8910: return;
8911: }
8912:
8913: =pod
8914:
8915: =item *&recurse_categories()
8916:
8917: Recursively used to generate breadcrumb trails for course categories.
8918:
8919: Inputs:
8920:
8921: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8922: categories and subcategories).
8923:
8924: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
8925:
8926: category (current course category, for which breadcrumb trail is being generated).
8927:
8928: trails (reference to array of breadcrumb trails for each category).
8929:
8930: allitems (reference to hash - key is category key
8931: (format: escaped(name):escaped(parent category):depth in hierarchy).
8932:
8933: parents (array containing containers directories for current category,
8934: back to top level).
8935:
8936: Returns: nothing
8937:
8938: Side effects: populates trails and allitems hash references
8939:
8940: =cut
8941:
8942: sub recurse_categories {
8943: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
8944: my $shallower = $depth - 1;
8945: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
8946: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
8947: my $name = $cats->[$depth]{$category}[$k];
8948: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8949: my $trailstr = join(' -> ',(@{$parents},$category));
8950: if ($allitems->{$item} eq '') {
8951: push(@{$trails},$trailstr);
8952: $allitems->{$item} = scalar(@{$trails})-1;
8953: }
8954: my $deeper = $depth+1;
8955: push(@{$parents},$category);
8956: if (ref($subcats) eq 'HASH') {
8957: my $subcat = &escape($name).':'.$category.':'.$depth;
8958: for (my $j=@{$parents}; $j>=0; $j--) {
8959: my $higher;
8960: if ($j > 0) {
8961: $higher = &escape($parents->[$j]).':'.
8962: &escape($parents->[$j-1]).':'.$j;
8963: } else {
8964: $higher = &escape($parents->[$j]).'::'.$j;
8965: }
8966: push(@{$subcats->{$higher}},$subcat);
8967: }
8968: }
8969: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
8970: $subcats);
8971: pop(@{$parents});
8972: }
8973: } else {
8974: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8975: my $trailstr = join(' -> ',(@{$parents},$category));
8976: if ($allitems->{$item} eq '') {
8977: push(@{$trails},$trailstr);
8978: $allitems->{$item} = scalar(@{$trails})-1;
8979: }
8980: }
8981: return;
8982: }
8983:
8984: =pod
8985:
8986: =item *&assign_categories_table()
8987:
8988: Create a datatable for display of hierarchical categories in a domain,
8989: with checkboxes to allow a course to be categorized.
8990:
8991: Inputs:
8992:
8993: cathash - reference to hash of categories defined for the domain (from
8994: configuration.db)
8995:
8996: currcat - scalar with an & separated list of categories assigned to a course.
8997:
8998: Returns: $output (markup to be displayed)
8999:
9000: =cut
9001:
9002: sub assign_categories_table {
9003: my ($cathash,$currcat) = @_;
9004: my $output;
9005: if (ref($cathash) eq 'HASH') {
9006: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
9007: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
9008: $maxdepth = scalar(@cats);
9009: if (@cats > 0) {
9010: my $itemcount = 0;
9011: if (ref($cats[0]) eq 'ARRAY') {
9012: $output = &Apache::loncommon::start_data_table();
9013: my @currcategories;
9014: if ($currcat ne '') {
9015: @currcategories = split('&',$currcat);
9016: }
9017: for (my $i=0; $i<@{$cats[0]}; $i++) {
9018: my $parent = $cats[0][$i];
9019: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9020: next if ($parent eq 'instcode');
9021: my $item = &escape($parent).'::0';
9022: my $checked = '';
9023: if (@currcategories > 0) {
9024: if (grep(/^\Q$item\E$/,@currcategories)) {
9025: $checked = ' checked="checked" ';
9026: }
9027: }
9028: $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
9029: '<input type="checkbox" name="usecategory" value="'.
9030: $item.'"'.$checked.' />'.$parent.'</span>'.
9031: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
9032: my $depth = 1;
9033: push(@path,$parent);
9034: $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
9035: pop(@path);
9036: $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
9037: $itemcount ++;
9038: }
9039: $output .= &Apache::loncommon::end_data_table();
9040: }
9041: }
9042: }
9043: return $output;
9044: }
9045:
9046: =pod
9047:
9048: =item *&assign_category_rows()
9049:
9050: Create a datatable row for display of nested categories in a domain,
9051: with checkboxes to allow a course to be categorized,called recursively.
9052:
9053: Inputs:
9054:
9055: itemcount - track row number for alternating colors
9056:
9057: cats - reference to array of arrays/hashes which encapsulates hierarchy of
9058: categories and subcategories.
9059:
9060: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
9061:
9062: parent - parent of current category item
9063:
9064: path - Array containing all categories back up through the hierarchy from the
9065: current category to the top level.
9066:
9067: currcategories - reference to array of current categories assigned to the course
9068:
9069: Returns: $output (markup to be displayed).
9070:
9071: =cut
9072:
9073: sub assign_category_rows {
9074: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
9075: my ($text,$name,$item,$chgstr);
9076: if (ref($cats) eq 'ARRAY') {
9077: my $maxdepth = scalar(@{$cats});
9078: if (ref($cats->[$depth]) eq 'HASH') {
9079: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
9080: my $numchildren = @{$cats->[$depth]{$parent}};
9081: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9082: $text .= '<td><table class="LC_datatable">';
9083: for (my $j=0; $j<$numchildren; $j++) {
9084: $name = $cats->[$depth]{$parent}[$j];
9085: $item = &escape($name).':'.&escape($parent).':'.$depth;
9086: my $deeper = $depth+1;
9087: my $checked = '';
9088: if (ref($currcategories) eq 'ARRAY') {
9089: if (@{$currcategories} > 0) {
9090: if (grep(/^\Q$item\E$/,@{$currcategories})) {
9091: $checked = ' checked="checked" ';
9092: }
9093: }
9094: }
9095: $text .= '<tr><td><span class="LC_nobreak"><label>'.
9096: '<input type="checkbox" name="usecategory" value="'.
9097: $item.'"'.$checked.' />'.$name.'</label></span>'.
9098: '<input type="hidden" name="catname" value="'.$name.'" />'.
9099: '</td><td>';
9100: if (ref($path) eq 'ARRAY') {
9101: push(@{$path},$name);
9102: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
9103: pop(@{$path});
9104: }
9105: $text .= '</td></tr>';
9106: }
9107: $text .= '</table></td>';
9108: }
9109: }
9110: }
9111: return $text;
9112: }
9113:
9114: ############################################################
9115: ############################################################
9116:
9117:
9118: sub commit_customrole {
9119: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
9120: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
9121: ($start?', '.&mt('starting').' '.localtime($start):'').
9122: ($end?', ending '.localtime($end):'').': <b>'.
9123: &Apache::lonnet::assigncustomrole(
9124: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
9125: '</b><br />';
9126: return $output;
9127: }
9128:
9129: sub commit_standardrole {
9130: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9131: my ($output,$logmsg,$linefeed);
9132: if ($context eq 'auto') {
9133: $linefeed = "\n";
9134: } else {
9135: $linefeed = "<br />\n";
9136: }
9137: if ($three eq 'st') {
9138: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9139: $one,$two,$sec,$context);
9140: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9141: ($result eq 'unknown_course') || ($result eq 'refused')) {
9142: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9143: } else {
9144: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9145: ($start?', '.&mt('starting').' '.localtime($start):'').
9146: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9147: if ($context eq 'auto') {
9148: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9149: } else {
9150: $output .= '<b>'.$result.'</b>'.$linefeed.
9151: &mt('Add to classlist').': <b>ok</b>';
9152: }
9153: $output .= $linefeed;
9154: }
9155: } else {
9156: $output = &mt('Assigning').' '.$three.' in '.$url.
9157: ($start?', '.&mt('starting').' '.localtime($start):'').
9158: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9159: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9160: if ($context eq 'auto') {
9161: $output .= $result.$linefeed;
9162: } else {
9163: $output .= '<b>'.$result.'</b>'.$linefeed;
9164: }
9165: }
9166: return $output;
9167: }
9168:
9169: sub commit_studentrole {
9170: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9171: my ($result,$linefeed,$oldsecurl,$newsecurl);
9172: if ($context eq 'auto') {
9173: $linefeed = "\n";
9174: } else {
9175: $linefeed = '<br />'."\n";
9176: }
9177: if (defined($one) && defined($two)) {
9178: my $cid=$one.'_'.$two;
9179: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9180: my $secchange = 0;
9181: my $expire_role_result;
9182: my $modify_section_result;
9183: if ($oldsec ne '-1') {
9184: if ($oldsec ne $sec) {
9185: $secchange = 1;
9186: my $now = time;
9187: my $uurl='/'.$cid;
9188: $uurl=~s/\_/\//g;
9189: if ($oldsec) {
9190: $uurl.='/'.$oldsec;
9191: }
9192: $oldsecurl = $uurl;
9193: $expire_role_result =
9194: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9195: if ($env{'request.course.sec'} ne '') {
9196: if ($expire_role_result eq 'refused') {
9197: my @roles = ('st');
9198: my @statuses = ('previous');
9199: my @roledoms = ($one);
9200: my $withsec = 1;
9201: my %roleshash =
9202: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9203: \@statuses,\@roles,\@roledoms,$withsec);
9204: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9205: my ($oldstart,$oldend) =
9206: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9207: if ($oldend > 0 && $oldend <= $now) {
9208: $expire_role_result = 'ok';
9209: }
9210: }
9211: }
9212: }
9213: $result = $expire_role_result;
9214: }
9215: }
9216: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9217: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9218: if ($modify_section_result =~ /^ok/) {
9219: if ($secchange == 1) {
9220: if ($sec eq '') {
9221: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9222: } else {
9223: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9224: }
9225: } elsif ($oldsec eq '-1') {
9226: if ($sec eq '') {
9227: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9228: } else {
9229: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9230: }
9231: } else {
9232: if ($sec eq '') {
9233: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9234: } else {
9235: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9236: }
9237: }
9238: } else {
9239: if ($secchange) {
9240: $$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;
9241: } else {
9242: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9243: }
9244: }
9245: $result = $modify_section_result;
9246: } elsif ($secchange == 1) {
9247: if ($oldsec eq '') {
9248: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9249: } else {
9250: $$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;
9251: }
9252: if ($expire_role_result eq 'refused') {
9253: my $newsecurl = '/'.$cid;
9254: $newsecurl =~ s/\_/\//g;
9255: if ($sec ne '') {
9256: $newsecurl.='/'.$sec;
9257: }
9258: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9259: if ($sec eq '') {
9260: $$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;
9261: } else {
9262: $$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;
9263: }
9264: }
9265: }
9266: }
9267: } else {
9268: $$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;
9269: $result = "error: incomplete course id\n";
9270: }
9271: return $result;
9272: }
9273:
9274: ############################################################
9275: ############################################################
9276:
9277: sub check_clone {
9278: my ($args,$linefeed) = @_;
9279: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9280: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9281: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9282: my $clonemsg;
9283: my $can_clone = 0;
9284:
9285: if ($clonehome eq 'no_host') {
9286: $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'});
9287: } else {
9288: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9289: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
9290: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
9291: $can_clone = 1;
9292: } else {
9293: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9294: $args->{'clonedomain'},$args->{'clonecourse'});
9295: my @cloners = split(/,/,$clonehash{'cloners'});
9296: if (grep(/^\*$/,@cloners)) {
9297: $can_clone = 1;
9298: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9299: $can_clone = 1;
9300: } else {
9301: my %roleshash =
9302: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9303: $args->{'ccdomain'},
9304: 'userroles',['active'],['cc'],
9305: [$args->{'clonedomain'}]);
9306: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9307: $can_clone = 1;
9308: } else {
9309: $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'});
9310: }
9311: }
9312: }
9313: }
9314: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9315: }
9316:
9317: sub construct_course {
9318: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum) = @_;
9319: my $outcome;
9320: my $linefeed = '<br />'."\n";
9321: if ($context eq 'auto') {
9322: $linefeed = "\n";
9323: }
9324:
9325: #
9326: # Are we cloning?
9327: #
9328: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9329: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9330: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9331: if ($context ne 'auto') {
9332: if ($clonemsg ne '') {
9333: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9334: }
9335: }
9336: $outcome .= $clonemsg.$linefeed;
9337:
9338: if (!$can_clone) {
9339: return (0,$outcome);
9340: }
9341: }
9342:
9343: #
9344: # Open course
9345: #
9346: my $crstype = lc($args->{'crstype'});
9347: my %cenv=();
9348: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9349: $args->{'cdescr'},
9350: $args->{'curl'},
9351: $args->{'course_home'},
9352: $args->{'nonstandard'},
9353: $args->{'crscode'},
9354: $args->{'ccuname'}.':'.
9355: $args->{'ccdomain'},
9356: $args->{'crstype'},
9357: $cnum);
9358:
9359:
9360: # Note: The testing routines depend on this being output; see
9361: # Utils::Course. This needs to at least be output as a comment
9362: # if anyone ever decides to not show this, and Utils::Course::new
9363: # will need to be suitably modified.
9364: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9365: #
9366: # Check if created correctly
9367: #
9368: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9369: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9370: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9371:
9372: #
9373: # Do the cloning
9374: #
9375: if ($can_clone && $cloneid) {
9376: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9377: if ($context ne 'auto') {
9378: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9379: }
9380: $outcome .= $clonemsg.$linefeed;
9381: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9382: # Copy all files
9383: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9384: # Restore URL
9385: $cenv{'url'}=$oldcenv{'url'};
9386: # Restore title
9387: $cenv{'description'}=$oldcenv{'description'};
9388: # Mark as cloned
9389: $cenv{'clonedfrom'}=$cloneid;
9390: # Need to clone grading mode
9391: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9392: $cenv{'grading'}=$newenv{'grading'};
9393: # Do not clone these environment entries
9394: &Apache::lonnet::del('environment',
9395: ['default_enrollment_start_date',
9396: 'default_enrollment_end_date',
9397: 'question.email',
9398: 'policy.email',
9399: 'comment.email',
9400: 'pch.users.denied',
9401: 'plc.users.denied',
9402: 'hidefromcat',
9403: 'categories'],
9404: $$crsudom,$$crsunum);
9405: }
9406:
9407: #
9408: # Set environment (will override cloned, if existing)
9409: #
9410: my @sections = ();
9411: my @xlists = ();
9412: if ($args->{'crstype'}) {
9413: $cenv{'type'}=$args->{'crstype'};
9414: }
9415: if ($args->{'crsid'}) {
9416: $cenv{'courseid'}=$args->{'crsid'};
9417: }
9418: if ($args->{'crscode'}) {
9419: $cenv{'internal.coursecode'}=$args->{'crscode'};
9420: }
9421: if ($args->{'crsquota'} ne '') {
9422: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9423: } else {
9424: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9425: }
9426: if ($args->{'ccuname'}) {
9427: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9428: ':'.$args->{'ccdomain'};
9429: } else {
9430: $cenv{'internal.courseowner'} = $args->{'curruser'};
9431: }
9432: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9433: if ($args->{'crssections'}) {
9434: $cenv{'internal.sectionnums'} = '';
9435: if ($args->{'crssections'} =~ m/,/) {
9436: @sections = split/,/,$args->{'crssections'};
9437: } else {
9438: $sections[0] = $args->{'crssections'};
9439: }
9440: if (@sections > 0) {
9441: foreach my $item (@sections) {
9442: my ($sec,$gp) = split/:/,$item;
9443: my $class = $args->{'crscode'}.$sec;
9444: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9445: $cenv{'internal.sectionnums'} .= $item.',';
9446: unless ($addcheck eq 'ok') {
9447: push @badclasses, $class;
9448: }
9449: }
9450: $cenv{'internal.sectionnums'} =~ s/,$//;
9451: }
9452: }
9453: # do not hide course coordinator from staff listing,
9454: # even if privileged
9455: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9456: # add crosslistings
9457: if ($args->{'crsxlist'}) {
9458: $cenv{'internal.crosslistings'}='';
9459: if ($args->{'crsxlist'} =~ m/,/) {
9460: @xlists = split/,/,$args->{'crsxlist'};
9461: } else {
9462: $xlists[0] = $args->{'crsxlist'};
9463: }
9464: if (@xlists > 0) {
9465: foreach my $item (@xlists) {
9466: my ($xl,$gp) = split/:/,$item;
9467: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9468: $cenv{'internal.crosslistings'} .= $item.',';
9469: unless ($addcheck eq 'ok') {
9470: push @badclasses, $xl;
9471: }
9472: }
9473: $cenv{'internal.crosslistings'} =~ s/,$//;
9474: }
9475: }
9476: if ($args->{'autoadds'}) {
9477: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9478: }
9479: if ($args->{'autodrops'}) {
9480: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9481: }
9482: # check for notification of enrollment changes
9483: my @notified = ();
9484: if ($args->{'notify_owner'}) {
9485: if ($args->{'ccuname'} ne '') {
9486: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9487: }
9488: }
9489: if ($args->{'notify_dc'}) {
9490: if ($uname ne '') {
9491: push(@notified,$uname.':'.$udom);
9492: }
9493: }
9494: if (@notified > 0) {
9495: my $notifylist;
9496: if (@notified > 1) {
9497: $notifylist = join(',',@notified);
9498: } else {
9499: $notifylist = $notified[0];
9500: }
9501: $cenv{'internal.notifylist'} = $notifylist;
9502: }
9503: if (@badclasses > 0) {
9504: my %lt=&Apache::lonlocal::texthash(
9505: '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',
9506: 'dnhr' => 'does not have rights to access enrollment in these classes',
9507: 'adby' => 'as determined by the policies of your institution on access to official classlists'
9508: );
9509: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
9510: ' ('.$lt{'adby'}.')';
9511: if ($context eq 'auto') {
9512: $outcome .= $badclass_msg.$linefeed;
9513: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
9514: foreach my $item (@badclasses) {
9515: if ($context eq 'auto') {
9516: $outcome .= " - $item\n";
9517: } else {
9518: $outcome .= "<li>$item</li>\n";
9519: }
9520: }
9521: if ($context eq 'auto') {
9522: $outcome .= $linefeed;
9523: } else {
9524: $outcome .= "</ul><br /><br /></div>\n";
9525: }
9526: }
9527: }
9528: if ($args->{'no_end_date'}) {
9529: $args->{'endaccess'} = 0;
9530: }
9531: $cenv{'internal.autostart'}=$args->{'enrollstart'};
9532: $cenv{'internal.autoend'}=$args->{'enrollend'};
9533: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
9534: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
9535: if ($args->{'showphotos'}) {
9536: $cenv{'internal.showphotos'}=$args->{'showphotos'};
9537: }
9538: $cenv{'internal.authtype'} = $args->{'authtype'};
9539: $cenv{'internal.autharg'} = $args->{'autharg'};
9540: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
9541: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
9542: 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');
9543: if ($context eq 'auto') {
9544: $outcome .= $krb_msg;
9545: } else {
9546: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
9547: }
9548: $outcome .= $linefeed;
9549: }
9550: }
9551: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
9552: if ($args->{'setpolicy'}) {
9553: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9554: }
9555: if ($args->{'setcontent'}) {
9556: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9557: }
9558: }
9559: if ($args->{'reshome'}) {
9560: $cenv{'reshome'}=$args->{'reshome'}.'/';
9561: $cenv{'reshome'}=~s/\/+$/\//;
9562: }
9563: #
9564: # course has keyed access
9565: #
9566: if ($args->{'setkeys'}) {
9567: $cenv{'keyaccess'}='yes';
9568: }
9569: # if specified, key authority is not course, but user
9570: # only active if keyaccess is yes
9571: if ($args->{'keyauth'}) {
9572: my ($user,$domain) = split(':',$args->{'keyauth'});
9573: $user = &LONCAPA::clean_username($user);
9574: $domain = &LONCAPA::clean_username($domain);
9575: if ($user ne '' && $domain ne '') {
9576: $cenv{'keyauth'}=$user.':'.$domain;
9577: }
9578: }
9579:
9580: if ($args->{'disresdis'}) {
9581: $cenv{'pch.roles.denied'}='st';
9582: }
9583: if ($args->{'disablechat'}) {
9584: $cenv{'plc.roles.denied'}='st';
9585: }
9586:
9587: # Record we've not yet viewed the Course Initialization Helper for this
9588: # course
9589: $cenv{'course.helper.not.run'} = 1;
9590: #
9591: # Use new Randomseed
9592: #
9593: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
9594: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
9595: #
9596: # The encryption code and receipt prefix for this course
9597: #
9598: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
9599: $cenv{'internal.encpref'}=100+int(9*rand(99));
9600: #
9601: # By default, use standard grading
9602: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
9603:
9604: $outcome .= $linefeed.&mt('Setting environment').': '.
9605: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
9606: #
9607: # Open all assignments
9608: #
9609: if ($args->{'openall'}) {
9610: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
9611: my %storecontent = ($storeunder => time,
9612: $storeunder.'.type' => 'date_start');
9613:
9614: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
9615: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
9616: }
9617: #
9618: # Set first page
9619: #
9620: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
9621: || ($cloneid)) {
9622: use LONCAPA::map;
9623: $outcome .= &mt('Setting first resource').': ';
9624:
9625: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
9626: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
9627:
9628: $outcome .= ($fatal?$errtext:'read ok').' - ';
9629: my $title; my $url;
9630: if ($args->{'firstres'} eq 'syl') {
9631: $title=&mt('Syllabus');
9632: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
9633: } else {
9634: $title=&mt('Navigate Contents');
9635: $url='/adm/navmaps';
9636: }
9637:
9638: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
9639: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
9640:
9641: if ($errtext) { $fatal=2; }
9642: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
9643: }
9644:
9645: return (1,$outcome);
9646: }
9647:
9648: ############################################################
9649: ############################################################
9650:
9651: sub course_type {
9652: my ($cid) = @_;
9653: if (!defined($cid)) {
9654: $cid = $env{'request.course.id'};
9655: }
9656: if (defined($env{'course.'.$cid.'.type'})) {
9657: return $env{'course.'.$cid.'.type'};
9658: } else {
9659: return 'Course';
9660: }
9661: }
9662:
9663: sub group_term {
9664: my $crstype = &course_type();
9665: my %names = (
9666: 'Course' => 'group',
9667: 'Community' => 'group',
9668: );
9669: return $names{$crstype};
9670: }
9671:
9672: sub icon {
9673: my ($file)=@_;
9674: my $curfext = lc((split(/\./,$file))[-1]);
9675: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
9676: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
9677: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
9678: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
9679: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9680: $curfext.".gif") {
9681: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9682: $curfext.".gif";
9683: }
9684: }
9685: return &lonhttpdurl($iconname);
9686: }
9687:
9688: sub lonhttpdurl {
9689: #
9690: # Had been used for "small fry" static images on separate port 8080.
9691: # Modify here if lightweight http functionality desired again.
9692: # Currently eliminated due to increasing firewall issues.
9693: #
9694: my ($url)=@_;
9695: return $url;
9696: }
9697:
9698: sub connection_aborted {
9699: my ($r)=@_;
9700: $r->print(" ");$r->rflush();
9701: my $c = $r->connection;
9702: return $c->aborted();
9703: }
9704:
9705: # Escapes strings that may have embedded 's that will be put into
9706: # strings as 'strings'.
9707: sub escape_single {
9708: my ($input) = @_;
9709: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
9710: $input =~ s/\'/\\\'/g; # Esacpe the 's....
9711: return $input;
9712: }
9713:
9714: # Same as escape_single, but escape's "'s This
9715: # can be used for "strings"
9716: sub escape_double {
9717: my ($input) = @_;
9718: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
9719: $input =~ s/\"/\\\"/g; # Esacpe the "s....
9720: return $input;
9721: }
9722:
9723: # Escapes the last element of a full URL.
9724: sub escape_url {
9725: my ($url) = @_;
9726: my @urlslices = split(/\//, $url,-1);
9727: my $lastitem = &escape(pop(@urlslices));
9728: return join('/',@urlslices).'/'.$lastitem;
9729: }
9730:
9731: sub compare_arrays {
9732: my ($arrayref1,$arrayref2) = @_;
9733: my (@difference,%count);
9734: @difference = ();
9735: %count = ();
9736: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
9737: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
9738: foreach my $element (keys(%count)) {
9739: if ($count{$element} == 1) {
9740: push(@difference,$element);
9741: }
9742: }
9743: }
9744: return @difference;
9745: }
9746:
9747: # -------------------------------------------------------- Initliaze user login
9748: sub init_user_environment {
9749: my ($r, $username, $domain, $authhost, $form, $args) = @_;
9750: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
9751:
9752: my $public=($username eq 'public' && $domain eq 'public');
9753:
9754: # See if old ID present, if so, remove
9755:
9756: my ($filename,$cookie,$userroles);
9757: my $now=time;
9758:
9759: if ($public) {
9760: my $max_public=100;
9761: my $oldest;
9762: my $oldest_time=0;
9763: for(my $next=1;$next<=$max_public;$next++) {
9764: if (-e $lonids."/publicuser_$next.id") {
9765: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
9766: if ($mtime<$oldest_time || !$oldest_time) {
9767: $oldest_time=$mtime;
9768: $oldest=$next;
9769: }
9770: } else {
9771: $cookie="publicuser_$next";
9772: last;
9773: }
9774: }
9775: if (!$cookie) { $cookie="publicuser_$oldest"; }
9776: } else {
9777: # if this isn't a robot, kill any existing non-robot sessions
9778: if (!$args->{'robot'}) {
9779: opendir(DIR,$lonids);
9780: while ($filename=readdir(DIR)) {
9781: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
9782: unlink($lonids.'/'.$filename);
9783: }
9784: }
9785: closedir(DIR);
9786: }
9787: # Give them a new cookie
9788: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
9789: : $now.$$.int(rand(10000)));
9790: $cookie="$username\_$id\_$domain\_$authhost";
9791:
9792: # Initialize roles
9793:
9794: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
9795: }
9796: # ------------------------------------ Check browser type and MathML capability
9797:
9798: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
9799: $clientunicode,$clientos) = &decode_user_agent($r);
9800:
9801: # -------------------------------------- Any accessibility options to remember?
9802: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
9803: foreach my $option ('imagesuppress','appletsuppress',
9804: 'embedsuppress','fontenhance','blackwhite') {
9805: if ($form->{$option} eq 'true') {
9806: &Apache::lonnet::put('environment',{$option => 'on'},
9807: $domain,$username);
9808: } else {
9809: &Apache::lonnet::del('environment',[$option],
9810: $domain,$username);
9811: }
9812: }
9813: }
9814: # ------------------------------------------------------------- Get environment
9815:
9816: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
9817: my ($tmp) = keys(%userenv);
9818: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9819: # default remote control to off
9820: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
9821: } else {
9822: undef(%userenv);
9823: }
9824: if (($userenv{'interface'}) && (!$form->{'interface'})) {
9825: $form->{'interface'}=$userenv{'interface'};
9826: }
9827: $env{'environment.remote'}=$userenv{'remote'};
9828: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
9829:
9830: # --------------- Do not trust query string to be put directly into environment
9831: foreach my $option ('imagesuppress','appletsuppress',
9832: 'embedsuppress','fontenhance','blackwhite',
9833: 'interface','localpath','localres') {
9834: $form->{$option}=~s/[\n\r\=]//gs;
9835: }
9836: # --------------------------------------------------------- Write first profile
9837:
9838: {
9839: my %initial_env =
9840: ("user.name" => $username,
9841: "user.domain" => $domain,
9842: "user.home" => $authhost,
9843: "browser.type" => $clientbrowser,
9844: "browser.version" => $clientversion,
9845: "browser.mathml" => $clientmathml,
9846: "browser.unicode" => $clientunicode,
9847: "browser.os" => $clientos,
9848: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
9849: "request.course.fn" => '',
9850: "request.course.uri" => '',
9851: "request.course.sec" => '',
9852: "request.role" => 'cm',
9853: "request.role.adv" => $env{'user.adv'},
9854: "request.host" => $ENV{'REMOTE_ADDR'},);
9855:
9856: if ($form->{'localpath'}) {
9857: $initial_env{"browser.localpath"} = $form->{'localpath'};
9858: $initial_env{"browser.localres"} = $form->{'localres'};
9859: }
9860:
9861: if ($public) {
9862: $initial_env{"environment.remote"} = "off";
9863: }
9864: if ($form->{'interface'}) {
9865: $form->{'interface'}=~s/\W//gs;
9866: $initial_env{"browser.interface"} = $form->{'interface'};
9867: $env{'browser.interface'}=$form->{'interface'};
9868: foreach my $option ('imagesuppress','appletsuppress',
9869: 'embedsuppress','fontenhance','blackwhite') {
9870: if (($form->{$option} eq 'true') ||
9871: ($userenv{$option} eq 'on')) {
9872: $initial_env{"browser.$option"} = "on";
9873: }
9874: }
9875: }
9876:
9877: foreach my $tool ('aboutme','blog','portfolio') {
9878: $userenv{'availabletools.'.$tool} =
9879: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
9880: }
9881:
9882: foreach my $crstype ('official','unofficial','community') {
9883: $userenv{'canrequest.'.$crstype} =
9884: &Apache::lonnet::usertools_access($username,$domain,$crstype,
9885: 'reload','requestcourses');
9886: }
9887:
9888: $env{'user.environment'} = "$lonids/$cookie.id";
9889:
9890: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
9891: &GDBM_WRCREAT(),0640)) {
9892: &_add_to_env(\%disk_env,\%initial_env);
9893: &_add_to_env(\%disk_env,\%userenv,'environment.');
9894: &_add_to_env(\%disk_env,$userroles);
9895: if (ref($args->{'extra_env'})) {
9896: &_add_to_env(\%disk_env,$args->{'extra_env'});
9897: }
9898: untie(%disk_env);
9899: } else {
9900: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
9901: 'Could not create environment storage in lonauth: '.$!.'</font>');
9902: return 'error: '.$!;
9903: }
9904: }
9905: $env{'request.role'}='cm';
9906: $env{'request.role.adv'}=$env{'user.adv'};
9907: $env{'browser.type'}=$clientbrowser;
9908:
9909: return $cookie;
9910:
9911: }
9912:
9913: sub _add_to_env {
9914: my ($idf,$env_data,$prefix) = @_;
9915: if (ref($env_data) eq 'HASH') {
9916: while (my ($key,$value) = each(%$env_data)) {
9917: $idf->{$prefix.$key} = $value;
9918: $env{$prefix.$key} = $value;
9919: }
9920: }
9921: }
9922:
9923: # --- Get the symbolic name of a problem and the url
9924: sub get_symb {
9925: my ($request,$silent) = @_;
9926: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9927: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
9928: if ($symb eq '') {
9929: if (!$silent) {
9930: $request->print("Unable to handle ambiguous references:$url:.");
9931: return ();
9932: }
9933: }
9934: &Apache::lonenc::check_decrypt(\$symb);
9935: return ($symb);
9936: }
9937:
9938: # --------------------------------------------------------------Get annotation
9939:
9940: sub get_annotation {
9941: my ($symb,$enc) = @_;
9942:
9943: my $key = $symb;
9944: if (!$enc) {
9945: $key =
9946: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
9947: }
9948: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
9949: return $annotation{$key};
9950: }
9951:
9952: sub clean_symb {
9953: my ($symb,$delete_enc) = @_;
9954:
9955: &Apache::lonenc::check_decrypt(\$symb);
9956: my $enc = $env{'request.enc'};
9957: if ($delete_enc) {
9958: delete($env{'request.enc'});
9959: }
9960:
9961: return ($symb,$enc);
9962: }
9963:
9964: =pod
9965:
9966: =back
9967:
9968: =cut
9969:
9970: 1;
9971: __END__;
9972:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>