1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1028.2.1 2011/12/26 13:47:18 foxr 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 %latex_language; # Language name LaTeX uses for selecting hyphenation.
158: my %cprtag;
159: my %scprtag;
160: my %fe; my %fd; my %fm;
161: my %category_extensions;
162:
163: # ---------------------------------------------- Thesaurus variables
164: #
165: # %Keywords:
166: # A hash used by &keyword to determine if a word is considered a keyword.
167: # $thesaurus_db_file
168: # Scalar containing the full path to the thesaurus database.
169:
170: my %Keywords;
171: my $thesaurus_db_file;
172:
173: #
174: # Initialize values from language.tab, copyright.tab, filetypes.tab,
175: # thesaurus.tab, and filecategories.tab.
176: #
177: BEGIN {
178: # Variable initialization
179: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
180: #
181: unless ($readit) {
182: # ------------------------------------------------------------------- languages
183: {
184: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
185: '/language.tab';
186: if ( open(my $fh,"<$langtabfile") ) {
187: while (my $line = <$fh>) {
188: next if ($line=~/^\#/);
189: chomp($line);
190: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
191: $language{$key}=$val.' - '.$enc;
192: if ($sup) {
193: $supported_language{$key}=$sup;
194: }
195: if ($latex) {
196: $latex_language{$two} = $latex;
197: }
198: }
199: close($fh);
200: }
201: }
202: # ------------------------------------------------------------------ copyrights
203: {
204: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
205: '/copyright.tab';
206: if ( open (my $fh,"<$copyrightfile") ) {
207: while (my $line = <$fh>) {
208: next if ($line=~/^\#/);
209: chomp($line);
210: my ($key,$val)=(split(/\s+/,$line,2));
211: $cprtag{$key}=$val;
212: }
213: close($fh);
214: }
215: }
216: # ----------------------------------------------------------- source copyrights
217: {
218: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
219: '/source_copyright.tab';
220: if ( open (my $fh,"<$sourcecopyrightfile") ) {
221: while (my $line = <$fh>) {
222: next if ($line =~ /^\#/);
223: chomp($line);
224: my ($key,$val)=(split(/\s+/,$line,2));
225: $scprtag{$key}=$val;
226: }
227: close($fh);
228: }
229: }
230:
231: # -------------------------------------------------------------- default domain designs
232: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
233: my $designfile = $designdir.'/default.tab';
234: if ( open (my $fh,"<$designfile") ) {
235: while (my $line = <$fh>) {
236: next if ($line =~ /^\#/);
237: chomp($line);
238: my ($key,$val)=(split(/\=/,$line));
239: if ($val) { $defaultdesign{$key}=$val; }
240: }
241: close($fh);
242: }
243:
244: # ------------------------------------------------------------- file categories
245: {
246: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
247: '/filecategories.tab';
248: if ( open (my $fh,"<$categoryfile") ) {
249: while (my $line = <$fh>) {
250: next if ($line =~ /^\#/);
251: chomp($line);
252: my ($extension,$category)=(split(/\s+/,$line,2));
253: push @{$category_extensions{lc($category)}},$extension;
254: }
255: close($fh);
256: }
257:
258: }
259: # ------------------------------------------------------------------ file types
260: {
261: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
262: '/filetypes.tab';
263: if ( open (my $fh,"<$typesfile") ) {
264: while (my $line = <$fh>) {
265: next if ($line =~ /^\#/);
266: chomp($line);
267: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
268: if ($descr ne '') {
269: $fe{$ending}=lc($emb);
270: $fd{$ending}=$descr;
271: if ($mime ne 'unk') { $fm{$ending}=$mime; }
272: }
273: }
274: close($fh);
275: }
276: }
277: &Apache::lonnet::logthis(
278: "<span style='color:yellow;'>INFO: Read file types</span>");
279: $readit=1;
280: } # end of unless($readit)
281:
282: }
283:
284: ###############################################################
285: ## HTML and Javascript Helper Functions ##
286: ###############################################################
287:
288: =pod
289:
290: =head1 HTML and Javascript Functions
291:
292: =over 4
293:
294: =item * &browser_and_searcher_javascript()
295:
296: X<browsing, javascript>X<searching, javascript>Returns a string
297: containing javascript with two functions, C<openbrowser> and
298: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
299: tags.
300:
301: =item * &openbrowser(formname,elementname,only,omit) [javascript]
302:
303: inputs: formname, elementname, only, omit
304:
305: formname and elementname indicate the name of the html form and name of
306: the element that the results of the browsing selection are to be placed in.
307:
308: Specifying 'only' will restrict the browser to displaying only files
309: with the given extension. Can be a comma separated list.
310:
311: Specifying 'omit' will restrict the browser to NOT displaying files
312: with the given extension. Can be a comma separated list.
313:
314: =item * &opensearcher(formname,elementname) [javascript]
315:
316: Inputs: formname, elementname
317:
318: formname and elementname specify the name of the html form and the name
319: of the element the selection from the search results will be placed in.
320:
321: =cut
322:
323: sub browser_and_searcher_javascript {
324: my ($mode)=@_;
325: if (!defined($mode)) { $mode='edit'; }
326: my $resurl=&escape_single(&lastresurl());
327: return <<END;
328: // <!-- BEGIN LON-CAPA Internal
329: var editbrowser = null;
330: function openbrowser(formname,elementname,only,omit,titleelement) {
331: var url = '$resurl/?';
332: if (editbrowser == null) {
333: url += 'launch=1&';
334: }
335: url += 'catalogmode=interactive&';
336: url += 'mode=$mode&';
337: url += 'inhibitmenu=yes&';
338: url += 'form=' + formname + '&';
339: if (only != null) {
340: url += 'only=' + only + '&';
341: } else {
342: url += 'only=&';
343: }
344: if (omit != null) {
345: url += 'omit=' + omit + '&';
346: } else {
347: url += 'omit=&';
348: }
349: if (titleelement != null) {
350: url += 'titleelement=' + titleelement + '&';
351: } else {
352: url += 'titleelement=&';
353: }
354: url += 'element=' + elementname + '';
355: var title = 'Browser';
356: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
357: options += ',width=700,height=600';
358: editbrowser = open(url,title,options,'1');
359: editbrowser.focus();
360: }
361: var editsearcher;
362: function opensearcher(formname,elementname,titleelement) {
363: var url = '/adm/searchcat?';
364: if (editsearcher == null) {
365: url += 'launch=1&';
366: }
367: url += 'catalogmode=interactive&';
368: url += 'mode=$mode&';
369: url += 'form=' + formname + '&';
370: if (titleelement != null) {
371: url += 'titleelement=' + titleelement + '&';
372: } else {
373: url += 'titleelement=&';
374: }
375: url += 'element=' + elementname + '';
376: var title = 'Search';
377: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
378: options += ',width=700,height=600';
379: editsearcher = open(url,title,options,'1');
380: editsearcher.focus();
381: }
382: // END LON-CAPA Internal -->
383: END
384: }
385:
386: sub lastresurl {
387: if ($env{'environment.lastresurl'}) {
388: return $env{'environment.lastresurl'}
389: } else {
390: return '/res';
391: }
392: }
393:
394: sub storeresurl {
395: my $resurl=&Apache::lonnet::clutter(shift);
396: unless ($resurl=~/^\/res/) { return 0; }
397: $resurl=~s/\/$//;
398: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
399: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
400: return 1;
401: }
402:
403: sub studentbrowser_javascript {
404: unless (
405: (($env{'request.course.id'}) &&
406: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
407: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
408: '/'.$env{'request.course.sec'})
409: ))
410: || ($env{'request.role'}=~/^(au|dc|su)/)
411: ) { return ''; }
412: return (<<'ENDSTDBRW');
413: <script type="text/javascript" language="Javascript">
414: // <![CDATA[
415: var stdeditbrowser;
416: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
417: var url = '/adm/pickstudent?';
418: var filter;
419: if (!ignorefilter) {
420: eval('filter=document.'+formname+'.'+uname+'.value;');
421: }
422: if (filter != null) {
423: if (filter != '') {
424: url += 'filter='+filter+'&';
425: }
426: }
427: url += 'form=' + formname + '&unameelement='+uname+
428: '&udomelement='+udom+
429: '&clicker='+clicker;
430: if (roleflag) { url+="&roles=1"; }
431: if (courseadvonly) { url+="&courseadvonly=1"; }
432: var title = 'Student_Browser';
433: var options = 'scrollbars=1,resizable=1,menubar=0';
434: options += ',width=700,height=600';
435: stdeditbrowser = open(url,title,options,'1');
436: stdeditbrowser.focus();
437: }
438: // ]]>
439: </script>
440: ENDSTDBRW
441: }
442:
443: sub resourcebrowser_javascript {
444: unless ($env{'request.course.id'}) { return ''; }
445: return (<<'ENDRESBRW');
446: <script type="text/javascript" language="Javascript">
447: // <![CDATA[
448: var reseditbrowser;
449: function openresbrowser(formname,reslink) {
450: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
451: var title = 'Resource_Browser';
452: var options = 'scrollbars=1,resizable=1,menubar=0';
453: options += ',width=700,height=500';
454: reseditbrowser = open(url,title,options,'1');
455: reseditbrowser.focus();
456: }
457: // ]]>
458: </script>
459: ENDRESBRW
460: }
461:
462: sub selectstudent_link {
463: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
464: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
465: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
466: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
467: if ($env{'request.course.id'}) {
468: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
469: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
470: '/'.$env{'request.course.sec'})) {
471: return '';
472: }
473: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
474: if ($courseadvonly) {
475: $callargs .= ",'',1,1";
476: }
477: return '<span class="LC_nobreak">'.
478: '<a href="javascript:openstdbrowser('.$callargs.');">'.
479: &mt('Select User').'</a></span>';
480: }
481: if ($env{'request.role'}=~/^(au|dc|su)/) {
482: $callargs .= ",'',1";
483: return '<span class="LC_nobreak">'.
484: '<a href="javascript:openstdbrowser('.$callargs.');">'.
485: &mt('Select User').'</a></span>';
486: }
487: return '';
488: }
489:
490: sub selectresource_link {
491: my ($form,$reslink,$arg)=@_;
492:
493: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
494: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
495: unless ($env{'request.course.id'}) { return $arg; }
496: return '<span class="LC_nobreak">'.
497: '<a href="javascript:openresbrowser('.$callargs.');">'.
498: $arg.'</a></span>';
499: }
500:
501:
502:
503: sub authorbrowser_javascript {
504: return <<"ENDAUTHORBRW";
505: <script type="text/javascript" language="JavaScript">
506: // <![CDATA[
507: var stdeditbrowser;
508:
509: function openauthorbrowser(formname,udom) {
510: var url = '/adm/pickauthor?';
511: url += 'form='+formname+'&roledom='+udom;
512: var title = 'Author_Browser';
513: var options = 'scrollbars=1,resizable=1,menubar=0';
514: options += ',width=700,height=600';
515: stdeditbrowser = open(url,title,options,'1');
516: stdeditbrowser.focus();
517: }
518:
519: // ]]>
520: </script>
521: ENDAUTHORBRW
522: }
523:
524: sub coursebrowser_javascript {
525: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
526: my $wintitle = 'Course_Browser';
527: if ($crstype eq 'Community') {
528: $wintitle = 'Community_Browser';
529: }
530: my $id_functions = &javascript_index_functions();
531: my $output = '
532: <script type="text/javascript" language="JavaScript">
533: // <![CDATA[
534: var stdeditbrowser;'."\n";
535:
536: $output .= <<"ENDSTDBRW";
537: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
538: var url = '/adm/pickcourse?';
539: var formid = getFormIdByName(formname);
540: var domainfilter = getDomainFromSelectbox(formname,udom);
541: if (domainfilter != null) {
542: if (domainfilter != '') {
543: url += 'domainfilter='+domainfilter+'&';
544: }
545: }
546: url += 'form=' + formname + '&cnumelement='+uname+
547: '&cdomelement='+udom+
548: '&cnameelement='+desc;
549: if (extra_element !=null && extra_element != '') {
550: if (formname == 'rolechoice' || formname == 'studentform') {
551: url += '&roleelement='+extra_element;
552: if (domainfilter == null || domainfilter == '') {
553: url += '&domainfilter='+extra_element;
554: }
555: }
556: else {
557: if (formname == 'portform') {
558: url += '&setroles='+extra_element;
559: } else {
560: if (formname == 'rules') {
561: url += '&fixeddom='+extra_element;
562: }
563: }
564: }
565: }
566: if (type != null && type != '') {
567: url += '&type='+type;
568: }
569: if (type_elem != null && type_elem != '') {
570: url += '&typeelement='+type_elem;
571: }
572: if (formname == 'ccrs') {
573: var ownername = document.forms[formid].ccuname.value;
574: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
575: url += '&cloner='+ownername+':'+ownerdom;
576: }
577: if (multflag !=null && multflag != '') {
578: url += '&multiple='+multflag;
579: }
580: var title = '$wintitle';
581: var options = 'scrollbars=1,resizable=1,menubar=0';
582: options += ',width=700,height=600';
583: stdeditbrowser = open(url,title,options,'1');
584: stdeditbrowser.focus();
585: }
586: $id_functions
587: ENDSTDBRW
588: if (($sec_element ne '') || ($role_element ne '')) {
589: $output .= &setsec_javascript($sec_element,$formname,$role_element);
590: }
591: $output .= '
592: // ]]>
593: </script>';
594: return $output;
595: }
596:
597: sub javascript_index_functions {
598: return <<"ENDJS";
599:
600: function getFormIdByName(formname) {
601: for (var i=0;i<document.forms.length;i++) {
602: if (document.forms[i].name == formname) {
603: return i;
604: }
605: }
606: return -1;
607: }
608:
609: function getIndexByName(formid,item) {
610: for (var i=0;i<document.forms[formid].elements.length;i++) {
611: if (document.forms[formid].elements[i].name == item) {
612: return i;
613: }
614: }
615: return -1;
616: }
617:
618: function getDomainFromSelectbox(formname,udom) {
619: var userdom;
620: var formid = getFormIdByName(formname);
621: if (formid > -1) {
622: var domid = getIndexByName(formid,udom);
623: if (domid > -1) {
624: if (document.forms[formid].elements[domid].type == 'select-one') {
625: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
626: }
627: if (document.forms[formid].elements[domid].type == 'hidden') {
628: userdom=document.forms[formid].elements[domid].value;
629: }
630: }
631: }
632: return userdom;
633: }
634:
635: ENDJS
636:
637: }
638:
639: sub javascript_array_indexof {
640: return <<ENDJS;
641: <script type="text/javascript" language="JavaScript">
642: // <![CDATA[
643:
644: if (!Array.prototype.indexOf) {
645: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
646: "use strict";
647: if (this === void 0 || this === null) {
648: throw new TypeError();
649: }
650: var t = Object(this);
651: var len = t.length >>> 0;
652: if (len === 0) {
653: return -1;
654: }
655: var n = 0;
656: if (arguments.length > 0) {
657: n = Number(arguments[1]);
658: if (n !== n) { // shortcut for verifying if it's NaN
659: n = 0;
660: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
661: n = (n > 0 || -1) * Math.floor(Math.abs(n));
662: }
663: }
664: if (n >= len) {
665: return -1;
666: }
667: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
668: for (; k < len; k++) {
669: if (k in t && t[k] === searchElement) {
670: return k;
671: }
672: }
673: return -1;
674: }
675: }
676:
677: // ]]>
678: </script>
679:
680: ENDJS
681:
682: }
683:
684: sub userbrowser_javascript {
685: my $id_functions = &javascript_index_functions();
686: return <<"ENDUSERBRW";
687:
688: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
689: var url = '/adm/pickuser?';
690: var userdom = getDomainFromSelectbox(formname,udom);
691: if (userdom != null) {
692: if (userdom != '') {
693: url += 'srchdom='+userdom+'&';
694: }
695: }
696: url += 'form=' + formname + '&unameelement='+uname+
697: '&udomelement='+udom+
698: '&ulastelement='+ulast+
699: '&ufirstelement='+ufirst+
700: '&uemailelement='+uemail+
701: '&hideudomelement='+hideudom+
702: '&coursedom='+crsdom;
703: if ((caller != null) && (caller != undefined)) {
704: url += '&caller='+caller;
705: }
706: var title = 'User_Browser';
707: var options = 'scrollbars=1,resizable=1,menubar=0';
708: options += ',width=700,height=600';
709: var stdeditbrowser = open(url,title,options,'1');
710: stdeditbrowser.focus();
711: }
712:
713: function fix_domain (formname,udom,origdom,uname) {
714: var formid = getFormIdByName(formname);
715: if (formid > -1) {
716: var unameid = getIndexByName(formid,uname);
717: var domid = getIndexByName(formid,udom);
718: var hidedomid = getIndexByName(formid,origdom);
719: if (hidedomid > -1) {
720: var fixeddom = document.forms[formid].elements[hidedomid].value;
721: var unameval = document.forms[formid].elements[unameid].value;
722: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
723: if (domid > -1) {
724: var slct = document.forms[formid].elements[domid];
725: if (slct.type == 'select-one') {
726: var i;
727: for (i=0;i<slct.length;i++) {
728: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
729: }
730: }
731: if (slct.type == 'hidden') {
732: slct.value = fixeddom;
733: }
734: }
735: }
736: }
737: }
738: return;
739: }
740:
741: $id_functions
742: ENDUSERBRW
743: }
744:
745: sub setsec_javascript {
746: my ($sec_element,$formname,$role_element) = @_;
747: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
748: $communityrolestr);
749: if ($role_element ne '') {
750: my @allroles = ('st','ta','ep','in','ad');
751: foreach my $crstype ('Course','Community') {
752: if ($crstype eq 'Community') {
753: foreach my $role (@allroles) {
754: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
755: }
756: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
757: } else {
758: foreach my $role (@allroles) {
759: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
760: }
761: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
762: }
763: }
764: $rolestr = '"'.join('","',@allroles).'"';
765: $courserolestr = '"'.join('","',@courserolenames).'"';
766: $communityrolestr = '"'.join('","',@communityrolenames).'"';
767: }
768: my $setsections = qq|
769: function setSect(sectionlist) {
770: var sectionsArray = new Array();
771: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
772: sectionsArray = sectionlist.split(",");
773: }
774: var numSections = sectionsArray.length;
775: document.$formname.$sec_element.length = 0;
776: if (numSections == 0) {
777: document.$formname.$sec_element.multiple=false;
778: document.$formname.$sec_element.size=1;
779: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
780: } else {
781: if (numSections == 1) {
782: document.$formname.$sec_element.multiple=false;
783: document.$formname.$sec_element.size=1;
784: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
785: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
786: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
787: } else {
788: for (var i=0; i<numSections; i++) {
789: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
790: }
791: document.$formname.$sec_element.multiple=true
792: if (numSections < 3) {
793: document.$formname.$sec_element.size=numSections;
794: } else {
795: document.$formname.$sec_element.size=3;
796: }
797: document.$formname.$sec_element.options[0].selected = false
798: }
799: }
800: }
801:
802: function setRole(crstype) {
803: |;
804: if ($role_element eq '') {
805: $setsections .= ' return;
806: }
807: ';
808: } else {
809: $setsections .= qq|
810: var elementLength = document.$formname.$role_element.length;
811: var allroles = Array($rolestr);
812: var courserolenames = Array($courserolestr);
813: var communityrolenames = Array($communityrolestr);
814: if (elementLength != undefined) {
815: if (document.$formname.$role_element.options[5].value == 'cc') {
816: if (crstype == 'Course') {
817: return;
818: } else {
819: allroles[5] = 'co';
820: for (var i=0; i<6; i++) {
821: document.$formname.$role_element.options[i].value = allroles[i];
822: document.$formname.$role_element.options[i].text = communityrolenames[i];
823: }
824: }
825: } else {
826: if (crstype == 'Community') {
827: return;
828: } else {
829: allroles[5] = 'cc';
830: for (var i=0; i<6; i++) {
831: document.$formname.$role_element.options[i].value = allroles[i];
832: document.$formname.$role_element.options[i].text = courserolenames[i];
833: }
834: }
835: }
836: }
837: return;
838: }
839: |;
840: }
841: return $setsections;
842: }
843:
844: sub selectcourse_link {
845: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
846: $typeelement) = @_;
847: my $type = $selecttype;
848: my $linktext = &mt('Select Course');
849: if ($selecttype eq 'Community') {
850: $linktext = &mt('Select Community');
851: } elsif ($selecttype eq 'Course/Community') {
852: $linktext = &mt('Select Course/Community');
853: $type = '';
854: } elsif ($selecttype eq 'Select') {
855: $linktext = &mt('Select');
856: $type = '';
857: }
858: return '<span class="LC_nobreak">'
859: ."<a href='"
860: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
861: .'","'.$udomele.'","'.$desc.'","'.$extra_element
862: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
863: ."'>".$linktext.'</a>'
864: .'</span>';
865: }
866:
867: sub selectauthor_link {
868: my ($form,$udom)=@_;
869: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
870: &mt('Select Author').'</a>';
871: }
872:
873: sub selectuser_link {
874: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
875: $coursedom,$linktext,$caller) = @_;
876: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
877: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
878: ');">'.$linktext.'</a>';
879: }
880:
881: sub check_uncheck_jscript {
882: my $jscript = <<"ENDSCRT";
883: function checkAll(field) {
884: if (field.length > 0) {
885: for (i = 0; i < field.length; i++) {
886: field[i].checked = true ;
887: }
888: } else {
889: field.checked = true
890: }
891: }
892:
893: function uncheckAll(field) {
894: if (field.length > 0) {
895: for (i = 0; i < field.length; i++) {
896: field[i].checked = false ;
897: }
898: } else {
899: field.checked = false ;
900: }
901: }
902: ENDSCRT
903: return $jscript;
904: }
905:
906: sub select_timezone {
907: my ($name,$selected,$onchange,$includeempty)=@_;
908: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
909: if ($includeempty) {
910: $output .= '<option value=""';
911: if (($selected eq '') || ($selected eq 'local')) {
912: $output .= ' selected="selected" ';
913: }
914: $output .= '> </option>';
915: }
916: my @timezones = DateTime::TimeZone->all_names;
917: foreach my $tzone (@timezones) {
918: $output.= '<option value="'.$tzone.'"';
919: if ($tzone eq $selected) {
920: $output.=' selected="selected"';
921: }
922: $output.=">$tzone</option>\n";
923: }
924: $output.="</select>";
925: return $output;
926: }
927:
928: sub select_datelocale {
929: my ($name,$selected,$onchange,$includeempty)=@_;
930: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
931: if ($includeempty) {
932: $output .= '<option value=""';
933: if ($selected eq '') {
934: $output .= ' selected="selected" ';
935: }
936: $output .= '> </option>';
937: }
938: my (@possibles,%locale_names);
939: my @locales = DateTime::Locale::Catalog::Locales;
940: foreach my $locale (@locales) {
941: if (ref($locale) eq 'HASH') {
942: my $id = $locale->{'id'};
943: if ($id ne '') {
944: my $en_terr = $locale->{'en_territory'};
945: my $native_terr = $locale->{'native_territory'};
946: my @languages = &Apache::lonlocal::preferred_languages();
947: if (grep(/^en$/,@languages) || !@languages) {
948: if ($en_terr ne '') {
949: $locale_names{$id} = '('.$en_terr.')';
950: } elsif ($native_terr ne '') {
951: $locale_names{$id} = $native_terr;
952: }
953: } else {
954: if ($native_terr ne '') {
955: $locale_names{$id} = $native_terr.' ';
956: } elsif ($en_terr ne '') {
957: $locale_names{$id} = '('.$en_terr.')';
958: }
959: }
960: push (@possibles,$id);
961: }
962: }
963: }
964: foreach my $item (sort(@possibles)) {
965: $output.= '<option value="'.$item.'"';
966: if ($item eq $selected) {
967: $output.=' selected="selected"';
968: }
969: $output.=">$item";
970: if ($locale_names{$item} ne '') {
971: $output.=" $locale_names{$item}</option>\n";
972: }
973: $output.="</option>\n";
974: }
975: $output.="</select>";
976: return $output;
977: }
978:
979: sub select_language {
980: my ($name,$selected,$includeempty) = @_;
981: my %langchoices;
982: if ($includeempty) {
983: %langchoices = ('' => 'No language preference');
984: }
985: foreach my $id (&languageids()) {
986: my $code = &supportedlanguagecode($id);
987: if ($code) {
988: $langchoices{$code} = &plainlanguagedescription($id);
989: }
990: }
991: return &select_form($selected,$name,\%langchoices);
992: }
993:
994: =pod
995:
996: =item * &linked_select_forms(...)
997:
998: linked_select_forms returns a string containing a <script></script> block
999: and html for two <select> menus. The select menus will be linked in that
1000: changing the value of the first menu will result in new values being placed
1001: in the second menu. The values in the select menu will appear in alphabetical
1002: order unless a defined order is provided.
1003:
1004: linked_select_forms takes the following ordered inputs:
1005:
1006: =over 4
1007:
1008: =item * $formname, the name of the <form> tag
1009:
1010: =item * $middletext, the text which appears between the <select> tags
1011:
1012: =item * $firstdefault, the default value for the first menu
1013:
1014: =item * $firstselectname, the name of the first <select> tag
1015:
1016: =item * $secondselectname, the name of the second <select> tag
1017:
1018: =item * $hashref, a reference to a hash containing the data for the menus.
1019:
1020: =item * $menuorder, the order of values in the first menu
1021:
1022: =back
1023:
1024: Below is an example of such a hash. Only the 'text', 'default', and
1025: 'select2' keys must appear as stated. keys(%menu) are the possible
1026: values for the first select menu. The text that coincides with the
1027: first menu value is given in $menu{$choice1}->{'text'}. The values
1028: and text for the second menu are given in the hash pointed to by
1029: $menu{$choice1}->{'select2'}.
1030:
1031: my %menu = ( A1 => { text =>"Choice A1" ,
1032: default => "B3",
1033: select2 => {
1034: B1 => "Choice B1",
1035: B2 => "Choice B2",
1036: B3 => "Choice B3",
1037: B4 => "Choice B4"
1038: },
1039: order => ['B4','B3','B1','B2'],
1040: },
1041: A2 => { text =>"Choice A2" ,
1042: default => "C2",
1043: select2 => {
1044: C1 => "Choice C1",
1045: C2 => "Choice C2",
1046: C3 => "Choice C3"
1047: },
1048: order => ['C2','C1','C3'],
1049: },
1050: A3 => { text =>"Choice A3" ,
1051: default => "D6",
1052: select2 => {
1053: D1 => "Choice D1",
1054: D2 => "Choice D2",
1055: D3 => "Choice D3",
1056: D4 => "Choice D4",
1057: D5 => "Choice D5",
1058: D6 => "Choice D6",
1059: D7 => "Choice D7"
1060: },
1061: order => ['D4','D3','D2','D1','D7','D6','D5'],
1062: }
1063: );
1064:
1065: =cut
1066:
1067: sub linked_select_forms {
1068: my ($formname,
1069: $middletext,
1070: $firstdefault,
1071: $firstselectname,
1072: $secondselectname,
1073: $hashref,
1074: $menuorder,
1075: ) = @_;
1076: my $second = "document.$formname.$secondselectname";
1077: my $first = "document.$formname.$firstselectname";
1078: # output the javascript to do the changing
1079: my $result = '';
1080: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1081: $result.="// <![CDATA[\n";
1082: $result.="var select2data = new Object();\n";
1083: $" = '","';
1084: my $debug = '';
1085: foreach my $s1 (sort(keys(%$hashref))) {
1086: $result.="select2data.d_$s1 = new Object();\n";
1087: $result.="select2data.d_$s1.def = new String('".
1088: $hashref->{$s1}->{'default'}."');\n";
1089: $result.="select2data.d_$s1.values = new Array(";
1090: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1091: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1092: @s2values = @{$hashref->{$s1}->{'order'}};
1093: }
1094: $result.="\"@s2values\");\n";
1095: $result.="select2data.d_$s1.texts = new Array(";
1096: my @s2texts;
1097: foreach my $value (@s2values) {
1098: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1099: }
1100: $result.="\"@s2texts\");\n";
1101: }
1102: $"=' ';
1103: $result.= <<"END";
1104:
1105: function select1_changed() {
1106: // Determine new choice
1107: var newvalue = "d_" + $first.value;
1108: // update select2
1109: var values = select2data[newvalue].values;
1110: var texts = select2data[newvalue].texts;
1111: var select2def = select2data[newvalue].def;
1112: var i;
1113: // out with the old
1114: for (i = 0; i < $second.options.length; i++) {
1115: $second.options[i] = null;
1116: }
1117: // in with the nuclear
1118: for (i=0;i<values.length; i++) {
1119: $second.options[i] = new Option(values[i]);
1120: $second.options[i].value = values[i];
1121: $second.options[i].text = texts[i];
1122: if (values[i] == select2def) {
1123: $second.options[i].selected = true;
1124: }
1125: }
1126: }
1127: // ]]>
1128: </script>
1129: END
1130: # output the initial values for the selection lists
1131: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1132: my @order = sort(keys(%{$hashref}));
1133: if (ref($menuorder) eq 'ARRAY') {
1134: @order = @{$menuorder};
1135: }
1136: foreach my $value (@order) {
1137: $result.=" <option value=\"$value\" ";
1138: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1139: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1140: }
1141: $result .= "</select>\n";
1142: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1143: $result .= $middletext;
1144: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
1145: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1146:
1147: my @secondorder = sort(keys(%select2));
1148: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1149: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1150: }
1151: foreach my $value (@secondorder) {
1152: $result.=" <option value=\"$value\" ";
1153: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1154: $result.=">".&mt($select2{$value})."</option>\n";
1155: }
1156: $result .= "</select>\n";
1157: # return $debug;
1158: return $result;
1159: } # end of sub linked_select_forms {
1160:
1161: =pod
1162:
1163: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1164:
1165: Returns a string corresponding to an HTML link to the given help
1166: $topic, where $topic corresponds to the name of a .tex file in
1167: /home/httpd/html/adm/help/tex, with underscores replaced by
1168: spaces.
1169:
1170: $text will optionally be linked to the same topic, allowing you to
1171: link text in addition to the graphic. If you do not want to link
1172: text, but wish to specify one of the later parameters, pass an
1173: empty string.
1174:
1175: $stayOnPage is a value that will be interpreted as a boolean. If true,
1176: the link will not open a new window. If false, the link will open
1177: a new window using Javascript. (Default is false.)
1178:
1179: $width and $height are optional numerical parameters that will
1180: override the width and height of the popped up window, which may
1181: be useful for certain help topics with big pictures included.
1182:
1183: $imgid is the id of the img tag used for the help icon. This may be
1184: used in a javascript call to switch the image src. See
1185: lonhtmlcommon::htmlareaselectactive() for an example.
1186:
1187: =cut
1188:
1189: sub help_open_topic {
1190: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1191: $text = "" if (not defined $text);
1192: $stayOnPage = 0 if (not defined $stayOnPage);
1193: $width = 350 if (not defined $width);
1194: $height = 400 if (not defined $height);
1195: my $filename = $topic;
1196: $filename =~ s/ /_/g;
1197:
1198: my $template = "";
1199: my $link;
1200:
1201: $topic=~s/\W/\_/g;
1202:
1203: if (!$stayOnPage) {
1204: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1205: } else {
1206: $link = "/adm/help/${filename}.hlp";
1207: }
1208:
1209: # Add the text
1210: if ($text ne "") {
1211: $template.='<span class="LC_help_open_topic">'
1212: .'<a target="_top" href="'.$link.'">'
1213: .$text.'</a>';
1214: }
1215:
1216: # (Always) Add the graphic
1217: my $title = &mt('Online Help');
1218: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1219: if ($imgid ne '') {
1220: $imgid = ' id="'.$imgid.'"';
1221: }
1222: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1223: .'<img src="'.$helpicon.'" border="0"'
1224: .' alt="'.&mt('Help: [_1]',$topic).'"'
1225: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1226: .' /></a>';
1227: if ($text ne "") {
1228: $template.='</span>';
1229: }
1230: return $template;
1231:
1232: }
1233:
1234: # This is a quicky function for Latex cheatsheet editing, since it
1235: # appears in at least four places
1236: sub helpLatexCheatsheet {
1237: my ($topic,$text,$not_author) = @_;
1238: my $out;
1239: my $addOther = '';
1240: if ($topic) {
1241: $addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
1242: undef, undef, 600).
1243: '</span> ';
1244: }
1245: $out = '<span>' # Start cheatsheet
1246: .$addOther
1247: .'<span>'
1248: .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
1249: undef,undef,600)
1250: .'</span> <span>'
1251: .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
1252: undef,undef,600)
1253: .'</span>';
1254: unless ($not_author) {
1255: $out .= ' <span>'
1256: .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
1257: undef,undef,600)
1258: .'</span>';
1259: }
1260: $out .= '</span>'; # End cheatsheet
1261: return $out;
1262: }
1263:
1264: sub general_help {
1265: my $helptopic='Student_Intro';
1266: if ($env{'request.role'}=~/^(ca|au)/) {
1267: $helptopic='Authoring_Intro';
1268: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1269: $helptopic='Course_Coordination_Intro';
1270: } elsif ($env{'request.role'}=~/^dc/) {
1271: $helptopic='Domain_Coordination_Intro';
1272: }
1273: return $helptopic;
1274: }
1275:
1276: sub update_help_link {
1277: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1278: my $origurl = $ENV{'REQUEST_URI'};
1279: $origurl=~s|^/~|/priv/|;
1280: my $timestamp = time;
1281: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1282: $$datum = &escape($$datum);
1283: }
1284:
1285: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1286: my $output .= <<"ENDOUTPUT";
1287: <script type="text/javascript">
1288: // <![CDATA[
1289: banner_link = '$banner_link';
1290: // ]]>
1291: </script>
1292: ENDOUTPUT
1293: return $output;
1294: }
1295:
1296: # now just updates the help link and generates a blue icon
1297: sub help_open_menu {
1298: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1299: = @_;
1300: $stayOnPage = 1;
1301: my $output;
1302: if ($component_help) {
1303: if (!$text) {
1304: $output=&help_open_topic($component_help,undef,$stayOnPage,
1305: $width,$height);
1306: } else {
1307: my $help_text;
1308: $help_text=&unescape($topic);
1309: $output='<table><tr><td>'.
1310: &help_open_topic($component_help,$help_text,$stayOnPage,
1311: $width,$height).'</td></tr></table>';
1312: }
1313: }
1314: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1315: return $output.$banner_link;
1316: }
1317:
1318: sub top_nav_help {
1319: my ($text) = @_;
1320: $text = &mt($text);
1321: my $stay_on_page = 1;
1322:
1323: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1324: : "javascript:helpMenu('open')";
1325: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1326:
1327: my $title = &mt('Get help');
1328:
1329: return <<"END";
1330: $banner_link
1331: <a href="$link" title="$title">$text</a>
1332: END
1333: }
1334:
1335: sub help_menu_js {
1336: my ($text) = @_;
1337: my $stayOnPage = 1;
1338: my $width = 620;
1339: my $height = 600;
1340: my $helptopic=&general_help();
1341: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1342: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1343: my $start_page =
1344: &Apache::loncommon::start_page('Help Menu', undef,
1345: {'frameset' => 1,
1346: 'js_ready' => 1,
1347: 'add_entries' => {
1348: 'border' => '0',
1349: 'rows' => "110,*",},});
1350: my $end_page =
1351: &Apache::loncommon::end_page({'frameset' => 1,
1352: 'js_ready' => 1,});
1353:
1354: my $template .= <<"ENDTEMPLATE";
1355: <script type="text/javascript">
1356: // <![CDATA[
1357: // <!-- BEGIN LON-CAPA Internal
1358: var banner_link = '';
1359: function helpMenu(target) {
1360: var caller = this;
1361: if (target == 'open') {
1362: var newWindow = null;
1363: try {
1364: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1365: }
1366: catch(error) {
1367: writeHelp(caller);
1368: return;
1369: }
1370: if (newWindow) {
1371: caller = newWindow;
1372: }
1373: }
1374: writeHelp(caller);
1375: return;
1376: }
1377: function writeHelp(caller) {
1378: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1379: caller.document.close()
1380: caller.focus()
1381: }
1382: // END LON-CAPA Internal -->
1383: // ]]>
1384: </script>
1385: ENDTEMPLATE
1386: return $template;
1387: }
1388:
1389: sub help_open_bug {
1390: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1391: unless ($env{'user.adv'}) { return ''; }
1392: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1393: $text = "" if (not defined $text);
1394: $stayOnPage=1;
1395: $width = 600 if (not defined $width);
1396: $height = 600 if (not defined $height);
1397:
1398: $topic=~s/\W+/\+/g;
1399: my $link='';
1400: my $template='';
1401: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1402: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1403: if (!$stayOnPage)
1404: {
1405: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1406: }
1407: else
1408: {
1409: $link = $url;
1410: }
1411: # Add the text
1412: if ($text ne "")
1413: {
1414: $template .=
1415: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1416: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1417: }
1418:
1419: # Add the graphic
1420: my $title = &mt('Report a Bug');
1421: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1422: $template .= <<"ENDTEMPLATE";
1423: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1424: ENDTEMPLATE
1425: if ($text ne '') { $template.='</td></tr></table>' };
1426: return $template;
1427:
1428: }
1429:
1430: sub help_open_faq {
1431: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1432: unless ($env{'user.adv'}) { return ''; }
1433: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1434: $text = "" if (not defined $text);
1435: $stayOnPage=1;
1436: $width = 350 if (not defined $width);
1437: $height = 400 if (not defined $height);
1438:
1439: $topic=~s/\W+/\+/g;
1440: my $link='';
1441: my $template='';
1442: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1443: if (!$stayOnPage)
1444: {
1445: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1446: }
1447: else
1448: {
1449: $link = $url;
1450: }
1451:
1452: # Add the text
1453: if ($text ne "")
1454: {
1455: $template .=
1456: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1457: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1458: }
1459:
1460: # Add the graphic
1461: my $title = &mt('View the FAQ');
1462: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1463: $template .= <<"ENDTEMPLATE";
1464: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1465: ENDTEMPLATE
1466: if ($text ne '') { $template.='</td></tr></table>' };
1467: return $template;
1468:
1469: }
1470:
1471: ###############################################################
1472: ###############################################################
1473:
1474: =pod
1475:
1476: =item * &change_content_javascript():
1477:
1478: This and the next function allow you to create small sections of an
1479: otherwise static HTML page that you can update on the fly with
1480: Javascript, even in Netscape 4.
1481:
1482: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1483: must be written to the HTML page once. It will prove the Javascript
1484: function "change(name, content)". Calling the change function with the
1485: name of the section
1486: you want to update, matching the name passed to C<changable_area>, and
1487: the new content you want to put in there, will put the content into
1488: that area.
1489:
1490: B<Note>: Netscape 4 only reserves enough space for the changable area
1491: to contain room for the original contents. You need to "make space"
1492: for whatever changes you wish to make, and be B<sure> to check your
1493: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1494: it's adequate for updating a one-line status display, but little more.
1495: This script will set the space to 100% width, so you only need to
1496: worry about height in Netscape 4.
1497:
1498: Modern browsers are much less limiting, and if you can commit to the
1499: user not using Netscape 4, this feature may be used freely with
1500: pretty much any HTML.
1501:
1502: =cut
1503:
1504: sub change_content_javascript {
1505: # If we're on Netscape 4, we need to use Layer-based code
1506: if ($env{'browser.type'} eq 'netscape' &&
1507: $env{'browser.version'} =~ /^4\./) {
1508: return (<<NETSCAPE4);
1509: function change(name, content) {
1510: doc = document.layers[name+"___escape"].layers[0].document;
1511: doc.open();
1512: doc.write(content);
1513: doc.close();
1514: }
1515: NETSCAPE4
1516: } else {
1517: # Otherwise, we need to use semi-standards-compliant code
1518: # (technically, "innerHTML" isn't standard but the equivalent
1519: # is really scary, and every useful browser supports it
1520: return (<<DOMBASED);
1521: function change(name, content) {
1522: element = document.getElementById(name);
1523: element.innerHTML = content;
1524: }
1525: DOMBASED
1526: }
1527: }
1528:
1529: =pod
1530:
1531: =item * &changable_area($name,$origContent):
1532:
1533: This provides a "changable area" that can be modified on the fly via
1534: the Javascript code provided in C<change_content_javascript>. $name is
1535: the name you will use to reference the area later; do not repeat the
1536: same name on a given HTML page more then once. $origContent is what
1537: the area will originally contain, which can be left blank.
1538:
1539: =cut
1540:
1541: sub changable_area {
1542: my ($name, $origContent) = @_;
1543:
1544: if ($env{'browser.type'} eq 'netscape' &&
1545: $env{'browser.version'} =~ /^4\./) {
1546: # If this is netscape 4, we need to use the Layer tag
1547: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1548: } else {
1549: return "<span id='$name'>$origContent</span>";
1550: }
1551: }
1552:
1553: =pod
1554:
1555: =item * &viewport_geometry_js
1556:
1557: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1558:
1559: =cut
1560:
1561:
1562: sub viewport_geometry_js {
1563: return <<"GEOMETRY";
1564: var Geometry = {};
1565: function init_geometry() {
1566: if (Geometry.init) { return };
1567: Geometry.init=1;
1568: if (window.innerHeight) {
1569: Geometry.getViewportHeight = function() { return window.innerHeight; };
1570: Geometry.getViewportWidth = function() { return window.innerWidth; };
1571: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1572: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1573: }
1574: else if (document.documentElement && document.documentElement.clientHeight) {
1575: Geometry.getViewportHeight =
1576: function() { return document.documentElement.clientHeight; };
1577: Geometry.getViewportWidth =
1578: function() { return document.documentElement.clientWidth; };
1579:
1580: Geometry.getHorizontalScroll =
1581: function() { return document.documentElement.scrollLeft; };
1582: Geometry.getVerticalScroll =
1583: function() { return document.documentElement.scrollTop; };
1584: }
1585: else if (document.body.clientHeight) {
1586: Geometry.getViewportHeight =
1587: function() { return document.body.clientHeight; };
1588: Geometry.getViewportWidth =
1589: function() { return document.body.clientWidth; };
1590: Geometry.getHorizontalScroll =
1591: function() { return document.body.scrollLeft; };
1592: Geometry.getVerticalScroll =
1593: function() { return document.body.scrollTop; };
1594: }
1595: }
1596:
1597: GEOMETRY
1598: }
1599:
1600: =pod
1601:
1602: =item * &viewport_size_js()
1603:
1604: 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.
1605:
1606: =cut
1607:
1608: sub viewport_size_js {
1609: my $geometry = &viewport_geometry_js();
1610: return <<"DIMS";
1611:
1612: $geometry
1613:
1614: function getViewportDims(width,height) {
1615: init_geometry();
1616: width.value = Geometry.getViewportWidth();
1617: height.value = Geometry.getViewportHeight();
1618: return;
1619: }
1620:
1621: DIMS
1622: }
1623:
1624: =pod
1625:
1626: =item * &resize_textarea_js()
1627:
1628: emits the needed javascript to resize a textarea to be as big as possible
1629:
1630: creates a function resize_textrea that takes two IDs first should be
1631: the id of the element to resize, second should be the id of a div that
1632: surrounds everything that comes after the textarea, this routine needs
1633: to be attached to the <body> for the onload and onresize events.
1634:
1635: =back
1636:
1637: =cut
1638:
1639: sub resize_textarea_js {
1640: my $geometry = &viewport_geometry_js();
1641: return <<"RESIZE";
1642: <script type="text/javascript">
1643: // <![CDATA[
1644: $geometry
1645:
1646: function getX(element) {
1647: var x = 0;
1648: while (element) {
1649: x += element.offsetLeft;
1650: element = element.offsetParent;
1651: }
1652: return x;
1653: }
1654: function getY(element) {
1655: var y = 0;
1656: while (element) {
1657: y += element.offsetTop;
1658: element = element.offsetParent;
1659: }
1660: return y;
1661: }
1662:
1663:
1664: function resize_textarea(textarea_id,bottom_id) {
1665: init_geometry();
1666: var textarea = document.getElementById(textarea_id);
1667: //alert(textarea);
1668:
1669: var textarea_top = getY(textarea);
1670: var textarea_height = textarea.offsetHeight;
1671: var bottom = document.getElementById(bottom_id);
1672: var bottom_top = getY(bottom);
1673: var bottom_height = bottom.offsetHeight;
1674: var window_height = Geometry.getViewportHeight();
1675: var fudge = 23;
1676: var new_height = window_height-fudge-textarea_top-bottom_height;
1677: if (new_height < 300) {
1678: new_height = 300;
1679: }
1680: textarea.style.height=new_height+'px';
1681: }
1682: // ]]>
1683: </script>
1684: RESIZE
1685:
1686: }
1687:
1688: =pod
1689:
1690: =head1 Excel and CSV file utility routines
1691:
1692: =over 4
1693:
1694: =cut
1695:
1696: ###############################################################
1697: ###############################################################
1698:
1699: =pod
1700:
1701: =item * &csv_translate($text)
1702:
1703: Translate $text to allow it to be output as a 'comma separated values'
1704: format.
1705:
1706: =cut
1707:
1708: ###############################################################
1709: ###############################################################
1710: sub csv_translate {
1711: my $text = shift;
1712: $text =~ s/\"/\"\"/g;
1713: $text =~ s/\n/ /g;
1714: return $text;
1715: }
1716:
1717: ###############################################################
1718: ###############################################################
1719:
1720: =pod
1721:
1722: =item * &define_excel_formats()
1723:
1724: Define some commonly used Excel cell formats.
1725:
1726: Currently supported formats:
1727:
1728: =over 4
1729:
1730: =item header
1731:
1732: =item bold
1733:
1734: =item h1
1735:
1736: =item h2
1737:
1738: =item h3
1739:
1740: =item h4
1741:
1742: =item i
1743:
1744: =item date
1745:
1746: =back
1747:
1748: Inputs: $workbook
1749:
1750: Returns: $format, a hash reference.
1751:
1752: =cut
1753:
1754: ###############################################################
1755: ###############################################################
1756: sub define_excel_formats {
1757: my ($workbook) = @_;
1758: my $format;
1759: $format->{'header'} = $workbook->add_format(bold => 1,
1760: bottom => 1,
1761: align => 'center');
1762: $format->{'bold'} = $workbook->add_format(bold=>1);
1763: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1764: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1765: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1766: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1767: $format->{'i'} = $workbook->add_format(italic=>1);
1768: $format->{'date'} = $workbook->add_format(num_format=>
1769: 'mm/dd/yyyy hh:mm:ss');
1770: return $format;
1771: }
1772:
1773: ###############################################################
1774: ###############################################################
1775:
1776: =pod
1777:
1778: =item * &create_workbook()
1779:
1780: Create an Excel worksheet. If it fails, output message on the
1781: request object and return undefs.
1782:
1783: Inputs: Apache request object
1784:
1785: Returns (undef) on failure,
1786: Excel worksheet object, scalar with filename, and formats
1787: from &Apache::loncommon::define_excel_formats on success
1788:
1789: =cut
1790:
1791: ###############################################################
1792: ###############################################################
1793: sub create_workbook {
1794: my ($r) = @_;
1795: #
1796: # Create the excel spreadsheet
1797: my $filename = '/prtspool/'.
1798: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1799: time.'_'.rand(1000000000).'.xls';
1800: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1801: if (! defined($workbook)) {
1802: $r->log_error("Error creating excel spreadsheet $filename: $!");
1803: $r->print(
1804: '<p class="LC_error">'
1805: .&mt('Problems occurred in creating the new Excel file.')
1806: .' '.&mt('This error has been logged.')
1807: .' '.&mt('Please alert your LON-CAPA administrator.')
1808: .'</p>'
1809: );
1810: return (undef);
1811: }
1812: #
1813: $workbook->set_tempdir(LONCAPA::tempdir());
1814: #
1815: my $format = &Apache::loncommon::define_excel_formats($workbook);
1816: return ($workbook,$filename,$format);
1817: }
1818:
1819: ###############################################################
1820: ###############################################################
1821:
1822: =pod
1823:
1824: =item * &create_text_file()
1825:
1826: Create a file to write to and eventually make available to the user.
1827: If file creation fails, outputs an error message on the request object and
1828: return undefs.
1829:
1830: Inputs: Apache request object, and file suffix
1831:
1832: Returns (undef) on failure,
1833: Filehandle and filename on success.
1834:
1835: =cut
1836:
1837: ###############################################################
1838: ###############################################################
1839: sub create_text_file {
1840: my ($r,$suffix) = @_;
1841: if (! defined($suffix)) { $suffix = 'txt'; };
1842: my $fh;
1843: my $filename = '/prtspool/'.
1844: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1845: time.'_'.rand(1000000000).'.'.$suffix;
1846: $fh = Apache::File->new('>/home/httpd'.$filename);
1847: if (! defined($fh)) {
1848: $r->log_error("Couldn't open $filename for output $!");
1849: $r->print(
1850: '<p class="LC_error">'
1851: .&mt('Problems occurred in creating the output file.')
1852: .' '.&mt('This error has been logged.')
1853: .' '.&mt('Please alert your LON-CAPA administrator.')
1854: .'</p>'
1855: );
1856: }
1857: return ($fh,$filename)
1858: }
1859:
1860:
1861: =pod
1862:
1863: =back
1864:
1865: =cut
1866:
1867: ###############################################################
1868: ## Home server <option> list generating code ##
1869: ###############################################################
1870:
1871: # ------------------------------------------
1872:
1873: sub domain_select {
1874: my ($name,$value,$multiple)=@_;
1875: my %domains=map {
1876: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1877: } &Apache::lonnet::all_domains();
1878: if ($multiple) {
1879: $domains{''}=&mt('Any domain');
1880: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1881: return &multiple_select_form($name,$value,4,\%domains);
1882: } else {
1883: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1884: return &select_form($name,$value,\%domains);
1885: }
1886: }
1887:
1888: #-------------------------------------------
1889:
1890: =pod
1891:
1892: =head1 Routines for form select boxes
1893:
1894: =over 4
1895:
1896: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1897:
1898: Returns a string containing a <select> element int multiple mode
1899:
1900:
1901: Args:
1902: $name - name of the <select> element
1903: $value - scalar or array ref of values that should already be selected
1904: $size - number of rows long the select element is
1905: $hash - the elements should be 'option' => 'shown text'
1906: (shown text should already have been &mt())
1907: $order - (optional) array ref of the order to show the elements in
1908:
1909: =cut
1910:
1911: #-------------------------------------------
1912: sub multiple_select_form {
1913: my ($name,$value,$size,$hash,$order)=@_;
1914: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1915: my $output='';
1916: if (! defined($size)) {
1917: $size = 4;
1918: if (scalar(keys(%$hash))<4) {
1919: $size = scalar(keys(%$hash));
1920: }
1921: }
1922: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1923: my @order;
1924: if (ref($order) eq 'ARRAY') {
1925: @order = @{$order};
1926: } else {
1927: @order = sort(keys(%$hash));
1928: }
1929: if (exists($$hash{'select_form_order'})) {
1930: @order = @{$$hash{'select_form_order'}};
1931: }
1932:
1933: foreach my $key (@order) {
1934: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1935: $output.='selected="selected" ' if ($selected{$key});
1936: $output.='>'.$hash->{$key}."</option>\n";
1937: }
1938: $output.="</select>\n";
1939: return $output;
1940: }
1941:
1942: #-------------------------------------------
1943:
1944: =pod
1945:
1946: =item * &select_form($defdom,$name,$hashref,$onchange)
1947:
1948: Returns a string containing a <select name='$name' size='1'> form to
1949: allow a user to select options from a ref to a hash containing:
1950: option_name => displayed text. An optional $onchange can include
1951: a javascript onchange item, e.g., onchange="this.form.submit();"
1952:
1953: See lonrights.pm for an example invocation and use.
1954:
1955: =cut
1956:
1957: #-------------------------------------------
1958: sub select_form {
1959: my ($def,$name,$hashref,$onchange) = @_;
1960: return unless (ref($hashref) eq 'HASH');
1961: if ($onchange) {
1962: $onchange = ' onchange="'.$onchange.'"';
1963: }
1964: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1965: my @keys;
1966: if (exists($hashref->{'select_form_order'})) {
1967: @keys=@{$hashref->{'select_form_order'}};
1968: } else {
1969: @keys=sort(keys(%{$hashref}));
1970: }
1971: foreach my $key (@keys) {
1972: $selectform.=
1973: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1974: ($key eq $def ? 'selected="selected" ' : '').
1975: ">".$hashref->{$key}."</option>\n";
1976: }
1977: $selectform.="</select>";
1978: return $selectform;
1979: }
1980:
1981: # For display filters
1982:
1983: sub display_filter {
1984: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1985: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1986: return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1987: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1988: (&mt('all'),10,20,50,100,1000,10000))).
1989: '</label></span> <span class="LC_nobreak">'.
1990: &mt('Filter [_1]',
1991: &select_form($env{'form.displayfilter'},
1992: 'displayfilter',
1993: {'currentfolder' => 'Current folder/page',
1994: 'containing' => 'Containing phrase',
1995: 'none' => 'None'})).
1996: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1997: }
1998:
1999: sub gradeleveldescription {
2000: my $gradelevel=shift;
2001: my %gradelevels=(0 => 'Not specified',
2002: 1 => 'Grade 1',
2003: 2 => 'Grade 2',
2004: 3 => 'Grade 3',
2005: 4 => 'Grade 4',
2006: 5 => 'Grade 5',
2007: 6 => 'Grade 6',
2008: 7 => 'Grade 7',
2009: 8 => 'Grade 8',
2010: 9 => 'Grade 9',
2011: 10 => 'Grade 10',
2012: 11 => 'Grade 11',
2013: 12 => 'Grade 12',
2014: 13 => 'Grade 13',
2015: 14 => '100 Level',
2016: 15 => '200 Level',
2017: 16 => '300 Level',
2018: 17 => '400 Level',
2019: 18 => 'Graduate Level');
2020: return &mt($gradelevels{$gradelevel});
2021: }
2022:
2023: sub select_level_form {
2024: my ($deflevel,$name)=@_;
2025: unless ($deflevel) { $deflevel=0; }
2026: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2027: for (my $i=0; $i<=18; $i++) {
2028: $selectform.="<option value=\"$i\" ".
2029: ($i==$deflevel ? 'selected="selected" ' : '').
2030: ">".&gradeleveldescription($i)."</option>\n";
2031: }
2032: $selectform.="</select>";
2033: return $selectform;
2034: }
2035:
2036: #-------------------------------------------
2037:
2038: =pod
2039:
2040: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
2041:
2042: Returns a string containing a <select name='$name' size='1'> form to
2043: allow a user to select the domain to preform an operation in.
2044: See loncreateuser.pm for an example invocation and use.
2045:
2046: If the $includeempty flag is set, it also includes an empty choice ("no domain
2047: selected");
2048:
2049: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2050:
2051: 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.
2052:
2053: The optional $incdoms is a reference to an array of domains which will be the only available options.
2054:
2055: =cut
2056:
2057: #-------------------------------------------
2058: sub select_dom_form {
2059: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
2060: if ($onchange) {
2061: $onchange = ' onchange="'.$onchange.'"';
2062: }
2063: my @domains;
2064: if (ref($incdoms) eq 'ARRAY') {
2065: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2066: } else {
2067: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2068: }
2069: if ($includeempty) { @domains=('',@domains); }
2070: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2071: foreach my $dom (@domains) {
2072: $selectdomain.="<option value=\"$dom\" ".
2073: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2074: if ($showdomdesc) {
2075: if ($dom ne '') {
2076: my $domdesc = &Apache::lonnet::domain($dom,'description');
2077: if ($domdesc ne '') {
2078: $selectdomain .= ' ('.$domdesc.')';
2079: }
2080: }
2081: }
2082: $selectdomain .= "</option>\n";
2083: }
2084: $selectdomain.="</select>";
2085: return $selectdomain;
2086: }
2087:
2088: #-------------------------------------------
2089:
2090: =pod
2091:
2092: =item * &home_server_form_item($domain,$name,$defaultflag)
2093:
2094: input: 4 arguments (two required, two optional) -
2095: $domain - domain of new user
2096: $name - name of form element
2097: $default - Value of 'default' causes a default item to be first
2098: option, and selected by default.
2099: $hide - Value of 'hide' causes hiding of the name of the server,
2100: if 1 server found, or default, if 0 found.
2101: output: returns 2 items:
2102: (a) form element which contains either:
2103: (i) <select name="$name">
2104: <option value="$hostid1">$hostid $servers{$hostid}</option>
2105: <option value="$hostid2">$hostid $servers{$hostid}</option>
2106: </select>
2107: form item if there are multiple library servers in $domain, or
2108: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2109: if there is only one library server in $domain.
2110:
2111: (b) number of library servers found.
2112:
2113: See loncreateuser.pm for example of use.
2114:
2115: =cut
2116:
2117: #-------------------------------------------
2118: sub home_server_form_item {
2119: my ($domain,$name,$default,$hide) = @_;
2120: my %servers = &Apache::lonnet::get_servers($domain,'library');
2121: my $result;
2122: my $numlib = keys(%servers);
2123: if ($numlib > 1) {
2124: $result .= '<select name="'.$name.'" />'."\n";
2125: if ($default) {
2126: $result .= '<option value="default" selected="selected">'.&mt('default').
2127: '</option>'."\n";
2128: }
2129: foreach my $hostid (sort(keys(%servers))) {
2130: $result.= '<option value="'.$hostid.'">'.
2131: $hostid.' '.$servers{$hostid}."</option>\n";
2132: }
2133: $result .= '</select>'."\n";
2134: } elsif ($numlib == 1) {
2135: my $hostid;
2136: foreach my $item (keys(%servers)) {
2137: $hostid = $item;
2138: }
2139: $result .= '<input type="hidden" name="'.$name.'" value="'.
2140: $hostid.'" />';
2141: if (!$hide) {
2142: $result .= $hostid.' '.$servers{$hostid};
2143: }
2144: $result .= "\n";
2145: } elsif ($default) {
2146: $result .= '<input type="hidden" name="'.$name.
2147: '" value="default" />';
2148: if (!$hide) {
2149: $result .= &mt('default');
2150: }
2151: $result .= "\n";
2152: }
2153: return ($result,$numlib);
2154: }
2155:
2156: =pod
2157:
2158: =back
2159:
2160: =cut
2161:
2162: ###############################################################
2163: ## Decoding User Agent ##
2164: ###############################################################
2165:
2166: =pod
2167:
2168: =head1 Decoding the User Agent
2169:
2170: =over 4
2171:
2172: =item * &decode_user_agent()
2173:
2174: Inputs: $r
2175:
2176: Outputs:
2177:
2178: =over 4
2179:
2180: =item * $httpbrowser
2181:
2182: =item * $clientbrowser
2183:
2184: =item * $clientversion
2185:
2186: =item * $clientmathml
2187:
2188: =item * $clientunicode
2189:
2190: =item * $clientos
2191:
2192: =back
2193:
2194: =back
2195:
2196: =cut
2197:
2198: ###############################################################
2199: ###############################################################
2200: sub decode_user_agent {
2201: my ($r)=@_;
2202: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2203: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2204: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2205: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2206: my $clientbrowser='unknown';
2207: my $clientversion='0';
2208: my $clientmathml='';
2209: my $clientunicode='0';
2210: for (my $i=0;$i<=$#browsertype;$i++) {
2211: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2212: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2213: $clientbrowser=$bname;
2214: $httpbrowser=~/$vreg/i;
2215: $clientversion=$1;
2216: $clientmathml=($clientversion>=$minv);
2217: $clientunicode=($clientversion>=$univ);
2218: }
2219: }
2220: my $clientos='unknown';
2221: if (($httpbrowser=~/linux/i) ||
2222: ($httpbrowser=~/unix/i) ||
2223: ($httpbrowser=~/ux/i) ||
2224: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2225: if (($httpbrowser=~/vax/i) ||
2226: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2227: if ($httpbrowser=~/next/i) { $clientos='next'; }
2228: if (($httpbrowser=~/mac/i) ||
2229: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2230: if ($httpbrowser=~/win/i) { $clientos='win'; }
2231: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2232: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2233: $clientunicode,$clientos,);
2234: }
2235:
2236: ###############################################################
2237: ## Authentication changing form generation subroutines ##
2238: ###############################################################
2239: ##
2240: ## All of the authform_xxxxxxx subroutines take their inputs in a
2241: ## hash, and have reasonable default values.
2242: ##
2243: ## formname = the name given in the <form> tag.
2244: #-------------------------------------------
2245:
2246: =pod
2247:
2248: =head1 Authentication Routines
2249:
2250: =over 4
2251:
2252: =item * &authform_xxxxxx()
2253:
2254: The authform_xxxxxx subroutines provide javascript and html forms which
2255: handle some of the conveniences required for authentication forms.
2256: This is not an optimal method, but it works.
2257:
2258: =over 4
2259:
2260: =item * authform_header
2261:
2262: =item * authform_authorwarning
2263:
2264: =item * authform_nochange
2265:
2266: =item * authform_kerberos
2267:
2268: =item * authform_internal
2269:
2270: =item * authform_filesystem
2271:
2272: =back
2273:
2274: See loncreateuser.pm for invocation and use examples.
2275:
2276: =cut
2277:
2278: #-------------------------------------------
2279: sub authform_header{
2280: my %in = (
2281: formname => 'cu',
2282: kerb_def_dom => '',
2283: @_,
2284: );
2285: $in{'formname'} = 'document.' . $in{'formname'};
2286: my $result='';
2287:
2288: #---------------------------------------------- Code for upper case translation
2289: my $Javascript_toUpperCase;
2290: unless ($in{kerb_def_dom}) {
2291: $Javascript_toUpperCase =<<"END";
2292: switch (choice) {
2293: case 'krb': currentform.elements[choicearg].value =
2294: currentform.elements[choicearg].value.toUpperCase();
2295: break;
2296: default:
2297: }
2298: END
2299: } else {
2300: $Javascript_toUpperCase = "";
2301: }
2302:
2303: my $radioval = "'nochange'";
2304: if (defined($in{'curr_authtype'})) {
2305: if ($in{'curr_authtype'} ne '') {
2306: $radioval = "'".$in{'curr_authtype'}."arg'";
2307: }
2308: }
2309: my $argfield = 'null';
2310: if (defined($in{'mode'})) {
2311: if ($in{'mode'} eq 'modifycourse') {
2312: if (defined($in{'curr_autharg'})) {
2313: if ($in{'curr_autharg'} ne '') {
2314: $argfield = "'$in{'curr_autharg'}'";
2315: }
2316: }
2317: }
2318: }
2319:
2320: $result.=<<"END";
2321: var current = new Object();
2322: current.radiovalue = $radioval;
2323: current.argfield = $argfield;
2324:
2325: function changed_radio(choice,currentform) {
2326: var choicearg = choice + 'arg';
2327: // If a radio button in changed, we need to change the argfield
2328: if (current.radiovalue != choice) {
2329: current.radiovalue = choice;
2330: if (current.argfield != null) {
2331: currentform.elements[current.argfield].value = '';
2332: }
2333: if (choice == 'nochange') {
2334: current.argfield = null;
2335: } else {
2336: current.argfield = choicearg;
2337: switch(choice) {
2338: case 'krb':
2339: currentform.elements[current.argfield].value =
2340: "$in{'kerb_def_dom'}";
2341: break;
2342: default:
2343: break;
2344: }
2345: }
2346: }
2347: return;
2348: }
2349:
2350: function changed_text(choice,currentform) {
2351: var choicearg = choice + 'arg';
2352: if (currentform.elements[choicearg].value !='') {
2353: $Javascript_toUpperCase
2354: // clear old field
2355: if ((current.argfield != choicearg) && (current.argfield != null)) {
2356: currentform.elements[current.argfield].value = '';
2357: }
2358: current.argfield = choicearg;
2359: }
2360: set_auth_radio_buttons(choice,currentform);
2361: return;
2362: }
2363:
2364: function set_auth_radio_buttons(newvalue,currentform) {
2365: var numauthchoices = currentform.login.length;
2366: if (typeof numauthchoices == "undefined") {
2367: return;
2368: }
2369: var i=0;
2370: while (i < numauthchoices) {
2371: if (currentform.login[i].value == newvalue) { break; }
2372: i++;
2373: }
2374: if (i == numauthchoices) {
2375: return;
2376: }
2377: current.radiovalue = newvalue;
2378: currentform.login[i].checked = true;
2379: return;
2380: }
2381: END
2382: return $result;
2383: }
2384:
2385: sub authform_authorwarning{
2386: my $result='';
2387: $result='<i>'.
2388: &mt('As a general rule, only authors or co-authors should be '.
2389: 'filesystem authenticated '.
2390: '(which allows access to the server filesystem).')."</i>\n";
2391: return $result;
2392: }
2393:
2394: sub authform_nochange{
2395: my %in = (
2396: formname => 'document.cu',
2397: kerb_def_dom => 'MSU.EDU',
2398: @_,
2399: );
2400: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2401: my $result;
2402: if (keys(%can_assign) == 0) {
2403: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2404: } else {
2405: $result = '<label>'.&mt('[_1] Do not change login data',
2406: '<input type="radio" name="login" value="nochange" '.
2407: 'checked="checked" onclick="'.
2408: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2409: '</label>';
2410: }
2411: return $result;
2412: }
2413:
2414: sub authform_kerberos {
2415: my %in = (
2416: formname => 'document.cu',
2417: kerb_def_dom => 'MSU.EDU',
2418: kerb_def_auth => 'krb4',
2419: @_,
2420: );
2421: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2422: $autharg,$jscall);
2423: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2424: if ($in{'kerb_def_auth'} eq 'krb5') {
2425: $check5 = ' checked="checked"';
2426: } else {
2427: $check4 = ' checked="checked"';
2428: }
2429: $krbarg = $in{'kerb_def_dom'};
2430: if (defined($in{'curr_authtype'})) {
2431: if ($in{'curr_authtype'} eq 'krb') {
2432: $krbcheck = ' checked="checked"';
2433: if (defined($in{'mode'})) {
2434: if ($in{'mode'} eq 'modifyuser') {
2435: $krbcheck = '';
2436: }
2437: }
2438: if (defined($in{'curr_kerb_ver'})) {
2439: if ($in{'curr_krb_ver'} eq '5') {
2440: $check5 = ' checked="checked"';
2441: $check4 = '';
2442: } else {
2443: $check4 = ' checked="checked"';
2444: $check5 = '';
2445: }
2446: }
2447: if (defined($in{'curr_autharg'})) {
2448: $krbarg = $in{'curr_autharg'};
2449: }
2450: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2451: if (defined($in{'curr_autharg'})) {
2452: $result =
2453: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2454: $in{'curr_autharg'},$krbver);
2455: } else {
2456: $result =
2457: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2458: }
2459: return $result;
2460: }
2461: }
2462: } else {
2463: if ($authnum == 1) {
2464: $authtype = '<input type="hidden" name="login" value="krb" />';
2465: }
2466: }
2467: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2468: return;
2469: } elsif ($authtype eq '') {
2470: if (defined($in{'mode'})) {
2471: if ($in{'mode'} eq 'modifycourse') {
2472: if ($authnum == 1) {
2473: $authtype = '<input type="hidden" name="login" value="krb" />';
2474: }
2475: }
2476: }
2477: }
2478: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2479: if ($authtype eq '') {
2480: $authtype = '<input type="radio" name="login" value="krb" '.
2481: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2482: $krbcheck.' />';
2483: }
2484: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2485: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2486: $in{'curr_authtype'} eq 'krb5') ||
2487: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2488: $in{'curr_authtype'} eq 'krb4')) {
2489: $result .= &mt
2490: ('[_1] Kerberos authenticated with domain [_2] '.
2491: '[_3] Version 4 [_4] Version 5 [_5]',
2492: '<label>'.$authtype,
2493: '</label><input type="text" size="10" name="krbarg" '.
2494: 'value="'.$krbarg.'" '.
2495: 'onchange="'.$jscall.'" />',
2496: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2497: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2498: '</label>');
2499: } elsif ($can_assign{'krb4'}) {
2500: $result .= &mt
2501: ('[_1] Kerberos authenticated with domain [_2] '.
2502: '[_3] Version 4 [_4]',
2503: '<label>'.$authtype,
2504: '</label><input type="text" size="10" name="krbarg" '.
2505: 'value="'.$krbarg.'" '.
2506: 'onchange="'.$jscall.'" />',
2507: '<label><input type="hidden" name="krbver" value="4" />',
2508: '</label>');
2509: } elsif ($can_assign{'krb5'}) {
2510: $result .= &mt
2511: ('[_1] Kerberos authenticated with domain [_2] '.
2512: '[_3] Version 5 [_4]',
2513: '<label>'.$authtype,
2514: '</label><input type="text" size="10" name="krbarg" '.
2515: 'value="'.$krbarg.'" '.
2516: 'onchange="'.$jscall.'" />',
2517: '<label><input type="hidden" name="krbver" value="5" />',
2518: '</label>');
2519: }
2520: return $result;
2521: }
2522:
2523: sub authform_internal{
2524: my %in = (
2525: formname => 'document.cu',
2526: kerb_def_dom => 'MSU.EDU',
2527: @_,
2528: );
2529: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2530: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2531: if (defined($in{'curr_authtype'})) {
2532: if ($in{'curr_authtype'} eq 'int') {
2533: if ($can_assign{'int'}) {
2534: $intcheck = 'checked="checked" ';
2535: if (defined($in{'mode'})) {
2536: if ($in{'mode'} eq 'modifyuser') {
2537: $intcheck = '';
2538: }
2539: }
2540: if (defined($in{'curr_autharg'})) {
2541: $intarg = $in{'curr_autharg'};
2542: }
2543: } else {
2544: $result = &mt('Currently internally authenticated.');
2545: return $result;
2546: }
2547: }
2548: } else {
2549: if ($authnum == 1) {
2550: $authtype = '<input type="hidden" name="login" value="int" />';
2551: }
2552: }
2553: if (!$can_assign{'int'}) {
2554: return;
2555: } elsif ($authtype eq '') {
2556: if (defined($in{'mode'})) {
2557: if ($in{'mode'} eq 'modifycourse') {
2558: if ($authnum == 1) {
2559: $authtype = '<input type="hidden" name="login" value="int" />';
2560: }
2561: }
2562: }
2563: }
2564: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2565: if ($authtype eq '') {
2566: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2567: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2568: }
2569: $autharg = '<input type="password" size="10" name="intarg" value="'.
2570: $intarg.'" onchange="'.$jscall.'" />';
2571: $result = &mt
2572: ('[_1] Internally authenticated (with initial password [_2])',
2573: '<label>'.$authtype,'</label>'.$autharg);
2574: $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>';
2575: return $result;
2576: }
2577:
2578: sub authform_local{
2579: my %in = (
2580: formname => 'document.cu',
2581: kerb_def_dom => 'MSU.EDU',
2582: @_,
2583: );
2584: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2585: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2586: if (defined($in{'curr_authtype'})) {
2587: if ($in{'curr_authtype'} eq 'loc') {
2588: if ($can_assign{'loc'}) {
2589: $loccheck = 'checked="checked" ';
2590: if (defined($in{'mode'})) {
2591: if ($in{'mode'} eq 'modifyuser') {
2592: $loccheck = '';
2593: }
2594: }
2595: if (defined($in{'curr_autharg'})) {
2596: $locarg = $in{'curr_autharg'};
2597: }
2598: } else {
2599: $result = &mt('Currently using local (institutional) authentication.');
2600: return $result;
2601: }
2602: }
2603: } else {
2604: if ($authnum == 1) {
2605: $authtype = '<input type="hidden" name="login" value="loc" />';
2606: }
2607: }
2608: if (!$can_assign{'loc'}) {
2609: return;
2610: } elsif ($authtype eq '') {
2611: if (defined($in{'mode'})) {
2612: if ($in{'mode'} eq 'modifycourse') {
2613: if ($authnum == 1) {
2614: $authtype = '<input type="hidden" name="login" value="loc" />';
2615: }
2616: }
2617: }
2618: }
2619: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2620: if ($authtype eq '') {
2621: $authtype = '<input type="radio" name="login" value="loc" '.
2622: $loccheck.' onchange="'.$jscall.'" onclick="'.
2623: $jscall.'" />';
2624: }
2625: $autharg = '<input type="text" size="10" name="locarg" value="'.
2626: $locarg.'" onchange="'.$jscall.'" />';
2627: $result = &mt('[_1] Local Authentication with argument [_2]',
2628: '<label>'.$authtype,'</label>'.$autharg);
2629: return $result;
2630: }
2631:
2632: sub authform_filesystem{
2633: my %in = (
2634: formname => 'document.cu',
2635: kerb_def_dom => 'MSU.EDU',
2636: @_,
2637: );
2638: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2639: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2640: if (defined($in{'curr_authtype'})) {
2641: if ($in{'curr_authtype'} eq 'fsys') {
2642: if ($can_assign{'fsys'}) {
2643: $fsyscheck = 'checked="checked" ';
2644: if (defined($in{'mode'})) {
2645: if ($in{'mode'} eq 'modifyuser') {
2646: $fsyscheck = '';
2647: }
2648: }
2649: } else {
2650: $result = &mt('Currently Filesystem Authenticated.');
2651: return $result;
2652: }
2653: }
2654: } else {
2655: if ($authnum == 1) {
2656: $authtype = '<input type="hidden" name="login" value="fsys" />';
2657: }
2658: }
2659: if (!$can_assign{'fsys'}) {
2660: return;
2661: } elsif ($authtype eq '') {
2662: if (defined($in{'mode'})) {
2663: if ($in{'mode'} eq 'modifycourse') {
2664: if ($authnum == 1) {
2665: $authtype = '<input type="hidden" name="login" value="fsys" />';
2666: }
2667: }
2668: }
2669: }
2670: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2671: if ($authtype eq '') {
2672: $authtype = '<input type="radio" name="login" value="fsys" '.
2673: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2674: $jscall.'" />';
2675: }
2676: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2677: ' onchange="'.$jscall.'" />';
2678: $result = &mt
2679: ('[_1] Filesystem Authenticated (with initial password [_2])',
2680: '<label><input type="radio" name="login" value="fsys" '.
2681: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2682: '</label><input type="password" size="10" name="fsysarg" value="" '.
2683: 'onchange="'.$jscall.'" />');
2684: return $result;
2685: }
2686:
2687: sub get_assignable_auth {
2688: my ($dom) = @_;
2689: if ($dom eq '') {
2690: $dom = $env{'request.role.domain'};
2691: }
2692: my %can_assign = (
2693: krb4 => 1,
2694: krb5 => 1,
2695: int => 1,
2696: loc => 1,
2697: );
2698: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2699: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2700: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2701: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2702: my $context;
2703: if ($env{'request.role'} =~ /^au/) {
2704: $context = 'author';
2705: } elsif ($env{'request.role'} =~ /^dc/) {
2706: $context = 'domain';
2707: } elsif ($env{'request.course.id'}) {
2708: $context = 'course';
2709: }
2710: if ($context) {
2711: if (ref($authhash->{$context}) eq 'HASH') {
2712: %can_assign = %{$authhash->{$context}};
2713: }
2714: }
2715: }
2716: }
2717: my $authnum = 0;
2718: foreach my $key (keys(%can_assign)) {
2719: if ($can_assign{$key}) {
2720: $authnum ++;
2721: }
2722: }
2723: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2724: $authnum --;
2725: }
2726: return ($authnum,%can_assign);
2727: }
2728:
2729: ###############################################################
2730: ## Get Kerberos Defaults for Domain ##
2731: ###############################################################
2732: ##
2733: ## Returns default kerberos version and an associated argument
2734: ## as listed in file domain.tab. If not listed, provides
2735: ## appropriate default domain and kerberos version.
2736: ##
2737: #-------------------------------------------
2738:
2739: =pod
2740:
2741: =item * &get_kerberos_defaults()
2742:
2743: get_kerberos_defaults($target_domain) returns the default kerberos
2744: version and domain. If not found, it defaults to version 4 and the
2745: domain of the server.
2746:
2747: =over 4
2748:
2749: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2750:
2751: =back
2752:
2753: =back
2754:
2755: =cut
2756:
2757: #-------------------------------------------
2758: sub get_kerberos_defaults {
2759: my $domain=shift;
2760: my ($krbdef,$krbdefdom);
2761: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2762: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2763: $krbdef = $domdefaults{'auth_def'};
2764: $krbdefdom = $domdefaults{'auth_arg_def'};
2765: } else {
2766: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2767: my $krbdefdom=$1;
2768: $krbdefdom=~tr/a-z/A-Z/;
2769: $krbdef = "krb4";
2770: }
2771: return ($krbdef,$krbdefdom);
2772: }
2773:
2774:
2775: ###############################################################
2776: ## Thesaurus Functions ##
2777: ###############################################################
2778:
2779: =pod
2780:
2781: =head1 Thesaurus Functions
2782:
2783: =over 4
2784:
2785: =item * &initialize_keywords()
2786:
2787: Initializes the package variable %Keywords if it is empty. Uses the
2788: package variable $thesaurus_db_file.
2789:
2790: =cut
2791:
2792: ###################################################
2793:
2794: sub initialize_keywords {
2795: return 1 if (scalar keys(%Keywords));
2796: # If we are here, %Keywords is empty, so fill it up
2797: # Make sure the file we need exists...
2798: if (! -e $thesaurus_db_file) {
2799: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2800: " failed because it does not exist");
2801: return 0;
2802: }
2803: # Set up the hash as a database
2804: my %thesaurus_db;
2805: if (! tie(%thesaurus_db,'GDBM_File',
2806: $thesaurus_db_file,&GDBM_READER(),0640)){
2807: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2808: $thesaurus_db_file);
2809: return 0;
2810: }
2811: # Get the average number of appearances of a word.
2812: my $avecount = $thesaurus_db{'average.count'};
2813: # Put keywords (those that appear > average) into %Keywords
2814: while (my ($word,$data)=each (%thesaurus_db)) {
2815: my ($count,undef) = split /:/,$data;
2816: $Keywords{$word}++ if ($count > $avecount);
2817: }
2818: untie %thesaurus_db;
2819: # Remove special values from %Keywords.
2820: foreach my $value ('total.count','average.count') {
2821: delete($Keywords{$value}) if (exists($Keywords{$value}));
2822: }
2823: return 1;
2824: }
2825:
2826: ###################################################
2827:
2828: =pod
2829:
2830: =item * &keyword($word)
2831:
2832: Returns true if $word is a keyword. A keyword is a word that appears more
2833: than the average number of times in the thesaurus database. Calls
2834: &initialize_keywords
2835:
2836: =cut
2837:
2838: ###################################################
2839:
2840: sub keyword {
2841: return if (!&initialize_keywords());
2842: my $word=lc(shift());
2843: $word=~s/\W//g;
2844: return exists($Keywords{$word});
2845: }
2846:
2847: ###############################################################
2848:
2849: =pod
2850:
2851: =item * &get_related_words()
2852:
2853: Look up a word in the thesaurus. Takes a scalar argument and returns
2854: an array of words. If the keyword is not in the thesaurus, an empty array
2855: will be returned. The order of the words returned is determined by the
2856: database which holds them.
2857:
2858: Uses global $thesaurus_db_file.
2859:
2860: =cut
2861:
2862: ###############################################################
2863: sub get_related_words {
2864: my $keyword = shift;
2865: my %thesaurus_db;
2866: if (! -e $thesaurus_db_file) {
2867: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2868: "failed because the file does not exist");
2869: return ();
2870: }
2871: if (! tie(%thesaurus_db,'GDBM_File',
2872: $thesaurus_db_file,&GDBM_READER(),0640)){
2873: return ();
2874: }
2875: my @Words=();
2876: my $count=0;
2877: if (exists($thesaurus_db{$keyword})) {
2878: # The first element is the number of times
2879: # the word appears. We do not need it now.
2880: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2881: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2882: my $threshold=$mostfrequentcount/10;
2883: foreach my $possibleword (@RelatedWords) {
2884: my ($word,$wordcount)=split(/\,/,$possibleword);
2885: if ($wordcount>$threshold) {
2886: push(@Words,$word);
2887: $count++;
2888: if ($count>10) { last; }
2889: }
2890: }
2891: }
2892: untie %thesaurus_db;
2893: return @Words;
2894: }
2895:
2896: =pod
2897:
2898: =back
2899:
2900: =cut
2901:
2902: # -------------------------------------------------------------- Plaintext name
2903: =pod
2904:
2905: =head1 User Name Functions
2906:
2907: =over 4
2908:
2909: =item * &plainname($uname,$udom,$first)
2910:
2911: Takes a users logon name and returns it as a string in
2912: "first middle last generation" form
2913: if $first is set to 'lastname' then it returns it as
2914: 'lastname generation, firstname middlename' if their is a lastname
2915:
2916: =cut
2917:
2918:
2919: ###############################################################
2920: sub plainname {
2921: my ($uname,$udom,$first)=@_;
2922: return if (!defined($uname) || !defined($udom));
2923: my %names=&getnames($uname,$udom);
2924: my $name=&Apache::lonnet::format_name($names{'firstname'},
2925: $names{'middlename'},
2926: $names{'lastname'},
2927: $names{'generation'},$first);
2928: $name=~s/^\s+//;
2929: $name=~s/\s+$//;
2930: $name=~s/\s+/ /g;
2931: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2932: return $name;
2933: }
2934:
2935: # -------------------------------------------------------------------- Nickname
2936: =pod
2937:
2938: =item * &nickname($uname,$udom)
2939:
2940: Gets a users name and returns it as a string as
2941:
2942: ""nickname""
2943:
2944: if the user has a nickname or
2945:
2946: "first middle last generation"
2947:
2948: if the user does not
2949:
2950: =cut
2951:
2952: sub nickname {
2953: my ($uname,$udom)=@_;
2954: return if (!defined($uname) || !defined($udom));
2955: my %names=&getnames($uname,$udom);
2956: my $name=$names{'nickname'};
2957: if ($name) {
2958: $name='"'.$name.'"';
2959: } else {
2960: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2961: $names{'lastname'}.' '.$names{'generation'};
2962: $name=~s/\s+$//;
2963: $name=~s/\s+/ /g;
2964: }
2965: return $name;
2966: }
2967:
2968: sub getnames {
2969: my ($uname,$udom)=@_;
2970: return if (!defined($uname) || !defined($udom));
2971: if ($udom eq 'public' && $uname eq 'public') {
2972: return ('lastname' => &mt('Public'));
2973: }
2974: my $id=$uname.':'.$udom;
2975: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2976: if ($cached) {
2977: return %{$names};
2978: } else {
2979: my %loadnames=&Apache::lonnet::get('environment',
2980: ['firstname','middlename','lastname','generation','nickname'],
2981: $udom,$uname);
2982: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2983: return %loadnames;
2984: }
2985: }
2986:
2987: # -------------------------------------------------------------------- getemails
2988:
2989: =pod
2990:
2991: =item * &getemails($uname,$udom)
2992:
2993: Gets a user's email information and returns it as a hash with keys:
2994: notification, critnotification, permanentemail
2995:
2996: For notification and critnotification, values are comma-separated lists
2997: of e-mail addresses; for permanentemail, value is a single e-mail address.
2998:
2999:
3000: =cut
3001:
3002:
3003: sub getemails {
3004: my ($uname,$udom)=@_;
3005: if ($udom eq 'public' && $uname eq 'public') {
3006: return;
3007: }
3008: if (!$udom) { $udom=$env{'user.domain'}; }
3009: if (!$uname) { $uname=$env{'user.name'}; }
3010: my $id=$uname.':'.$udom;
3011: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3012: if ($cached) {
3013: return %{$names};
3014: } else {
3015: my %loadnames=&Apache::lonnet::get('environment',
3016: ['notification','critnotification',
3017: 'permanentemail'],
3018: $udom,$uname);
3019: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3020: return %loadnames;
3021: }
3022: }
3023:
3024: sub flush_email_cache {
3025: my ($uname,$udom)=@_;
3026: if (!$udom) { $udom =$env{'user.domain'}; }
3027: if (!$uname) { $uname=$env{'user.name'}; }
3028: return if ($udom eq 'public' && $uname eq 'public');
3029: my $id=$uname.':'.$udom;
3030: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3031: }
3032:
3033: # -------------------------------------------------------------------- getlangs
3034:
3035: =pod
3036:
3037: =item * &getlangs($uname,$udom)
3038:
3039: Gets a user's language preference and returns it as a hash with key:
3040: language.
3041:
3042: =cut
3043:
3044:
3045: sub getlangs {
3046: my ($uname,$udom) = @_;
3047: if (!$udom) { $udom =$env{'user.domain'}; }
3048: if (!$uname) { $uname=$env{'user.name'}; }
3049: my $id=$uname.':'.$udom;
3050: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3051: if ($cached) {
3052: return %{$langs};
3053: } else {
3054: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3055: $udom,$uname);
3056: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3057: return %loadlangs;
3058: }
3059: }
3060:
3061: sub flush_langs_cache {
3062: my ($uname,$udom)=@_;
3063: if (!$udom) { $udom =$env{'user.domain'}; }
3064: if (!$uname) { $uname=$env{'user.name'}; }
3065: return if ($udom eq 'public' && $uname eq 'public');
3066: my $id=$uname.':'.$udom;
3067: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3068: }
3069:
3070: # ------------------------------------------------------------------ Screenname
3071:
3072: =pod
3073:
3074: =item * &screenname($uname,$udom)
3075:
3076: Gets a users screenname and returns it as a string
3077:
3078: =cut
3079:
3080: sub screenname {
3081: my ($uname,$udom)=@_;
3082: if ($uname eq $env{'user.name'} &&
3083: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3084: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3085: return $names{'screenname'};
3086: }
3087:
3088:
3089: # ------------------------------------------------------------- Confirm Wrapper
3090: =pod
3091:
3092: =item confirmwrapper
3093:
3094: Wrap messages about completion of operation in box
3095:
3096: =cut
3097:
3098: sub confirmwrapper {
3099: my ($message)=@_;
3100: if ($message) {
3101: return "\n".'<div class="LC_confirm_box">'."\n"
3102: .$message."\n"
3103: .'</div>'."\n";
3104: } else {
3105: return $message;
3106: }
3107: }
3108:
3109: # ------------------------------------------------------------- Message Wrapper
3110:
3111: sub messagewrapper {
3112: my ($link,$username,$domain,$subject,$text)=@_;
3113: return
3114: '<a href="/adm/email?compose=individual&'.
3115: 'recname='.$username.'&recdom='.$domain.
3116: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3117: 'title="'.&mt('Send message').'">'.$link.'</a>';
3118: }
3119:
3120: # --------------------------------------------------------------- Notes Wrapper
3121:
3122: sub noteswrapper {
3123: my ($link,$un,$do)=@_;
3124: return
3125: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3126: }
3127:
3128: # ------------------------------------------------------------- Aboutme Wrapper
3129:
3130: sub aboutmewrapper {
3131: my ($link,$username,$domain,$target)=@_;
3132: if (!defined($username) && !defined($domain)) {
3133: return;
3134: }
3135: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
3136: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3137: }
3138:
3139: # ------------------------------------------------------------ Syllabus Wrapper
3140:
3141: sub syllabuswrapper {
3142: my ($linktext,$coursedir,$domain)=@_;
3143: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3144: }
3145:
3146: # -----------------------------------------------------------------------------
3147:
3148: sub track_student_link {
3149: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3150: my $link ="/adm/trackstudent?";
3151: my $title = 'View recent activity';
3152: if (defined($sname) && $sname !~ /^\s*$/ &&
3153: defined($sdom) && $sdom !~ /^\s*$/) {
3154: $link .= "selected_student=$sname:$sdom";
3155: $title .= ' of this student';
3156: }
3157: if (defined($target) && $target !~ /^\s*$/) {
3158: $target = qq{target="$target"};
3159: } else {
3160: $target = '';
3161: }
3162: if ($start) { $link.='&start='.$start; }
3163: if ($only_body) { $link .= '&only_body=1'; }
3164: $title = &mt($title);
3165: $linktext = &mt($linktext);
3166: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3167: &help_open_topic('View_recent_activity');
3168: }
3169:
3170: sub slot_reservations_link {
3171: my ($linktext,$sname,$sdom,$target) = @_;
3172: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3173: my $title = 'View slot reservation history';
3174: if (defined($sname) && $sname !~ /^\s*$/ &&
3175: defined($sdom) && $sdom !~ /^\s*$/) {
3176: $link .= "&uname=$sname&udom=$sdom";
3177: $title .= ' of this student';
3178: }
3179: if (defined($target) && $target !~ /^\s*$/) {
3180: $target = qq{target="$target"};
3181: } else {
3182: $target = '';
3183: }
3184: $title = &mt($title);
3185: $linktext = &mt($linktext);
3186: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3187: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3188:
3189: }
3190:
3191: # ===================================================== Display a student photo
3192:
3193:
3194: sub student_image_tag {
3195: my ($domain,$user)=@_;
3196: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3197: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3198: return '<img src="'.$imgsrc.'" align="right" />';
3199: } else {
3200: return '';
3201: }
3202: }
3203:
3204: =pod
3205:
3206: =back
3207:
3208: =head1 Access .tab File Data
3209:
3210: =over 4
3211:
3212: =item * &languageids()
3213:
3214: returns list of all language ids
3215:
3216: =cut
3217:
3218: sub languageids {
3219: return sort(keys(%language));
3220: }
3221:
3222: =pod
3223:
3224: =item * &languagedescription()
3225:
3226: returns description of a specified language id
3227:
3228: =cut
3229:
3230: sub languagedescription {
3231: my $code=shift;
3232: return ($supported_language{$code}?'* ':'').
3233: $language{$code}.
3234: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3235: }
3236:
3237: =pod
3238:
3239: =item * &plainlanguagedescription
3240:
3241: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3242: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3243:
3244: =cut
3245:
3246: sub plainlanguagedescription {
3247: my $code=shift;
3248: return $language{$code};
3249: }
3250:
3251: =pod
3252:
3253: =item * &supportedlanguagecode
3254:
3255: Returns the supported language code (e.g. sptutf maps to pt) given a language
3256: code.
3257:
3258: =cut
3259:
3260: sub supportedlanguagecode {
3261: my $code=shift;
3262: return $supported_language{$code};
3263: }
3264:
3265: =pod
3266:
3267: =item * &latexlanguage()
3268:
3269: Given a language key code returns the correspondnig language to use
3270: to select the correct hyphenation on LaTeX printouts. This is undef if there
3271: is no supported hyphenation for the language code.
3272:
3273: =cut
3274:
3275: sub latexlanguage {
3276: my $code = shift;
3277: return $latex_language{$code};
3278: }
3279:
3280: =pod
3281:
3282: =item * ©rightids()
3283:
3284: returns list of all copyrights
3285:
3286: =cut
3287:
3288: sub copyrightids {
3289: return sort(keys(%cprtag));
3290: }
3291:
3292: =pod
3293:
3294: =item * ©rightdescription()
3295:
3296: returns description of a specified copyright id
3297:
3298: =cut
3299:
3300: sub copyrightdescription {
3301: return &mt($cprtag{shift(@_)});
3302: }
3303:
3304: =pod
3305:
3306: =item * &source_copyrightids()
3307:
3308: returns list of all source copyrights
3309:
3310: =cut
3311:
3312: sub source_copyrightids {
3313: return sort(keys(%scprtag));
3314: }
3315:
3316: =pod
3317:
3318: =item * &source_copyrightdescription()
3319:
3320: returns description of a specified source copyright id
3321:
3322: =cut
3323:
3324: sub source_copyrightdescription {
3325: return &mt($scprtag{shift(@_)});
3326: }
3327:
3328: =pod
3329:
3330: =item * &filecategories()
3331:
3332: returns list of all file categories
3333:
3334: =cut
3335:
3336: sub filecategories {
3337: return sort(keys(%category_extensions));
3338: }
3339:
3340: =pod
3341:
3342: =item * &filecategorytypes()
3343:
3344: returns list of file types belonging to a given file
3345: category
3346:
3347: =cut
3348:
3349: sub filecategorytypes {
3350: my ($cat) = @_;
3351: return @{$category_extensions{lc($cat)}};
3352: }
3353:
3354: =pod
3355:
3356: =item * &fileembstyle()
3357:
3358: returns embedding style for a specified file type
3359:
3360: =cut
3361:
3362: sub fileembstyle {
3363: return $fe{lc(shift(@_))};
3364: }
3365:
3366: sub filemimetype {
3367: return $fm{lc(shift(@_))};
3368: }
3369:
3370:
3371: sub filecategoryselect {
3372: my ($name,$value)=@_;
3373: return &select_form($value,$name,
3374: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3375: }
3376:
3377: =pod
3378:
3379: =item * &filedescription()
3380:
3381: returns description for a specified file type
3382:
3383: =cut
3384:
3385: sub filedescription {
3386: my $file_description = $fd{lc(shift())};
3387: $file_description =~ s:([\[\]]):~$1:g;
3388: return &mt($file_description);
3389: }
3390:
3391: =pod
3392:
3393: =item * &filedescriptionex()
3394:
3395: returns description for a specified file type with
3396: extra formatting
3397:
3398: =cut
3399:
3400: sub filedescriptionex {
3401: my $ex=shift;
3402: my $file_description = $fd{lc($ex)};
3403: $file_description =~ s:([\[\]]):~$1:g;
3404: return '.'.$ex.' '.&mt($file_description);
3405: }
3406:
3407: # End of .tab access
3408: =pod
3409:
3410: =back
3411:
3412: =cut
3413:
3414: # ------------------------------------------------------------------ File Types
3415: sub fileextensions {
3416: return sort(keys(%fe));
3417: }
3418:
3419: # ----------------------------------------------------------- Display Languages
3420: # returns a hash with all desired display languages
3421: #
3422:
3423: sub display_languages {
3424: my %languages=();
3425: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3426: $languages{$lang}=1;
3427: }
3428: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3429: if ($env{'form.displaylanguage'}) {
3430: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3431: $languages{$lang}=1;
3432: }
3433: }
3434: return %languages;
3435: }
3436:
3437: sub languages {
3438: my ($possible_langs) = @_;
3439: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3440: if (!ref($possible_langs)) {
3441: if( wantarray ) {
3442: return @preferred_langs;
3443: } else {
3444: return $preferred_langs[0];
3445: }
3446: }
3447: my %possibilities = map { $_ => 1 } (@$possible_langs);
3448: my @preferred_possibilities;
3449: foreach my $preferred_lang (@preferred_langs) {
3450: if (exists($possibilities{$preferred_lang})) {
3451: push(@preferred_possibilities, $preferred_lang);
3452: }
3453: }
3454: if( wantarray ) {
3455: return @preferred_possibilities;
3456: }
3457: return $preferred_possibilities[0];
3458: }
3459:
3460: sub user_lang {
3461: my ($touname,$toudom,$fromcid) = @_;
3462: my @userlangs;
3463: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3464: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3465: $env{'course.'.$fromcid.'.languages'}));
3466: } else {
3467: my %langhash = &getlangs($touname,$toudom);
3468: if ($langhash{'languages'} ne '') {
3469: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3470: } else {
3471: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3472: if ($domdefs{'lang_def'} ne '') {
3473: @userlangs = ($domdefs{'lang_def'});
3474: }
3475: }
3476: }
3477: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3478: my $user_lh = Apache::localize->get_handle(@languages);
3479: return $user_lh;
3480: }
3481:
3482:
3483: ###############################################################
3484: ## Student Answer Attempts ##
3485: ###############################################################
3486:
3487: =pod
3488:
3489: =head1 Alternate Problem Views
3490:
3491: =over 4
3492:
3493: =item * &get_previous_attempt($symb, $username, $domain, $course,
3494: $getattempt, $regexp, $gradesub)
3495:
3496: Return string with previous attempt on problem. Arguments:
3497:
3498: =over 4
3499:
3500: =item * $symb: Problem, including path
3501:
3502: =item * $username: username of the desired student
3503:
3504: =item * $domain: domain of the desired student
3505:
3506: =item * $course: Course ID
3507:
3508: =item * $getattempt: Leave blank for all attempts, otherwise put
3509: something
3510:
3511: =item * $regexp: if string matches this regexp, the string will be
3512: sent to $gradesub
3513:
3514: =item * $gradesub: routine that processes the string if it matches $regexp
3515:
3516: =back
3517:
3518: The output string is a table containing all desired attempts, if any.
3519:
3520: =cut
3521:
3522: sub get_previous_attempt {
3523: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3524: my $prevattempts='';
3525: no strict 'refs';
3526: if ($symb) {
3527: my (%returnhash)=
3528: &Apache::lonnet::restore($symb,$course,$domain,$username);
3529: if ($returnhash{'version'}) {
3530: my %lasthash=();
3531: my $version;
3532: for ($version=1;$version<=$returnhash{'version'};$version++) {
3533: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3534: $lasthash{$key}=$returnhash{$version.':'.$key};
3535: }
3536: }
3537: $prevattempts=&start_data_table().&start_data_table_header_row();
3538: $prevattempts.='<th>'.&mt('History').'</th>';
3539: my (%typeparts,%lasthidden);
3540: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3541: foreach my $key (sort(keys(%lasthash))) {
3542: my ($ign,@parts) = split(/\./,$key);
3543: if ($#parts > 0) {
3544: my $data=$parts[-1];
3545: next if ($data eq 'foilorder');
3546: pop(@parts);
3547: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3548: if ($data eq 'type') {
3549: unless ($showsurv) {
3550: my $id = join(',',@parts);
3551: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3552: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3553: $lasthidden{$ign.'.'.$id} = 1;
3554: }
3555: }
3556: }
3557: } else {
3558: if ($#parts == 0) {
3559: $prevattempts.='<th>'.$parts[0].'</th>';
3560: } else {
3561: $prevattempts.='<th>'.$ign.'</th>';
3562: }
3563: }
3564: }
3565: $prevattempts.=&end_data_table_header_row();
3566: if ($getattempt eq '') {
3567: for ($version=1;$version<=$returnhash{'version'};$version++) {
3568: my @hidden;
3569: if (%typeparts) {
3570: foreach my $id (keys(%typeparts)) {
3571: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3572: push(@hidden,$id);
3573: }
3574: }
3575: }
3576: $prevattempts.=&start_data_table_row().
3577: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3578: if (@hidden) {
3579: foreach my $key (sort(keys(%lasthash))) {
3580: next if ($key =~ /\.foilorder$/);
3581: my $hide;
3582: foreach my $id (@hidden) {
3583: if ($key =~ /^\Q$id\E/) {
3584: $hide = 1;
3585: last;
3586: }
3587: }
3588: if ($hide) {
3589: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3590: if (($data eq 'award') || ($data eq 'awarddetail')) {
3591: my $value = &format_previous_attempt_value($key,
3592: $returnhash{$version.':'.$key});
3593: $prevattempts.='<td>'.$value.' </td>';
3594: } else {
3595: $prevattempts.='<td> </td>';
3596: }
3597: } else {
3598: if ($key =~ /\./) {
3599: my $value = &format_previous_attempt_value($key,
3600: $returnhash{$version.':'.$key});
3601: $prevattempts.='<td>'.$value.' </td>';
3602: } else {
3603: $prevattempts.='<td> </td>';
3604: }
3605: }
3606: }
3607: } else {
3608: foreach my $key (sort(keys(%lasthash))) {
3609: next if ($key =~ /\.foilorder$/);
3610: my $value = &format_previous_attempt_value($key,
3611: $returnhash{$version.':'.$key});
3612: $prevattempts.='<td>'.$value.' </td>';
3613: }
3614: }
3615: $prevattempts.=&end_data_table_row();
3616: }
3617: }
3618: my @currhidden = keys(%lasthidden);
3619: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3620: foreach my $key (sort(keys(%lasthash))) {
3621: next if ($key =~ /\.foilorder$/);
3622: if (%typeparts) {
3623: my $hidden;
3624: foreach my $id (@currhidden) {
3625: if ($key =~ /^\Q$id\E/) {
3626: $hidden = 1;
3627: last;
3628: }
3629: }
3630: if ($hidden) {
3631: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3632: if (($data eq 'award') || ($data eq 'awarddetail')) {
3633: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3634: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3635: $value = &$gradesub($value);
3636: }
3637: $prevattempts.='<td>'.$value.' </td>';
3638: } else {
3639: $prevattempts.='<td> </td>';
3640: }
3641: } else {
3642: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3643: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3644: $value = &$gradesub($value);
3645: }
3646: $prevattempts.='<td>'.$value.' </td>';
3647: }
3648: } else {
3649: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3650: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3651: $value = &$gradesub($value);
3652: }
3653: $prevattempts.='<td>'.$value.' </td>';
3654: }
3655: }
3656: $prevattempts.= &end_data_table_row().&end_data_table();
3657: } else {
3658: $prevattempts=
3659: &start_data_table().&start_data_table_row().
3660: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3661: &end_data_table_row().&end_data_table();
3662: }
3663: } else {
3664: $prevattempts=
3665: &start_data_table().&start_data_table_row().
3666: '<td>'.&mt('No data.').'</td>'.
3667: &end_data_table_row().&end_data_table();
3668: }
3669: }
3670:
3671: sub format_previous_attempt_value {
3672: my ($key,$value) = @_;
3673: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3674: $value = &Apache::lonlocal::locallocaltime($value);
3675: } elsif (ref($value) eq 'ARRAY') {
3676: $value = '('.join(', ', @{ $value }).')';
3677: } elsif ($key =~ /answerstring$/) {
3678: my %answers = &Apache::lonnet::str2hash($value);
3679: my @anskeys = sort(keys(%answers));
3680: if (@anskeys == 1) {
3681: my $answer = $answers{$anskeys[0]};
3682: if ($answer =~ m{\0}) {
3683: $answer =~ s{\0}{,}g;
3684: }
3685: my $tag_internal_answer_name = 'INTERNAL';
3686: if ($anskeys[0] eq $tag_internal_answer_name) {
3687: $value = $answer;
3688: } else {
3689: $value = $anskeys[0].'='.$answer;
3690: }
3691: } else {
3692: foreach my $ans (@anskeys) {
3693: my $answer = $answers{$ans};
3694: if ($answer =~ m{\0}) {
3695: $answer =~ s{\0}{,}g;
3696: }
3697: $value .= $ans.'='.$answer.'<br />';;
3698: }
3699: }
3700: } else {
3701: $value = &unescape($value);
3702: }
3703: return $value;
3704: }
3705:
3706:
3707: sub relative_to_absolute {
3708: my ($url,$output)=@_;
3709: my $parser=HTML::TokeParser->new(\$output);
3710: my $token;
3711: my $thisdir=$url;
3712: my @rlinks=();
3713: while ($token=$parser->get_token) {
3714: if ($token->[0] eq 'S') {
3715: if ($token->[1] eq 'a') {
3716: if ($token->[2]->{'href'}) {
3717: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3718: }
3719: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3720: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3721: } elsif ($token->[1] eq 'base') {
3722: $thisdir=$token->[2]->{'href'};
3723: }
3724: }
3725: }
3726: $thisdir=~s-/[^/]*$--;
3727: foreach my $link (@rlinks) {
3728: unless (($link=~/^https?\:\/\//i) ||
3729: ($link=~/^\//) ||
3730: ($link=~/^javascript:/i) ||
3731: ($link=~/^mailto:/i) ||
3732: ($link=~/^\#/)) {
3733: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3734: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3735: }
3736: }
3737: # -------------------------------------------------- Deal with Applet codebases
3738: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3739: return $output;
3740: }
3741:
3742: =pod
3743:
3744: =item * &get_student_view()
3745:
3746: show a snapshot of what student was looking at
3747:
3748: =cut
3749:
3750: sub get_student_view {
3751: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3752: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3753: my (%form);
3754: my @elements=('symb','courseid','domain','username');
3755: foreach my $element (@elements) {
3756: $form{'grade_'.$element}=eval '$'.$element #'
3757: }
3758: if (defined($moreenv)) {
3759: %form=(%form,%{$moreenv});
3760: }
3761: if (defined($target)) { $form{'grade_target'} = $target; }
3762: $feedurl=&Apache::lonnet::clutter($feedurl);
3763: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3764: $userview=~s/\<body[^\>]*\>//gi;
3765: $userview=~s/\<\/body\>//gi;
3766: $userview=~s/\<html\>//gi;
3767: $userview=~s/\<\/html\>//gi;
3768: $userview=~s/\<head\>//gi;
3769: $userview=~s/\<\/head\>//gi;
3770: $userview=~s/action\s*\=/would_be_action\=/gi;
3771: $userview=&relative_to_absolute($feedurl,$userview);
3772: if (wantarray) {
3773: return ($userview,$response);
3774: } else {
3775: return $userview;
3776: }
3777: }
3778:
3779: sub get_student_view_with_retries {
3780: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3781:
3782: my $ok = 0; # True if we got a good response.
3783: my $content;
3784: my $response;
3785:
3786: # Try to get the student_view done. within the retries count:
3787:
3788: do {
3789: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3790: $ok = $response->is_success;
3791: if (!$ok) {
3792: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3793: }
3794: $retries--;
3795: } while (!$ok && ($retries > 0));
3796:
3797: if (!$ok) {
3798: $content = ''; # On error return an empty content.
3799: }
3800: if (wantarray) {
3801: return ($content, $response);
3802: } else {
3803: return $content;
3804: }
3805: }
3806:
3807: =pod
3808:
3809: =item * &get_student_answers()
3810:
3811: show a snapshot of how student was answering problem
3812:
3813: =cut
3814:
3815: sub get_student_answers {
3816: my ($symb,$username,$domain,$courseid,%form) = @_;
3817: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3818: my (%moreenv);
3819: my @elements=('symb','courseid','domain','username');
3820: foreach my $element (@elements) {
3821: $moreenv{'grade_'.$element}=eval '$'.$element #'
3822: }
3823: $moreenv{'grade_target'}='answer';
3824: %moreenv=(%form,%moreenv);
3825: $feedurl = &Apache::lonnet::clutter($feedurl);
3826: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3827: return $userview;
3828: }
3829:
3830: =pod
3831:
3832: =item * &submlink()
3833:
3834: Inputs: $text $uname $udom $symb $target
3835:
3836: Returns: A link to grades.pm such as to see the SUBM view of a student
3837:
3838: =cut
3839:
3840: ###############################################
3841: sub submlink {
3842: my ($text,$uname,$udom,$symb,$target)=@_;
3843: if (!($uname && $udom)) {
3844: (my $cursymb, my $courseid,$udom,$uname)=
3845: &Apache::lonnet::whichuser($symb);
3846: if (!$symb) { $symb=$cursymb; }
3847: }
3848: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3849: $symb=&escape($symb);
3850: if ($target) { $target=" target=\"$target\""; }
3851: return
3852: '<a href="/adm/grades?command=submission'.
3853: '&symb='.$symb.
3854: '&student='.$uname.
3855: '&userdom='.$udom.'"'.
3856: $target.'>'.$text.'</a>';
3857: }
3858: ##############################################
3859:
3860: =pod
3861:
3862: =item * &pgrdlink()
3863:
3864: Inputs: $text $uname $udom $symb $target
3865:
3866: Returns: A link to grades.pm such as to see the PGRD view of a student
3867:
3868: =cut
3869:
3870: ###############################################
3871: sub pgrdlink {
3872: my $link=&submlink(@_);
3873: $link=~s/(&command=submission)/$1&showgrading=yes/;
3874: return $link;
3875: }
3876: ##############################################
3877:
3878: =pod
3879:
3880: =item * &pprmlink()
3881:
3882: Inputs: $text $uname $udom $symb $target
3883:
3884: Returns: A link to parmset.pm such as to see the PPRM view of a
3885: student and a specific resource
3886:
3887: =cut
3888:
3889: ###############################################
3890: sub pprmlink {
3891: my ($text,$uname,$udom,$symb,$target)=@_;
3892: if (!($uname && $udom)) {
3893: (my $cursymb, my $courseid,$udom,$uname)=
3894: &Apache::lonnet::whichuser($symb);
3895: if (!$symb) { $symb=$cursymb; }
3896: }
3897: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3898: $symb=&escape($symb);
3899: if ($target) { $target="target=\"$target\""; }
3900: return '<a href="/adm/parmset?command=set&'.
3901: 'symb='.$symb.'&uname='.$uname.
3902: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3903: }
3904: ##############################################
3905:
3906: =pod
3907:
3908: =back
3909:
3910: =cut
3911:
3912: ###############################################
3913:
3914:
3915: sub timehash {
3916: my ($thistime) = @_;
3917: my $timezone = &Apache::lonlocal::gettimezone();
3918: my $dt = DateTime->from_epoch(epoch => $thistime)
3919: ->set_time_zone($timezone);
3920: my $wday = $dt->day_of_week();
3921: if ($wday == 7) { $wday = 0; }
3922: return ( 'second' => $dt->second(),
3923: 'minute' => $dt->minute(),
3924: 'hour' => $dt->hour(),
3925: 'day' => $dt->day_of_month(),
3926: 'month' => $dt->month(),
3927: 'year' => $dt->year(),
3928: 'weekday' => $wday,
3929: 'dayyear' => $dt->day_of_year(),
3930: 'dlsav' => $dt->is_dst() );
3931: }
3932:
3933: sub utc_string {
3934: my ($date)=@_;
3935: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3936: }
3937:
3938: sub maketime {
3939: my %th=@_;
3940: my ($epoch_time,$timezone,$dt);
3941: $timezone = &Apache::lonlocal::gettimezone();
3942: eval {
3943: $dt = DateTime->new( year => $th{'year'},
3944: month => $th{'month'},
3945: day => $th{'day'},
3946: hour => $th{'hour'},
3947: minute => $th{'minute'},
3948: second => $th{'second'},
3949: time_zone => $timezone,
3950: );
3951: };
3952: if (!$@) {
3953: $epoch_time = $dt->epoch;
3954: if ($epoch_time) {
3955: return $epoch_time;
3956: }
3957: }
3958: return POSIX::mktime(
3959: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3960: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3961: }
3962:
3963: #########################################
3964:
3965: sub findallcourses {
3966: my ($roles,$uname,$udom) = @_;
3967: my %roles;
3968: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3969: my %courses;
3970: my $now=time;
3971: if (!defined($uname)) {
3972: $uname = $env{'user.name'};
3973: }
3974: if (!defined($udom)) {
3975: $udom = $env{'user.domain'};
3976: }
3977: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3978: my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
3979: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
3980: $extra);
3981: if (!%roles) {
3982: %roles = (
3983: cc => 1,
3984: co => 1,
3985: in => 1,
3986: ep => 1,
3987: ta => 1,
3988: cr => 1,
3989: st => 1,
3990: );
3991: }
3992: foreach my $entry (keys(%roleshash)) {
3993: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3994: if ($trole =~ /^cr/) {
3995: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3996: } else {
3997: next if (!exists($roles{$trole}));
3998: }
3999: if ($tend) {
4000: next if ($tend < $now);
4001: }
4002: if ($tstart) {
4003: next if ($tstart > $now);
4004: }
4005: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
4006: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4007: if ($secpart eq '') {
4008: ($cnum,$role) = split(/_/,$cnumpart);
4009: $sec = 'none';
4010: $realsec = '';
4011: } else {
4012: $cnum = $cnumpart;
4013: ($sec,$role) = split(/_/,$secpart);
4014: $realsec = $sec;
4015: }
4016: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
4017: }
4018: } else {
4019: foreach my $key (keys(%env)) {
4020: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4021: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4022: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4023: next if ($role eq 'ca' || $role eq 'aa');
4024: next if (%roles && !exists($roles{$role}));
4025: my ($starttime,$endtime)=split(/\./,$env{$key});
4026: my $active=1;
4027: if ($starttime) {
4028: if ($now<$starttime) { $active=0; }
4029: }
4030: if ($endtime) {
4031: if ($now>$endtime) { $active=0; }
4032: }
4033: if ($active) {
4034: if ($sec eq '') {
4035: $sec = 'none';
4036: }
4037: $courses{$cdom.'_'.$cnum}{$sec} =
4038: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
4039: }
4040: }
4041: }
4042: }
4043: return %courses;
4044: }
4045:
4046: ###############################################
4047:
4048: sub blockcheck {
4049: my ($setters,$activity,$uname,$udom) = @_;
4050:
4051: if (!defined($udom)) {
4052: $udom = $env{'user.domain'};
4053: }
4054: if (!defined($uname)) {
4055: $uname = $env{'user.name'};
4056: }
4057:
4058: # If uname and udom are for a course, check for blocks in the course.
4059:
4060: if (&Apache::lonnet::is_course($udom,$uname)) {
4061: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
4062: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
4063: return ($startblock,$endblock);
4064: }
4065:
4066: my $startblock = 0;
4067: my $endblock = 0;
4068: my %live_courses = &findallcourses(undef,$uname,$udom);
4069:
4070: # If uname is for a user, and activity is course-specific, i.e.,
4071: # boards, chat or groups, check for blocking in current course only.
4072:
4073: if (($activity eq 'boards' || $activity eq 'chat' ||
4074: $activity eq 'groups') && ($env{'request.course.id'})) {
4075: foreach my $key (keys(%live_courses)) {
4076: if ($key ne $env{'request.course.id'}) {
4077: delete($live_courses{$key});
4078: }
4079: }
4080: }
4081:
4082: my $otheruser = 0;
4083: my %own_courses;
4084: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4085: # Resource belongs to user other than current user.
4086: $otheruser = 1;
4087: # Gather courses for current user
4088: %own_courses =
4089: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4090: }
4091:
4092: # Gather active course roles - course coordinator, instructor,
4093: # exam proctor, ta, student, or custom role.
4094:
4095: foreach my $course (keys(%live_courses)) {
4096: my ($cdom,$cnum);
4097: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4098: $cdom = $env{'course.'.$course.'.domain'};
4099: $cnum = $env{'course.'.$course.'.num'};
4100: } else {
4101: ($cdom,$cnum) = split(/_/,$course);
4102: }
4103: my $no_ownblock = 0;
4104: my $no_userblock = 0;
4105: if ($otheruser && $activity ne 'com') {
4106: # Check if current user has 'evb' priv for this
4107: if (defined($own_courses{$course})) {
4108: foreach my $sec (keys(%{$own_courses{$course}})) {
4109: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4110: if ($sec ne 'none') {
4111: $checkrole .= '/'.$sec;
4112: }
4113: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4114: $no_ownblock = 1;
4115: last;
4116: }
4117: }
4118: }
4119: # if they have 'evb' priv and are currently not playing student
4120: next if (($no_ownblock) &&
4121: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4122: }
4123: foreach my $sec (keys(%{$live_courses{$course}})) {
4124: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4125: if ($sec ne 'none') {
4126: $checkrole .= '/'.$sec;
4127: }
4128: if ($otheruser) {
4129: # Resource belongs to user other than current user.
4130: # Assemble privs for that user, and check for 'evb' priv.
4131: my ($trole,$tdom,$tnum,$tsec);
4132: my $entry = $live_courses{$course}{$sec};
4133: if ($entry =~ /^cr/) {
4134: ($trole,$tdom,$tnum,$tsec) =
4135: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4136: } else {
4137: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4138: }
4139: my ($spec,$area,$trest,%allroles,%userroles);
4140: $area = '/'.$tdom.'/'.$tnum;
4141: $trest = $tnum;
4142: if ($tsec ne '') {
4143: $area .= '/'.$tsec;
4144: $trest .= '/'.$tsec;
4145: }
4146: $spec = $trole.'.'.$area;
4147: if ($trole =~ /^cr/) {
4148: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4149: $tdom,$spec,$trest,$area);
4150: } else {
4151: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4152: $tdom,$spec,$trest,$area);
4153: }
4154: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4155: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4156: if ($1) {
4157: $no_userblock = 1;
4158: last;
4159: }
4160: }
4161: } else {
4162: # Resource belongs to current user
4163: # Check for 'evb' priv via lonnet::allowed().
4164: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4165: $no_ownblock = 1;
4166: last;
4167: }
4168: }
4169: }
4170: # if they have the evb priv and are currently not playing student
4171: next if (($no_ownblock) &&
4172: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4173: next if ($no_userblock);
4174:
4175: # Retrieve blocking times and identity of locker for course
4176: # of specified user, unless user has 'evb' privilege.
4177:
4178: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
4179: if (($start != 0) &&
4180: (($startblock == 0) || ($startblock > $start))) {
4181: $startblock = $start;
4182: }
4183: if (($end != 0) &&
4184: (($endblock == 0) || ($endblock < $end))) {
4185: $endblock = $end;
4186: }
4187: }
4188: return ($startblock,$endblock);
4189: }
4190:
4191: sub get_blocks {
4192: my ($setters,$activity,$cdom,$cnum) = @_;
4193: my $startblock = 0;
4194: my $endblock = 0;
4195: my $course = $cdom.'_'.$cnum;
4196: $setters->{$course} = {};
4197: $setters->{$course}{'staff'} = [];
4198: $setters->{$course}{'times'} = [];
4199: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
4200: foreach my $record (keys(%records)) {
4201: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
4202: if ($start <= time && $end >= time) {
4203: my ($staff_name,$staff_dom,$title,$blocks) =
4204: &parse_block_record($records{$record});
4205: if ($blocks->{$activity} eq 'on') {
4206: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4207: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4208: if ( ($startblock == 0) || ($startblock > $start) ) {
4209: $startblock = $start;
4210: }
4211: if ( ($endblock == 0) || ($endblock < $end) ) {
4212: $endblock = $end;
4213: }
4214: }
4215: }
4216: }
4217: return ($startblock,$endblock);
4218: }
4219:
4220: sub parse_block_record {
4221: my ($record) = @_;
4222: my ($setuname,$setudom,$title,$blocks);
4223: if (ref($record) eq 'HASH') {
4224: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4225: $title = &unescape($record->{'event'});
4226: $blocks = $record->{'blocks'};
4227: } else {
4228: my @data = split(/:/,$record,3);
4229: if (scalar(@data) eq 2) {
4230: $title = $data[1];
4231: ($setuname,$setudom) = split(/@/,$data[0]);
4232: } else {
4233: ($setuname,$setudom,$title) = @data;
4234: }
4235: $blocks = { 'com' => 'on' };
4236: }
4237: return ($setuname,$setudom,$title,$blocks);
4238: }
4239:
4240: sub blocking_status {
4241: my ($activity,$uname,$udom) = @_;
4242: my %setters;
4243:
4244: # check for active blocking
4245: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
4246:
4247: my $blocked = $startblock && $endblock ? 1 : 0;
4248:
4249: # caller just wants to know whether a block is active
4250: if (!wantarray) { return $blocked; }
4251:
4252: # build a link to a popup window containing the details
4253: my $querystring = "?activity=$activity";
4254: # $uname and $udom decide whose portfolio the user is trying to look at
4255: $querystring .= "&udom=$udom" if $udom;
4256: $querystring .= "&uname=$uname" if $uname;
4257:
4258: my $output .= <<'END_MYBLOCK';
4259: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4260: var options = "width=" + w + ",height=" + h + ",";
4261: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4262: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4263: var newWin = window.open(url, wdwName, options);
4264: newWin.focus();
4265: }
4266: END_MYBLOCK
4267:
4268: $output = Apache::lonhtmlcommon::scripttag($output);
4269:
4270: my $popupUrl = "/adm/blockingstatus/$querystring";
4271: my $text = mt('Communication Blocked');
4272:
4273: $output .= <<"END_BLOCK";
4274: <div class='LC_comblock'>
4275: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4276: title='$text'>
4277: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4278: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4279: title='$text'>$text</a>
4280: </div>
4281:
4282: END_BLOCK
4283:
4284: return ($blocked, $output);
4285: }
4286:
4287: ###############################################
4288:
4289: sub check_ip_acc {
4290: my ($acc)=@_;
4291: &Apache::lonxml::debug("acc is $acc");
4292: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4293: return 1;
4294: }
4295: my $allowed=0;
4296: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4297:
4298: my $name;
4299: foreach my $pattern (split(',',$acc)) {
4300: $pattern =~ s/^\s*//;
4301: $pattern =~ s/\s*$//;
4302: if ($pattern =~ /\*$/) {
4303: #35.8.*
4304: $pattern=~s/\*//;
4305: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4306: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4307: #35.8.3.[34-56]
4308: my $low=$2;
4309: my $high=$3;
4310: $pattern=$1;
4311: if ($ip =~ /^\Q$pattern\E/) {
4312: my $last=(split(/\./,$ip))[3];
4313: if ($last <=$high && $last >=$low) { $allowed=1; }
4314: }
4315: } elsif ($pattern =~ /^\*/) {
4316: #*.msu.edu
4317: $pattern=~s/\*//;
4318: if (!defined($name)) {
4319: use Socket;
4320: my $netaddr=inet_aton($ip);
4321: ($name)=gethostbyaddr($netaddr,AF_INET);
4322: }
4323: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4324: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4325: #127.0.0.1
4326: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4327: } else {
4328: #some.name.com
4329: if (!defined($name)) {
4330: use Socket;
4331: my $netaddr=inet_aton($ip);
4332: ($name)=gethostbyaddr($netaddr,AF_INET);
4333: }
4334: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4335: }
4336: if ($allowed) { last; }
4337: }
4338: return $allowed;
4339: }
4340:
4341: ###############################################
4342:
4343: =pod
4344:
4345: =head1 Domain Template Functions
4346:
4347: =over 4
4348:
4349: =item * &determinedomain()
4350:
4351: Inputs: $domain (usually will be undef)
4352:
4353: Returns: Determines which domain should be used for designs
4354:
4355: =cut
4356:
4357: ###############################################
4358: sub determinedomain {
4359: my $domain=shift;
4360: if (! $domain) {
4361: # Determine domain if we have not been given one
4362: $domain = &Apache::lonnet::default_login_domain();
4363: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4364: if ($env{'request.role.domain'}) {
4365: $domain=$env{'request.role.domain'};
4366: }
4367: }
4368: return $domain;
4369: }
4370: ###############################################
4371:
4372: sub devalidate_domconfig_cache {
4373: my ($udom)=@_;
4374: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4375: }
4376:
4377: # ---------------------- Get domain configuration for a domain
4378: sub get_domainconf {
4379: my ($udom) = @_;
4380: my $cachetime=1800;
4381: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4382: if (defined($cached)) { return %{$result}; }
4383:
4384: my %domconfig = &Apache::lonnet::get_dom('configuration',
4385: ['login','rolecolors','autoenroll'],$udom);
4386: my (%designhash,%legacy);
4387: if (keys(%domconfig) > 0) {
4388: if (ref($domconfig{'login'}) eq 'HASH') {
4389: if (keys(%{$domconfig{'login'}})) {
4390: foreach my $key (keys(%{$domconfig{'login'}})) {
4391: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4392: if ($key eq 'loginvia') {
4393: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4394: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4395: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4396: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4397: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4398: $designhash{$udom.'.login.loginvia'} = $server;
4399: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4400:
4401: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4402: } else {
4403: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4404: }
4405: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4406: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4407: }
4408: }
4409: }
4410: }
4411: }
4412: } else {
4413: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4414: $designhash{$udom.'.login.'.$key.'_'.$img} =
4415: $domconfig{'login'}{$key}{$img};
4416: }
4417: }
4418: } else {
4419: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4420: }
4421: }
4422: } else {
4423: $legacy{'login'} = 1;
4424: }
4425: } else {
4426: $legacy{'login'} = 1;
4427: }
4428: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4429: if (keys(%{$domconfig{'rolecolors'}})) {
4430: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4431: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4432: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4433: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4434: }
4435: }
4436: }
4437: } else {
4438: $legacy{'rolecolors'} = 1;
4439: }
4440: } else {
4441: $legacy{'rolecolors'} = 1;
4442: }
4443: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4444: if ($domconfig{'autoenroll'}{'co-owners'}) {
4445: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4446: }
4447: }
4448: if (keys(%legacy) > 0) {
4449: my %legacyhash = &get_legacy_domconf($udom);
4450: foreach my $item (keys(%legacyhash)) {
4451: if ($item =~ /^\Q$udom\E\.login/) {
4452: if ($legacy{'login'}) {
4453: $designhash{$item} = $legacyhash{$item};
4454: }
4455: } else {
4456: if ($legacy{'rolecolors'}) {
4457: $designhash{$item} = $legacyhash{$item};
4458: }
4459: }
4460: }
4461: }
4462: } else {
4463: %designhash = &get_legacy_domconf($udom);
4464: }
4465: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4466: $cachetime);
4467: return %designhash;
4468: }
4469:
4470: sub get_legacy_domconf {
4471: my ($udom) = @_;
4472: my %legacyhash;
4473: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4474: my $designfile = $designdir.'/'.$udom.'.tab';
4475: if (-e $designfile) {
4476: if ( open (my $fh,"<$designfile") ) {
4477: while (my $line = <$fh>) {
4478: next if ($line =~ /^\#/);
4479: chomp($line);
4480: my ($key,$val)=(split(/\=/,$line));
4481: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4482: }
4483: close($fh);
4484: }
4485: }
4486: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4487: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4488: }
4489: return %legacyhash;
4490: }
4491:
4492: =pod
4493:
4494: =item * &domainlogo()
4495:
4496: Inputs: $domain (usually will be undef)
4497:
4498: Returns: A link to a domain logo, if the domain logo exists.
4499: If the domain logo does not exist, a description of the domain.
4500:
4501: =cut
4502:
4503: ###############################################
4504: sub domainlogo {
4505: my $domain = &determinedomain(shift);
4506: my %designhash = &get_domainconf($domain);
4507: # See if there is a logo
4508: if ($designhash{$domain.'.login.domlogo'} ne '') {
4509: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4510: if ($imgsrc =~ m{^/(adm|res)/}) {
4511: if ($imgsrc =~ m{^/res/}) {
4512: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4513: &Apache::lonnet::repcopy($local_name);
4514: }
4515: $imgsrc = &lonhttpdurl($imgsrc);
4516: }
4517: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4518: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4519: return &Apache::lonnet::domain($domain,'description');
4520: } else {
4521: return '';
4522: }
4523: }
4524: ##############################################
4525:
4526: =pod
4527:
4528: =item * &designparm()
4529:
4530: Inputs: $which parameter; $domain (usually will be undef)
4531:
4532: Returns: value of designparamter $which
4533:
4534: =cut
4535:
4536:
4537: ##############################################
4538: sub designparm {
4539: my ($which,$domain)=@_;
4540: if (exists($env{'environment.color.'.$which})) {
4541: return $env{'environment.color.'.$which};
4542: }
4543: $domain=&determinedomain($domain);
4544: my %domdesign;
4545: unless ($domain eq 'public') {
4546: %domdesign = &get_domainconf($domain);
4547: }
4548: my $output;
4549: if ($domdesign{$domain.'.'.$which} ne '') {
4550: $output = $domdesign{$domain.'.'.$which};
4551: } else {
4552: $output = $defaultdesign{$which};
4553: }
4554: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4555: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4556: if ($output =~ m{^/(adm|res)/}) {
4557: if ($output =~ m{^/res/}) {
4558: my $local_name = &Apache::lonnet::filelocation('',$output);
4559: &Apache::lonnet::repcopy($local_name);
4560: }
4561: $output = &lonhttpdurl($output);
4562: }
4563: }
4564: return $output;
4565: }
4566:
4567: ##############################################
4568: =pod
4569:
4570: =item * &authorspace()
4571:
4572: Inputs: $url (usually will be undef).
4573:
4574: Returns: Path to Construction Space containing the resource or
4575: directory being viewed (or for which action is being taken).
4576: If $url is provided, and begins /priv/<domain>/<uname>
4577: the path will be that portion of the $context argument.
4578: Otherwise the path will be for the author space of the current
4579: user when the current role is author, or for that of the
4580: co-author/assistant co-author space when the current role
4581: is co-author or assistant co-author.
4582:
4583: =cut
4584:
4585: sub authorspace {
4586: my ($url) = @_;
4587: if ($url ne '') {
4588: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4589: return $1;
4590: }
4591: }
4592: my $caname = '';
4593: my $cadom = '';
4594: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4595: ($cadom,$caname) =
4596: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4597: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4598: $caname = $env{'user.name'};
4599: $cadom = $env{'user.domain'};
4600: }
4601: if (($caname ne '') && ($cadom ne '')) {
4602: return "/priv/$cadom/$caname/";
4603: }
4604: return;
4605: }
4606:
4607: ##############################################
4608: =pod
4609:
4610: =item * &head_subbox()
4611:
4612: Inputs: $content (contains HTML code with page functions, etc.)
4613:
4614: Returns: HTML div with $content
4615: To be included in page header
4616:
4617: =cut
4618:
4619: sub head_subbox {
4620: my ($content)=@_;
4621: my $output =
4622: '<div class="LC_head_subbox">'
4623: .$content
4624: .'</div>'
4625: }
4626:
4627: ##############################################
4628: =pod
4629:
4630: =item * &CSTR_pageheader()
4631:
4632: Input: (optional) filename from which breadcrumb trail is built.
4633: In most cases no input as needed, as $env{'request.filename'}
4634: is appropriate for use in building the breadcrumb trail.
4635:
4636: Returns: HTML div with CSTR path and recent box
4637: To be included on Construction Space pages
4638:
4639: =cut
4640:
4641: sub CSTR_pageheader {
4642: my ($trailfile) = @_;
4643: if ($trailfile eq '') {
4644: $trailfile = $env{'request.filename'};
4645: }
4646:
4647: # this is for resources; directories have customtitle, and crumbs
4648: # and select recent are created in lonpubdir.pm
4649:
4650: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
4651: my ($udom,$uname,$thisdisfn)=
4652: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
4653: my $formaction = "/priv/$udom/$uname/$thisdisfn";
4654: $formaction =~ s{/+}{/}g;
4655:
4656: my $parentpath = '';
4657: my $lastitem = '';
4658: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4659: $parentpath = $1;
4660: $lastitem = $2;
4661: } else {
4662: $lastitem = $thisdisfn;
4663: }
4664:
4665: my $output =
4666: '<div>'
4667: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4668: .'<b>'.&mt('Construction Space:').'</b> '
4669: .'<form name="dirs" method="post" action="'.$formaction
4670: .'" target="_top">' #FIXME lonpubdir: target="_parent"
4671: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
4672:
4673: if ($lastitem) {
4674: $output .=
4675: '<span class="LC_filename">'
4676: .$lastitem
4677: .'</span>';
4678: }
4679: $output .=
4680: '<br />'
4681: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4682: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4683: .'</form>'
4684: .&Apache::lonmenu::constspaceform()
4685: .'</div>';
4686:
4687: return $output;
4688: }
4689:
4690: ###############################################
4691: ###############################################
4692:
4693: =pod
4694:
4695: =back
4696:
4697: =head1 HTML Helpers
4698:
4699: =over 4
4700:
4701: =item * &bodytag()
4702:
4703: Returns a uniform header for LON-CAPA web pages.
4704:
4705: Inputs:
4706:
4707: =over 4
4708:
4709: =item * $title, A title to be displayed on the page.
4710:
4711: =item * $function, the current role (can be undef).
4712:
4713: =item * $addentries, extra parameters for the <body> tag.
4714:
4715: =item * $bodyonly, if defined, only return the <body> tag.
4716:
4717: =item * $domain, if defined, force a given domain.
4718:
4719: =item * $forcereg, if page should register as content page (relevant for
4720: text interface only)
4721:
4722: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
4723: navigational links
4724:
4725: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4726:
4727: =item * $args, optional argument valid values are
4728: no_auto_mt_title -> prevents &mt()ing the title arg
4729: inherit_jsmath -> when creating popup window in a page,
4730: should it have jsmath forced on by the
4731: current page
4732:
4733: =back
4734:
4735: Returns: A uniform header for LON-CAPA web pages.
4736: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4737: If $bodyonly is undef or zero, an html string containing a <body> tag and
4738: other decorations will be returned.
4739:
4740: =cut
4741:
4742: sub bodytag {
4743: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
4744: $no_nav_bar,$bgcolor,$args)=@_;
4745:
4746: my $public;
4747: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
4748: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
4749: $public = 1;
4750: }
4751: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4752:
4753: $function = &get_users_function() if (!$function);
4754: my $img = &designparm($function.'.img',$domain);
4755: my $font = &designparm($function.'.font',$domain);
4756: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4757:
4758: my %design = ( 'style' => 'margin-top: 0',
4759: 'bgcolor' => $pgbg,
4760: 'text' => $font,
4761: 'alink' => &designparm($function.'.alink',$domain),
4762: 'vlink' => &designparm($function.'.vlink',$domain),
4763: 'link' => &designparm($function.'.link',$domain),);
4764: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4765:
4766: # role and realm
4767: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4768: if ($role eq 'ca') {
4769: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4770: $realm = &plainname($rname,$rdom);
4771: }
4772: # realm
4773: if ($env{'request.course.id'}) {
4774: if ($env{'request.role'} !~ /^cr/) {
4775: $role = &Apache::lonnet::plaintext($role,&course_type());
4776: }
4777: if ($env{'request.course.sec'}) {
4778: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
4779: }
4780: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4781: } else {
4782: $role = &Apache::lonnet::plaintext($role);
4783: }
4784:
4785: if (!$realm) { $realm=' '; }
4786:
4787: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4788:
4789: # construct main body tag
4790: my $bodytag = "<body $extra_body_attr>".
4791: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4792:
4793: if ($bodyonly) {
4794: return $bodytag;
4795: }
4796:
4797: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4798: if ($public) {
4799: undef($role);
4800: } else {
4801: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4802: }
4803:
4804: my $titleinfo = '<h1>'.$title.'</h1>';
4805: #
4806: # Extra info if you are the DC
4807: my $dc_info = '';
4808: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4809: $env{'course.'.$env{'request.course.id'}.
4810: '.domain'}.'/'})) {
4811: my $cid = $env{'request.course.id'};
4812: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4813: $dc_info =~ s/\s+$//;
4814: }
4815:
4816: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
4817: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
4818:
4819: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') {
4820: return $bodytag;
4821: }
4822:
4823: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
4824:
4825: # if ($env{'request.state'} eq 'construct') {
4826: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
4827: # }
4828:
4829:
4830:
4831: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
4832: if ($dc_info) {
4833: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
4834: }
4835: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
4836: <em>$realm</em> $dc_info</div>|;
4837: return $bodytag;
4838: }
4839:
4840: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
4841: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
4842: }
4843:
4844: $bodytag .= Apache::lonhtmlcommon::scripttag(
4845: Apache::lonmenu::utilityfunctions(), 'start');
4846:
4847: $bodytag .= Apache::lonmenu::primary_menu();
4848:
4849: if ($dc_info) {
4850: $dc_info = &dc_courseid_toggle($dc_info);
4851: }
4852: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
4853:
4854: #don't show menus for public users
4855: if (!$public){
4856: $bodytag .= Apache::lonmenu::secondary_menu();
4857: $bodytag .= Apache::lonmenu::serverform();
4858: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4859: if ($env{'request.state'} eq 'construct') {
4860: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
4861: $args->{'bread_crumbs'});
4862: } elsif ($forcereg) {
4863: $bodytag .= &Apache::lonmenu::innerregister($forcereg);
4864: }
4865: }else{
4866: # this is to seperate menu from content when there's no secondary
4867: # menu. Especially needed for public accessible ressources.
4868: $bodytag .= '<hr style="clear:both" />';
4869: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4870: }
4871:
4872: return $bodytag;
4873: }
4874:
4875: sub dc_courseid_toggle {
4876: my ($dc_info) = @_;
4877: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
4878: '<a href="javascript:showCourseID();">'.
4879: &mt('(More ...)').'</a></span>'.
4880: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
4881: }
4882:
4883: sub make_attr_string {
4884: my ($register,$attr_ref) = @_;
4885:
4886: if ($attr_ref && !ref($attr_ref)) {
4887: die("addentries Must be a hash ref ".
4888: join(':',caller(1))." ".
4889: join(':',caller(0))." ");
4890: }
4891:
4892: if ($register) {
4893: my ($on_load,$on_unload);
4894: foreach my $key (keys(%{$attr_ref})) {
4895: if (lc($key) eq 'onload') {
4896: $on_load.=$attr_ref->{$key}.';';
4897: delete($attr_ref->{$key});
4898:
4899: } elsif (lc($key) eq 'onunload') {
4900: $on_unload.=$attr_ref->{$key}.';';
4901: delete($attr_ref->{$key});
4902: }
4903: }
4904: $attr_ref->{'onload'} = $on_load;
4905: $attr_ref->{'onunload'}= $on_unload;
4906: }
4907:
4908: my $attr_string;
4909: foreach my $attr (keys(%$attr_ref)) {
4910: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4911: }
4912: return $attr_string;
4913: }
4914:
4915:
4916: ###############################################
4917: ###############################################
4918:
4919: =pod
4920:
4921: =item * &endbodytag()
4922:
4923: Returns a uniform footer for LON-CAPA web pages.
4924:
4925: Inputs: 1 - optional reference to an args hash
4926: If in the hash, key for noredirectlink has a value which evaluates to true,
4927: a 'Continue' link is not displayed if the page contains an
4928: internal redirect in the <head></head> section,
4929: i.e., $env{'internal.head.redirect'} exists
4930:
4931: =cut
4932:
4933: sub endbodytag {
4934: my ($args) = @_;
4935: my $endbodytag='</body>';
4936: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4937: if ( exists( $env{'internal.head.redirect'} ) ) {
4938: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4939: $endbodytag=
4940: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4941: &mt('Continue').'</a>'.
4942: $endbodytag;
4943: }
4944: }
4945: return $endbodytag;
4946: }
4947:
4948: =pod
4949:
4950: =item * &standard_css()
4951:
4952: Returns a style sheet
4953:
4954: Inputs: (all optional)
4955: domain -> force to color decorate a page for a specific
4956: domain
4957: function -> force usage of a specific rolish color scheme
4958: bgcolor -> override the default page bgcolor
4959:
4960: =cut
4961:
4962: sub standard_css {
4963: my ($function,$domain,$bgcolor) = @_;
4964: $function = &get_users_function() if (!$function);
4965: my $img = &designparm($function.'.img', $domain);
4966: my $tabbg = &designparm($function.'.tabbg', $domain);
4967: my $font = &designparm($function.'.font', $domain);
4968: my $fontmenu = &designparm($function.'.fontmenu', $domain);
4969: #second colour for later usage
4970: my $sidebg = &designparm($function.'.sidebg',$domain);
4971: my $pgbg_or_bgcolor =
4972: $bgcolor ||
4973: &designparm($function.'.pgbg', $domain);
4974: my $pgbg = &designparm($function.'.pgbg', $domain);
4975: my $alink = &designparm($function.'.alink', $domain);
4976: my $vlink = &designparm($function.'.vlink', $domain);
4977: my $link = &designparm($function.'.link', $domain);
4978:
4979: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4980: my $mono = 'monospace';
4981: my $data_table_head = $sidebg;
4982: my $data_table_light = '#FAFAFA';
4983: my $data_table_dark = '#F0F0F0';
4984: my $data_table_darker = '#CCCCCC';
4985: my $data_table_highlight = '#FFFF00';
4986: my $mail_new = '#FFBB77';
4987: my $mail_new_hover = '#DD9955';
4988: my $mail_read = '#BBBB77';
4989: my $mail_read_hover = '#999944';
4990: my $mail_replied = '#AAAA88';
4991: my $mail_replied_hover = '#888855';
4992: my $mail_other = '#99BBBB';
4993: my $mail_other_hover = '#669999';
4994: my $table_header = '#DDDDDD';
4995: my $feedback_link_bg = '#BBBBBB';
4996: my $lg_border_color = '#C8C8C8';
4997: my $button_hover = '#BF2317';
4998:
4999: my $border = ($env{'browser.type'} eq 'explorer' ||
5000: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5001: : '0 3px 0 4px';
5002:
5003:
5004: return <<END;
5005:
5006: /* needed for iframe to allow 100% height in FF */
5007: body, html {
5008: margin: 0;
5009: padding: 0 0.5%;
5010: height: 99%; /* to avoid scrollbars */
5011: }
5012:
5013: body {
5014: font-family: $sans;
5015: line-height:130%;
5016: font-size:0.83em;
5017: color:$font;
5018: }
5019:
5020: a:focus,
5021: a:focus img {
5022: color: red;
5023: background: yellow;
5024: }
5025:
5026: form, .inline {
5027: display: inline;
5028: }
5029:
5030: .LC_right {
5031: text-align:right;
5032: }
5033:
5034: .LC_middle {
5035: vertical-align:middle;
5036: }
5037:
5038: .LC_400Box {
5039: width:400px;
5040: }
5041:
5042: .LC_iframecontainer {
5043: width: 98%;
5044: margin: 0;
5045: position: fixed;
5046: top: 8.5em;
5047: bottom: 0;
5048: }
5049:
5050: .LC_iframecontainer iframe{
5051: border: none;
5052: width: 100%;
5053: height: 100%;
5054: }
5055:
5056: .LC_filename {
5057: font-family: $mono;
5058: white-space:pre;
5059: font-size: 120%;
5060: }
5061:
5062: .LC_fileicon {
5063: border: none;
5064: height: 1.3em;
5065: vertical-align: text-bottom;
5066: margin-right: 0.3em;
5067: text-decoration:none;
5068: }
5069:
5070: .LC_setting {
5071: text-decoration:underline;
5072: }
5073:
5074: .LC_error {
5075: color: red;
5076: font-size: larger;
5077: }
5078:
5079: .LC_warning,
5080: .LC_diff_removed {
5081: color: red;
5082: }
5083:
5084: .LC_info,
5085: .LC_success,
5086: .LC_diff_added {
5087: color: green;
5088: }
5089:
5090: div.LC_confirm_box {
5091: background-color: #FAFAFA;
5092: border: 1px solid $lg_border_color;
5093: margin-right: 0;
5094: padding: 5px;
5095: }
5096:
5097: div.LC_confirm_box .LC_error img,
5098: div.LC_confirm_box .LC_success img {
5099: vertical-align: middle;
5100: }
5101:
5102: .LC_icon {
5103: border: none;
5104: vertical-align: middle;
5105: }
5106:
5107: .LC_docs_spacer {
5108: width: 25px;
5109: height: 1px;
5110: border: none;
5111: }
5112:
5113: .LC_internal_info {
5114: color: #999999;
5115: }
5116:
5117: .LC_discussion {
5118: background: $tabbg;
5119: border: 1px solid black;
5120: margin: 2px;
5121: }
5122:
5123: .LC_disc_action_links_bar {
5124: background: $tabbg;
5125: border: none;
5126: margin: 4px;
5127: }
5128:
5129: .LC_disc_action_left {
5130: text-align: left;
5131: }
5132:
5133: .LC_disc_action_right {
5134: text-align: right;
5135: }
5136:
5137: .LC_disc_new_item {
5138: background: white;
5139: border: 2px solid red;
5140: margin: 2px;
5141: }
5142:
5143: .LC_disc_old_item {
5144: background: white;
5145: border: 1px solid black;
5146: margin: 2px;
5147: }
5148:
5149: table.LC_pastsubmission {
5150: border: 1px solid black;
5151: margin: 2px;
5152: }
5153:
5154: table#LC_menubuttons {
5155: width: 100%;
5156: background: $pgbg;
5157: border: 2px;
5158: border-collapse: separate;
5159: padding: 0;
5160: }
5161:
5162: table#LC_title_bar a {
5163: color: $fontmenu;
5164: }
5165:
5166: table#LC_title_bar {
5167: clear: both;
5168: display: none;
5169: }
5170:
5171: table#LC_title_bar,
5172: table.LC_breadcrumbs, /* obsolete? */
5173: table#LC_title_bar.LC_with_remote {
5174: width: 100%;
5175: border-color: $pgbg;
5176: border-style: solid;
5177: border-width: $border;
5178: background: $pgbg;
5179: color: $fontmenu;
5180: border-collapse: collapse;
5181: padding: 0;
5182: margin: 0;
5183: }
5184:
5185: ul.LC_breadcrumb_tools_outerlist {
5186: margin: 0;
5187: padding: 0;
5188: position: relative;
5189: list-style: none;
5190: }
5191: ul.LC_breadcrumb_tools_outerlist li {
5192: display: inline;
5193: }
5194:
5195: .LC_breadcrumb_tools_navigation {
5196: padding: 0;
5197: margin: 0;
5198: float: left;
5199: }
5200: .LC_breadcrumb_tools_tools {
5201: padding: 0;
5202: margin: 0;
5203: float: right;
5204: }
5205:
5206: table#LC_title_bar td {
5207: background: $tabbg;
5208: }
5209:
5210: table#LC_menubuttons img {
5211: border: none;
5212: }
5213:
5214: .LC_breadcrumbs_component {
5215: float: right;
5216: margin: 0 1em;
5217: }
5218: .LC_breadcrumbs_component img {
5219: vertical-align: middle;
5220: }
5221:
5222: td.LC_table_cell_checkbox {
5223: text-align: center;
5224: }
5225:
5226: .LC_fontsize_small {
5227: font-size: 70%;
5228: }
5229:
5230: #LC_breadcrumbs {
5231: clear:both;
5232: background: $sidebg;
5233: border-bottom: 1px solid $lg_border_color;
5234: line-height: 2.5em;
5235: overflow: hidden;
5236: margin: 0;
5237: padding: 0;
5238: text-align: left;
5239: }
5240:
5241: .LC_head_subbox {
5242: clear:both;
5243: background: #F8F8F8; /* $sidebg; */
5244: border: 1px solid $sidebg;
5245: margin: 0 0 10px 0;
5246: padding: 3px;
5247: text-align: left;
5248: }
5249:
5250: .LC_fontsize_medium {
5251: font-size: 85%;
5252: }
5253:
5254: .LC_fontsize_large {
5255: font-size: 120%;
5256: }
5257:
5258: .LC_menubuttons_inline_text {
5259: color: $font;
5260: font-size: 90%;
5261: padding-left:3px;
5262: }
5263:
5264: .LC_menubuttons_inline_text img{
5265: vertical-align: middle;
5266: }
5267:
5268: li.LC_menubuttons_inline_text img,a {
5269: cursor:pointer;
5270: text-decoration: none;
5271: }
5272:
5273: .LC_menubuttons_link {
5274: text-decoration: none;
5275: }
5276:
5277: .LC_menubuttons_category {
5278: color: $font;
5279: background: $pgbg;
5280: font-size: larger;
5281: font-weight: bold;
5282: }
5283:
5284: td.LC_menubuttons_text {
5285: color: $font;
5286: }
5287:
5288: .LC_current_location {
5289: background: $tabbg;
5290: }
5291:
5292: table.LC_data_table {
5293: border: 1px solid #000000;
5294: border-collapse: separate;
5295: border-spacing: 1px;
5296: background: $pgbg;
5297: }
5298:
5299: .LC_data_table_dense {
5300: font-size: small;
5301: }
5302:
5303: table.LC_nested_outer {
5304: border: 1px solid #000000;
5305: border-collapse: collapse;
5306: border-spacing: 0;
5307: width: 100%;
5308: }
5309:
5310: table.LC_innerpickbox,
5311: table.LC_nested {
5312: border: none;
5313: border-collapse: collapse;
5314: border-spacing: 0;
5315: width: 100%;
5316: }
5317:
5318: table.LC_data_table tr th,
5319: table.LC_calendar tr th,
5320: table.LC_prior_tries tr th,
5321: table.LC_innerpickbox tr th {
5322: font-weight: bold;
5323: background-color: $data_table_head;
5324: color:$fontmenu;
5325: font-size:90%;
5326: }
5327:
5328: table.LC_innerpickbox tr th,
5329: table.LC_innerpickbox tr td {
5330: vertical-align: top;
5331: }
5332:
5333: table.LC_data_table tr.LC_info_row > td {
5334: background-color: #CCCCCC;
5335: font-weight: bold;
5336: text-align: left;
5337: }
5338:
5339: table.LC_data_table tr.LC_odd_row > td {
5340: background-color: $data_table_light;
5341: padding: 2px;
5342: vertical-align: top;
5343: }
5344:
5345: table.LC_pick_box tr > td.LC_odd_row {
5346: background-color: $data_table_light;
5347: vertical-align: top;
5348: }
5349:
5350: table.LC_data_table tr.LC_even_row > td {
5351: background-color: $data_table_dark;
5352: padding: 2px;
5353: vertical-align: top;
5354: }
5355:
5356: table.LC_pick_box tr > td.LC_even_row {
5357: background-color: $data_table_dark;
5358: vertical-align: top;
5359: }
5360:
5361: table.LC_data_table tr.LC_data_table_highlight td {
5362: background-color: $data_table_darker;
5363: }
5364:
5365: table.LC_data_table tr td.LC_leftcol_header {
5366: background-color: $data_table_head;
5367: font-weight: bold;
5368: }
5369:
5370: table.LC_data_table tr.LC_empty_row td,
5371: table.LC_nested tr.LC_empty_row td {
5372: font-weight: bold;
5373: font-style: italic;
5374: text-align: center;
5375: padding: 8px;
5376: }
5377:
5378: table.LC_data_table tr.LC_empty_row td {
5379: background-color: $sidebg;
5380: }
5381:
5382: table.LC_nested tr.LC_empty_row td {
5383: background-color: #FFFFFF;
5384: }
5385:
5386: table.LC_caption {
5387: }
5388:
5389: table.LC_nested tr.LC_empty_row td {
5390: padding: 4ex
5391: }
5392:
5393: table.LC_nested_outer tr th {
5394: font-weight: bold;
5395: color:$fontmenu;
5396: background-color: $data_table_head;
5397: font-size: small;
5398: border-bottom: 1px solid #000000;
5399: }
5400:
5401: table.LC_nested_outer tr td.LC_subheader {
5402: background-color: $data_table_head;
5403: font-weight: bold;
5404: font-size: small;
5405: border-bottom: 1px solid #000000;
5406: text-align: right;
5407: }
5408:
5409: table.LC_nested tr.LC_info_row td {
5410: background-color: #CCCCCC;
5411: font-weight: bold;
5412: font-size: small;
5413: text-align: center;
5414: }
5415:
5416: table.LC_nested tr.LC_info_row td.LC_left_item,
5417: table.LC_nested_outer tr th.LC_left_item {
5418: text-align: left;
5419: }
5420:
5421: table.LC_nested td {
5422: background-color: #FFFFFF;
5423: font-size: small;
5424: }
5425:
5426: table.LC_nested_outer tr th.LC_right_item,
5427: table.LC_nested tr.LC_info_row td.LC_right_item,
5428: table.LC_nested tr.LC_odd_row td.LC_right_item,
5429: table.LC_nested tr td.LC_right_item {
5430: text-align: right;
5431: }
5432:
5433: table.LC_nested tr.LC_odd_row td {
5434: background-color: #EEEEEE;
5435: }
5436:
5437: table.LC_createuser {
5438: }
5439:
5440: table.LC_createuser tr.LC_section_row td {
5441: font-size: small;
5442: }
5443:
5444: table.LC_createuser tr.LC_info_row td {
5445: background-color: #CCCCCC;
5446: font-weight: bold;
5447: text-align: center;
5448: }
5449:
5450: table.LC_calendar {
5451: border: 1px solid #000000;
5452: border-collapse: collapse;
5453: width: 98%;
5454: }
5455:
5456: table.LC_calendar_pickdate {
5457: font-size: xx-small;
5458: }
5459:
5460: table.LC_calendar tr td {
5461: border: 1px solid #000000;
5462: vertical-align: top;
5463: width: 14%;
5464: }
5465:
5466: table.LC_calendar tr td.LC_calendar_day_empty {
5467: background-color: $data_table_dark;
5468: }
5469:
5470: table.LC_calendar tr td.LC_calendar_day_current {
5471: background-color: $data_table_highlight;
5472: }
5473:
5474: table.LC_data_table tr td.LC_mail_new {
5475: background-color: $mail_new;
5476: }
5477:
5478: table.LC_data_table tr.LC_mail_new:hover {
5479: background-color: $mail_new_hover;
5480: }
5481:
5482: table.LC_data_table tr td.LC_mail_read {
5483: background-color: $mail_read;
5484: }
5485:
5486: /*
5487: table.LC_data_table tr.LC_mail_read:hover {
5488: background-color: $mail_read_hover;
5489: }
5490: */
5491:
5492: table.LC_data_table tr td.LC_mail_replied {
5493: background-color: $mail_replied;
5494: }
5495:
5496: /*
5497: table.LC_data_table tr.LC_mail_replied:hover {
5498: background-color: $mail_replied_hover;
5499: }
5500: */
5501:
5502: table.LC_data_table tr td.LC_mail_other {
5503: background-color: $mail_other;
5504: }
5505:
5506: /*
5507: table.LC_data_table tr.LC_mail_other:hover {
5508: background-color: $mail_other_hover;
5509: }
5510: */
5511:
5512: table.LC_data_table tr > td.LC_browser_file,
5513: table.LC_data_table tr > td.LC_browser_file_published {
5514: background: #AAEE77;
5515: }
5516:
5517: table.LC_data_table tr > td.LC_browser_file_locked,
5518: table.LC_data_table tr > td.LC_browser_file_unpublished {
5519: background: #FFAA99;
5520: }
5521:
5522: table.LC_data_table tr > td.LC_browser_file_obsolete {
5523: background: #888888;
5524: }
5525:
5526: table.LC_data_table tr > td.LC_browser_file_modified,
5527: table.LC_data_table tr > td.LC_browser_file_metamodified {
5528: background: #F8F866;
5529: }
5530:
5531: table.LC_data_table tr.LC_browser_folder > td {
5532: background: #E0E8FF;
5533: }
5534:
5535: table.LC_data_table tr > td.LC_roles_is {
5536: /* background: #77FF77; */
5537: }
5538:
5539: table.LC_data_table tr > td.LC_roles_future {
5540: border-right: 8px solid #FFFF77;
5541: }
5542:
5543: table.LC_data_table tr > td.LC_roles_will {
5544: border-right: 8px solid #FFAA77;
5545: }
5546:
5547: table.LC_data_table tr > td.LC_roles_expired {
5548: border-right: 8px solid #FF7777;
5549: }
5550:
5551: table.LC_data_table tr > td.LC_roles_will_not {
5552: border-right: 8px solid #AAFF77;
5553: }
5554:
5555: table.LC_data_table tr > td.LC_roles_selected {
5556: border-right: 8px solid #11CC55;
5557: }
5558:
5559: span.LC_current_location {
5560: font-size:larger;
5561: background: $pgbg;
5562: }
5563:
5564: span.LC_parm_menu_item {
5565: font-size: larger;
5566: }
5567:
5568: span.LC_parm_scope_all {
5569: color: red;
5570: }
5571:
5572: span.LC_parm_scope_folder {
5573: color: green;
5574: }
5575:
5576: span.LC_parm_scope_resource {
5577: color: orange;
5578: }
5579:
5580: span.LC_parm_part {
5581: color: blue;
5582: }
5583:
5584: span.LC_parm_folder,
5585: span.LC_parm_symb {
5586: font-size: x-small;
5587: font-family: $mono;
5588: color: #AAAAAA;
5589: }
5590:
5591: ul.LC_parm_parmlist li {
5592: display: inline-block;
5593: padding: 0.3em 0.8em;
5594: vertical-align: top;
5595: width: 150px;
5596: border-top:1px solid $lg_border_color;
5597: }
5598:
5599: td.LC_parm_overview_level_menu,
5600: td.LC_parm_overview_map_menu,
5601: td.LC_parm_overview_parm_selectors,
5602: td.LC_parm_overview_restrictions {
5603: border: 1px solid black;
5604: border-collapse: collapse;
5605: }
5606:
5607: table.LC_parm_overview_restrictions td {
5608: border-width: 1px 4px 1px 4px;
5609: border-style: solid;
5610: border-color: $pgbg;
5611: text-align: center;
5612: }
5613:
5614: table.LC_parm_overview_restrictions th {
5615: background: $tabbg;
5616: border-width: 1px 4px 1px 4px;
5617: border-style: solid;
5618: border-color: $pgbg;
5619: }
5620:
5621: table#LC_helpmenu {
5622: border: none;
5623: height: 55px;
5624: border-spacing: 0;
5625: }
5626:
5627: table#LC_helpmenu fieldset legend {
5628: font-size: larger;
5629: }
5630:
5631: table#LC_helpmenu_links {
5632: width: 100%;
5633: border: 1px solid black;
5634: background: $pgbg;
5635: padding: 0;
5636: border-spacing: 1px;
5637: }
5638:
5639: table#LC_helpmenu_links tr td {
5640: padding: 1px;
5641: background: $tabbg;
5642: text-align: center;
5643: font-weight: bold;
5644: }
5645:
5646: table#LC_helpmenu_links a:link,
5647: table#LC_helpmenu_links a:visited,
5648: table#LC_helpmenu_links a:active {
5649: text-decoration: none;
5650: color: $font;
5651: }
5652:
5653: table#LC_helpmenu_links a:hover {
5654: text-decoration: underline;
5655: color: $vlink;
5656: }
5657:
5658: .LC_chrt_popup_exists {
5659: border: 1px solid #339933;
5660: margin: -1px;
5661: }
5662:
5663: .LC_chrt_popup_up {
5664: border: 1px solid yellow;
5665: margin: -1px;
5666: }
5667:
5668: .LC_chrt_popup {
5669: border: 1px solid #8888FF;
5670: background: #CCCCFF;
5671: }
5672:
5673: table.LC_pick_box {
5674: border-collapse: separate;
5675: background: white;
5676: border: 1px solid black;
5677: border-spacing: 1px;
5678: }
5679:
5680: table.LC_pick_box td.LC_pick_box_title {
5681: background: $sidebg;
5682: font-weight: bold;
5683: text-align: left;
5684: vertical-align: top;
5685: width: 184px;
5686: padding: 8px;
5687: }
5688:
5689: table.LC_pick_box td.LC_pick_box_value {
5690: text-align: left;
5691: padding: 8px;
5692: }
5693:
5694: table.LC_pick_box td.LC_pick_box_select {
5695: text-align: left;
5696: padding: 8px;
5697: }
5698:
5699: table.LC_pick_box td.LC_pick_box_separator {
5700: padding: 0;
5701: height: 1px;
5702: background: black;
5703: }
5704:
5705: table.LC_pick_box td.LC_pick_box_submit {
5706: text-align: right;
5707: }
5708:
5709: table.LC_pick_box td.LC_evenrow_value {
5710: text-align: left;
5711: padding: 8px;
5712: background-color: $data_table_light;
5713: }
5714:
5715: table.LC_pick_box td.LC_oddrow_value {
5716: text-align: left;
5717: padding: 8px;
5718: background-color: $data_table_light;
5719: }
5720:
5721: span.LC_helpform_receipt_cat {
5722: font-weight: bold;
5723: }
5724:
5725: table.LC_group_priv_box {
5726: background: white;
5727: border: 1px solid black;
5728: border-spacing: 1px;
5729: }
5730:
5731: table.LC_group_priv_box td.LC_pick_box_title {
5732: background: $tabbg;
5733: font-weight: bold;
5734: text-align: right;
5735: width: 184px;
5736: }
5737:
5738: table.LC_group_priv_box td.LC_groups_fixed {
5739: background: $data_table_light;
5740: text-align: center;
5741: }
5742:
5743: table.LC_group_priv_box td.LC_groups_optional {
5744: background: $data_table_dark;
5745: text-align: center;
5746: }
5747:
5748: table.LC_group_priv_box td.LC_groups_functionality {
5749: background: $data_table_darker;
5750: text-align: center;
5751: font-weight: bold;
5752: }
5753:
5754: table.LC_group_priv td {
5755: text-align: left;
5756: padding: 0;
5757: }
5758:
5759: .LC_navbuttons {
5760: margin: 2ex 0ex 2ex 0ex;
5761: }
5762:
5763: .LC_topic_bar {
5764: font-weight: bold;
5765: background: $tabbg;
5766: margin: 1em 0em 1em 2em;
5767: padding: 3px;
5768: font-size: 1.2em;
5769: }
5770:
5771: .LC_topic_bar span {
5772: left: 0.5em;
5773: position: absolute;
5774: vertical-align: middle;
5775: font-size: 1.2em;
5776: }
5777:
5778: table.LC_course_group_status {
5779: margin: 20px;
5780: }
5781:
5782: table.LC_status_selector td {
5783: vertical-align: top;
5784: text-align: center;
5785: padding: 4px;
5786: }
5787:
5788: div.LC_feedback_link {
5789: clear: both;
5790: background: $sidebg;
5791: width: 100%;
5792: padding-bottom: 10px;
5793: border: 1px $tabbg solid;
5794: height: 22px;
5795: line-height: 22px;
5796: padding-top: 5px;
5797: }
5798:
5799: div.LC_feedback_link img {
5800: height: 22px;
5801: vertical-align:middle;
5802: }
5803:
5804: div.LC_feedback_link a {
5805: text-decoration: none;
5806: }
5807:
5808: div.LC_comblock {
5809: display:inline;
5810: color:$font;
5811: font-size:90%;
5812: }
5813:
5814: div.LC_feedback_link div.LC_comblock {
5815: padding-left:5px;
5816: }
5817:
5818: div.LC_feedback_link div.LC_comblock a {
5819: color:$font;
5820: }
5821:
5822: span.LC_feedback_link {
5823: /* background: $feedback_link_bg; */
5824: font-size: larger;
5825: }
5826:
5827: span.LC_message_link {
5828: /* background: $feedback_link_bg; */
5829: font-size: larger;
5830: position: absolute;
5831: right: 1em;
5832: }
5833:
5834: table.LC_prior_tries {
5835: border: 1px solid #000000;
5836: border-collapse: separate;
5837: border-spacing: 1px;
5838: }
5839:
5840: table.LC_prior_tries td {
5841: padding: 2px;
5842: }
5843:
5844: .LC_answer_correct {
5845: background: lightgreen;
5846: color: darkgreen;
5847: padding: 6px;
5848: }
5849:
5850: .LC_answer_charged_try {
5851: background: #FFAAAA;
5852: color: darkred;
5853: padding: 6px;
5854: }
5855:
5856: .LC_answer_not_charged_try,
5857: .LC_answer_no_grade,
5858: .LC_answer_late {
5859: background: lightyellow;
5860: color: black;
5861: padding: 6px;
5862: }
5863:
5864: .LC_answer_previous {
5865: background: lightblue;
5866: color: darkblue;
5867: padding: 6px;
5868: }
5869:
5870: .LC_answer_no_message {
5871: background: #FFFFFF;
5872: color: black;
5873: padding: 6px;
5874: }
5875:
5876: .LC_answer_unknown {
5877: background: orange;
5878: color: black;
5879: padding: 6px;
5880: }
5881:
5882: span.LC_prior_numerical,
5883: span.LC_prior_string,
5884: span.LC_prior_custom,
5885: span.LC_prior_reaction,
5886: span.LC_prior_math {
5887: font-family: $mono;
5888: white-space: pre;
5889: }
5890:
5891: span.LC_prior_string {
5892: font-family: $mono;
5893: white-space: pre;
5894: }
5895:
5896: table.LC_prior_option {
5897: width: 100%;
5898: border-collapse: collapse;
5899: }
5900:
5901: table.LC_prior_rank,
5902: table.LC_prior_match {
5903: border-collapse: collapse;
5904: }
5905:
5906: table.LC_prior_option tr td,
5907: table.LC_prior_rank tr td,
5908: table.LC_prior_match tr td {
5909: border: 1px solid #000000;
5910: }
5911:
5912: .LC_nobreak {
5913: white-space: nowrap;
5914: }
5915:
5916: span.LC_cusr_emph {
5917: font-style: italic;
5918: }
5919:
5920: span.LC_cusr_subheading {
5921: font-weight: normal;
5922: font-size: 85%;
5923: }
5924:
5925: div.LC_docs_entry_move {
5926: border: 1px solid #BBBBBB;
5927: background: #DDDDDD;
5928: width: 22px;
5929: padding: 1px;
5930: margin: 0;
5931: }
5932:
5933: table.LC_data_table tr > td.LC_docs_entry_commands,
5934: table.LC_data_table tr > td.LC_docs_entry_parameter {
5935: background: #DDDDDD;
5936: font-size: x-small;
5937: }
5938:
5939: .LC_docs_entry_parameter {
5940: white-space: nowrap;
5941: }
5942:
5943: .LC_docs_copy {
5944: color: #000099;
5945: }
5946:
5947: .LC_docs_cut {
5948: color: #550044;
5949: }
5950:
5951: .LC_docs_rename {
5952: color: #009900;
5953: }
5954:
5955: .LC_docs_remove {
5956: color: #990000;
5957: }
5958:
5959: .LC_docs_reinit_warn,
5960: .LC_docs_ext_edit {
5961: font-size: x-small;
5962: }
5963:
5964: table.LC_docs_adddocs td,
5965: table.LC_docs_adddocs th {
5966: border: 1px solid #BBBBBB;
5967: padding: 4px;
5968: background: #DDDDDD;
5969: }
5970:
5971: table.LC_sty_begin {
5972: background: #BBFFBB;
5973: }
5974:
5975: table.LC_sty_end {
5976: background: #FFBBBB;
5977: }
5978:
5979: table.LC_double_column {
5980: border-width: 0;
5981: border-collapse: collapse;
5982: width: 100%;
5983: padding: 2px;
5984: }
5985:
5986: table.LC_double_column tr td.LC_left_col {
5987: top: 2px;
5988: left: 2px;
5989: width: 47%;
5990: vertical-align: top;
5991: }
5992:
5993: table.LC_double_column tr td.LC_right_col {
5994: top: 2px;
5995: right: 2px;
5996: width: 47%;
5997: vertical-align: top;
5998: }
5999:
6000: div.LC_left_float {
6001: float: left;
6002: padding-right: 5%;
6003: padding-bottom: 4px;
6004: }
6005:
6006: div.LC_clear_float_header {
6007: padding-bottom: 2px;
6008: }
6009:
6010: div.LC_clear_float_footer {
6011: padding-top: 10px;
6012: clear: both;
6013: }
6014:
6015: div.LC_grade_show_user {
6016: /* border-left: 5px solid $sidebg; */
6017: border-top: 5px solid #000000;
6018: margin: 50px 0 0 0;
6019: padding: 15px 0 5px 10px;
6020: }
6021:
6022: div.LC_grade_show_user_odd_row {
6023: /* border-left: 5px solid #000000; */
6024: }
6025:
6026: div.LC_grade_show_user div.LC_Box {
6027: margin-right: 50px;
6028: }
6029:
6030: div.LC_grade_submissions,
6031: div.LC_grade_message_center,
6032: div.LC_grade_info_links {
6033: margin: 5px;
6034: width: 99%;
6035: background: #FFFFFF;
6036: }
6037:
6038: div.LC_grade_submissions_header,
6039: div.LC_grade_message_center_header {
6040: font-weight: bold;
6041: font-size: large;
6042: }
6043:
6044: div.LC_grade_submissions_body,
6045: div.LC_grade_message_center_body {
6046: border: 1px solid black;
6047: width: 99%;
6048: background: #FFFFFF;
6049: }
6050:
6051: table.LC_scantron_action {
6052: width: 100%;
6053: }
6054:
6055: table.LC_scantron_action tr th {
6056: font-weight:bold;
6057: font-style:normal;
6058: }
6059:
6060: .LC_edit_problem_header,
6061: div.LC_edit_problem_footer {
6062: font-weight: normal;
6063: font-size: medium;
6064: margin: 2px;
6065: }
6066:
6067: div.LC_edit_problem_header,
6068: div.LC_edit_problem_header div,
6069: div.LC_edit_problem_footer,
6070: div.LC_edit_problem_footer div,
6071: div.LC_edit_problem_editxml_header,
6072: div.LC_edit_problem_editxml_header div {
6073: margin-top: 5px;
6074: }
6075:
6076: div.LC_edit_problem_header_title {
6077: font-weight: bold;
6078: font-size: larger;
6079: background: $tabbg;
6080: padding: 3px;
6081: }
6082:
6083: table.LC_edit_problem_header_title {
6084: width: 100%;
6085: background: $tabbg;
6086: }
6087:
6088: div.LC_edit_problem_discards {
6089: float: left;
6090: padding-bottom: 5px;
6091: }
6092:
6093: div.LC_edit_problem_saves {
6094: float: right;
6095: padding-bottom: 5px;
6096: }
6097:
6098: img.stift {
6099: border-width: 0;
6100: vertical-align: middle;
6101: }
6102:
6103: table td.LC_mainmenu_col_fieldset {
6104: vertical-align: top;
6105: }
6106:
6107: div.LC_createcourse {
6108: margin: 10px 10px 10px 10px;
6109: }
6110:
6111: .LC_dccid {
6112: margin: 0.2em 0 0 0;
6113: padding: 0;
6114: font-size: 90%;
6115: display:none;
6116: }
6117:
6118: a:hover,
6119: ol.LC_primary_menu a:hover,
6120: ol#LC_MenuBreadcrumbs a:hover,
6121: ol#LC_PathBreadcrumbs a:hover,
6122: ul#LC_secondary_menu a:hover,
6123: .LC_FormSectionClearButton input:hover
6124: ul.LC_TabContent li:hover a {
6125: color:$button_hover;
6126: text-decoration:none;
6127: }
6128:
6129: h1 {
6130: padding: 0;
6131: line-height:130%;
6132: }
6133:
6134: h2,
6135: h3,
6136: h4,
6137: h5,
6138: h6 {
6139: margin: 5px 0 5px 0;
6140: padding: 0;
6141: line-height:130%;
6142: }
6143:
6144: .LC_hcell {
6145: padding:3px 15px 3px 15px;
6146: margin: 0;
6147: background-color:$tabbg;
6148: color:$fontmenu;
6149: border-bottom:solid 1px $lg_border_color;
6150: }
6151:
6152: .LC_Box > .LC_hcell {
6153: margin: 0 -10px 10px -10px;
6154: }
6155:
6156: .LC_noBorder {
6157: border: 0;
6158: }
6159:
6160: .LC_FormSectionClearButton input {
6161: background-color:transparent;
6162: border: none;
6163: cursor:pointer;
6164: text-decoration:underline;
6165: }
6166:
6167: .LC_help_open_topic {
6168: color: #FFFFFF;
6169: background-color: #EEEEFF;
6170: margin: 1px;
6171: padding: 4px;
6172: border: 1px solid #000033;
6173: white-space: nowrap;
6174: /* vertical-align: middle; */
6175: }
6176:
6177: dl,
6178: ul,
6179: div,
6180: fieldset {
6181: margin: 10px 10px 10px 0;
6182: /* overflow: hidden; */
6183: }
6184:
6185: fieldset > legend {
6186: font-weight: bold;
6187: padding: 0 5px 0 5px;
6188: }
6189:
6190: #LC_nav_bar {
6191: float: left;
6192: background-color: $pgbg_or_bgcolor;
6193: margin: 0 0 2px 0;
6194: }
6195:
6196: #LC_realm {
6197: margin: 0.2em 0 0 0;
6198: padding: 0;
6199: font-weight: bold;
6200: text-align: center;
6201: background-color: $pgbg_or_bgcolor;
6202: }
6203:
6204: #LC_nav_bar em {
6205: font-weight: bold;
6206: font-style: normal;
6207: }
6208:
6209: ol.LC_primary_menu {
6210: float: right;
6211: margin: 0;
6212: background-color: $pgbg_or_bgcolor;
6213: }
6214:
6215: ol#LC_PathBreadcrumbs {
6216: margin: 0;
6217: }
6218:
6219: ol.LC_primary_menu li {
6220: display: inline;
6221: padding: 5px 5px 0 10px;
6222: vertical-align: top;
6223: }
6224:
6225: ol.LC_primary_menu li img {
6226: vertical-align: bottom;
6227: height: 1.1em;
6228: }
6229:
6230: ol.LC_primary_menu a {
6231: color: RGB(80, 80, 80);
6232: text-decoration: none;
6233: }
6234:
6235: ol.LC_primary_menu a.LC_new_message {
6236: font-weight:bold;
6237: color: darkred;
6238: }
6239:
6240: ol.LC_docs_parameters {
6241: margin-left: 0;
6242: padding: 0;
6243: list-style: none;
6244: }
6245:
6246: ol.LC_docs_parameters li {
6247: margin: 0;
6248: padding-right: 20px;
6249: display: inline;
6250: }
6251:
6252: ol.LC_docs_parameters li:before {
6253: content: "\\002022 \\0020";
6254: }
6255:
6256: li.LC_docs_parameters_title {
6257: font-weight: bold;
6258: }
6259:
6260: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6261: content: "";
6262: }
6263:
6264: ul#LC_secondary_menu {
6265: clear: both;
6266: color: $fontmenu;
6267: background: $tabbg;
6268: list-style: none;
6269: padding: 0;
6270: margin: 0;
6271: width: 100%;
6272: text-align: left;
6273: }
6274:
6275: ul#LC_secondary_menu li {
6276: font-weight: bold;
6277: line-height: 1.8em;
6278: padding: 0 0.8em;
6279: border-right: 1px solid black;
6280: display: inline;
6281: vertical-align: middle;
6282: }
6283:
6284: ul.LC_TabContent {
6285: display:block;
6286: background: $sidebg;
6287: border-bottom: solid 1px $lg_border_color;
6288: list-style:none;
6289: margin: -1px -10px 0 -10px;
6290: padding: 0;
6291: }
6292:
6293: ul.LC_TabContent li,
6294: ul.LC_TabContentBigger li {
6295: float:left;
6296: }
6297:
6298: ul#LC_secondary_menu li a {
6299: color: $fontmenu;
6300: text-decoration: none;
6301: }
6302:
6303: ul.LC_TabContent {
6304: min-height:20px;
6305: }
6306:
6307: ul.LC_TabContent li {
6308: vertical-align:middle;
6309: padding: 0 16px 0 10px;
6310: background-color:$tabbg;
6311: border-bottom:solid 1px $lg_border_color;
6312: border-left: solid 1px $font;
6313: }
6314:
6315: ul.LC_TabContent .right {
6316: float:right;
6317: }
6318:
6319: ul.LC_TabContent li a,
6320: ul.LC_TabContent li {
6321: color:rgb(47,47,47);
6322: text-decoration:none;
6323: font-size:95%;
6324: font-weight:bold;
6325: min-height:20px;
6326: }
6327:
6328: ul.LC_TabContent li a:hover,
6329: ul.LC_TabContent li a:focus {
6330: color: $button_hover;
6331: background:none;
6332: outline:none;
6333: }
6334:
6335: ul.LC_TabContent li:hover {
6336: color: $button_hover;
6337: cursor:pointer;
6338: }
6339:
6340: ul.LC_TabContent li.active {
6341: color: $font;
6342: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6343: border-bottom:solid 1px #FFFFFF;
6344: cursor: default;
6345: }
6346:
6347: ul.LC_TabContent li.active a {
6348: color:$font;
6349: background:#FFFFFF;
6350: outline: none;
6351: }
6352: #maincoursedoc {
6353: clear:both;
6354: }
6355:
6356: ul.LC_TabContentBigger {
6357: display:block;
6358: list-style:none;
6359: padding: 0;
6360: }
6361:
6362: ul.LC_TabContentBigger li {
6363: vertical-align:bottom;
6364: height: 30px;
6365: font-size:110%;
6366: font-weight:bold;
6367: color: #737373;
6368: }
6369:
6370: ul.LC_TabContentBigger li.active {
6371: position: relative;
6372: top: 1px;
6373: }
6374:
6375: ul.LC_TabContentBigger li a {
6376: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6377: height: 30px;
6378: line-height: 30px;
6379: text-align: center;
6380: display: block;
6381: text-decoration: none;
6382: outline: none;
6383: }
6384:
6385: ul.LC_TabContentBigger li.active a {
6386: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6387: color:$font;
6388: }
6389:
6390: ul.LC_TabContentBigger li b {
6391: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6392: display: block;
6393: float: left;
6394: padding: 0 30px;
6395: border-bottom: 1px solid $lg_border_color;
6396: }
6397:
6398: ul.LC_TabContentBigger li:hover b {
6399: color:$button_hover;
6400: }
6401:
6402: ul.LC_TabContentBigger li.active b {
6403: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6404: color:$font;
6405: border: 0;
6406: }
6407:
6408:
6409: ul.LC_CourseBreadcrumbs {
6410: background: $sidebg;
6411: height: 2em;
6412: padding-left: 10px;
6413: margin: 0;
6414: list-style-position: inside;
6415: }
6416:
6417: ol#LC_MenuBreadcrumbs,
6418: ol#LC_PathBreadcrumbs {
6419: padding-left: 10px;
6420: margin: 0;
6421: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6422: }
6423:
6424: ol#LC_MenuBreadcrumbs li,
6425: ol#LC_PathBreadcrumbs li,
6426: ul.LC_CourseBreadcrumbs li {
6427: display: inline;
6428: white-space: normal;
6429: }
6430:
6431: ol#LC_MenuBreadcrumbs li a,
6432: ul.LC_CourseBreadcrumbs li a {
6433: text-decoration: none;
6434: font-size:90%;
6435: }
6436:
6437: ol#LC_MenuBreadcrumbs h1 {
6438: display: inline;
6439: font-size: 90%;
6440: line-height: 2.5em;
6441: margin: 0;
6442: padding: 0;
6443: }
6444:
6445: ol#LC_PathBreadcrumbs li a {
6446: text-decoration:none;
6447: font-size:100%;
6448: font-weight:bold;
6449: }
6450:
6451: .LC_Box {
6452: border: solid 1px $lg_border_color;
6453: padding: 0 10px 10px 10px;
6454: }
6455:
6456: .LC_DocsBox {
6457: border: solid 1px $lg_border_color;
6458: padding: 0 0 10px 10px;
6459: }
6460:
6461: .LC_AboutMe_Image {
6462: float:left;
6463: margin-right:10px;
6464: }
6465:
6466: .LC_Clear_AboutMe_Image {
6467: clear:left;
6468: }
6469:
6470: dl.LC_ListStyleClean dt {
6471: padding-right: 5px;
6472: display: table-header-group;
6473: }
6474:
6475: dl.LC_ListStyleClean dd {
6476: display: table-row;
6477: }
6478:
6479: .LC_ListStyleClean,
6480: .LC_ListStyleSimple,
6481: .LC_ListStyleNormal,
6482: .LC_ListStyleSpecial {
6483: /* display:block; */
6484: list-style-position: inside;
6485: list-style-type: none;
6486: overflow: hidden;
6487: padding: 0;
6488: }
6489:
6490: .LC_ListStyleSimple li,
6491: .LC_ListStyleSimple dd,
6492: .LC_ListStyleNormal li,
6493: .LC_ListStyleNormal dd,
6494: .LC_ListStyleSpecial li,
6495: .LC_ListStyleSpecial dd {
6496: margin: 0;
6497: padding: 5px 5px 5px 10px;
6498: clear: both;
6499: }
6500:
6501: .LC_ListStyleClean li,
6502: .LC_ListStyleClean dd {
6503: padding-top: 0;
6504: padding-bottom: 0;
6505: }
6506:
6507: .LC_ListStyleSimple dd,
6508: .LC_ListStyleSimple li {
6509: border-bottom: solid 1px $lg_border_color;
6510: }
6511:
6512: .LC_ListStyleSpecial li,
6513: .LC_ListStyleSpecial dd {
6514: list-style-type: none;
6515: background-color: RGB(220, 220, 220);
6516: margin-bottom: 4px;
6517: }
6518:
6519: table.LC_SimpleTable {
6520: margin:5px;
6521: border:solid 1px $lg_border_color;
6522: }
6523:
6524: table.LC_SimpleTable tr {
6525: padding: 0;
6526: border:solid 1px $lg_border_color;
6527: }
6528:
6529: table.LC_SimpleTable thead {
6530: background:rgb(220,220,220);
6531: }
6532:
6533: div.LC_columnSection {
6534: display: block;
6535: clear: both;
6536: overflow: hidden;
6537: margin: 0;
6538: }
6539:
6540: div.LC_columnSection>* {
6541: float: left;
6542: margin: 10px 20px 10px 0;
6543: overflow:hidden;
6544: }
6545:
6546: table em {
6547: font-weight: bold;
6548: font-style: normal;
6549: }
6550:
6551: table.LC_tableBrowseRes,
6552: table.LC_tableOfContent {
6553: border:none;
6554: border-spacing: 1px;
6555: padding: 3px;
6556: background-color: #FFFFFF;
6557: font-size: 90%;
6558: }
6559:
6560: table.LC_tableOfContent {
6561: border-collapse: collapse;
6562: }
6563:
6564: table.LC_tableBrowseRes a,
6565: table.LC_tableOfContent a {
6566: background-color: transparent;
6567: text-decoration: none;
6568: }
6569:
6570: table.LC_tableOfContent img {
6571: border: none;
6572: height: 1.3em;
6573: vertical-align: text-bottom;
6574: margin-right: 0.3em;
6575: }
6576:
6577: a#LC_content_toolbar_firsthomework {
6578: background-image:url(/res/adm/pages/open-first-problem.gif);
6579: }
6580:
6581: a#LC_content_toolbar_everything {
6582: background-image:url(/res/adm/pages/show-all.gif);
6583: }
6584:
6585: a#LC_content_toolbar_uncompleted {
6586: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
6587: }
6588:
6589: #LC_content_toolbar_clearbubbles {
6590: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
6591: }
6592:
6593: a#LC_content_toolbar_changefolder {
6594: background : url(/res/adm/pages/close-all-folders.gif) top center ;
6595: }
6596:
6597: a#LC_content_toolbar_changefolder_toggled {
6598: background-image:url(/res/adm/pages/open-all-folders.gif);
6599: }
6600:
6601: ul#LC_toolbar li a:hover {
6602: background-position: bottom center;
6603: }
6604:
6605: ul#LC_toolbar {
6606: padding: 0;
6607: margin: 2px;
6608: list-style:none;
6609: position:relative;
6610: background-color:white;
6611: }
6612:
6613: ul#LC_toolbar li {
6614: border:1px solid white;
6615: padding: 0;
6616: margin: 0;
6617: float: left;
6618: display:inline;
6619: vertical-align:middle;
6620: }
6621:
6622:
6623: a.LC_toolbarItem {
6624: display:block;
6625: padding: 0;
6626: margin: 0;
6627: height: 32px;
6628: width: 32px;
6629: color:white;
6630: border: none;
6631: background-repeat:no-repeat;
6632: background-color:transparent;
6633: }
6634:
6635: ul.LC_funclist {
6636: margin: 0;
6637: padding: 0.5em 1em 0.5em 0;
6638: }
6639:
6640: ul.LC_funclist > li:first-child {
6641: font-weight:bold;
6642: margin-left:0.8em;
6643: }
6644:
6645: ul.LC_funclist + ul.LC_funclist {
6646: /*
6647: left border as a seperator if we have more than
6648: one list
6649: */
6650: border-left: 1px solid $sidebg;
6651: /*
6652: this hides the left border behind the border of the
6653: outer box if element is wrapped to the next 'line'
6654: */
6655: margin-left: -1px;
6656: }
6657:
6658: ul.LC_funclist li {
6659: display: inline;
6660: white-space: nowrap;
6661: margin: 0 0 0 25px;
6662: line-height: 150%;
6663: }
6664:
6665: .LC_hidden {
6666: display: none;
6667: }
6668:
6669: END
6670: }
6671:
6672: =pod
6673:
6674: =item * &headtag()
6675:
6676: Returns a uniform footer for LON-CAPA web pages.
6677:
6678: Inputs: $title - optional title for the head
6679: $head_extra - optional extra HTML to put inside the <head>
6680: $args - optional arguments
6681: force_register - if is true call registerurl so the remote is
6682: informed
6683: redirect -> array ref of
6684: 1- seconds before redirect occurs
6685: 2- url to redirect to
6686: 3- whether the side effect should occur
6687: (side effect of setting
6688: $env{'internal.head.redirect'} to the url
6689: redirected too)
6690: domain -> force to color decorate a page for a specific
6691: domain
6692: function -> force usage of a specific rolish color scheme
6693: bgcolor -> override the default page bgcolor
6694: no_auto_mt_title
6695: -> prevent &mt()ing the title arg
6696:
6697: =cut
6698:
6699: sub headtag {
6700: my ($title,$head_extra,$args) = @_;
6701:
6702: my $function = $args->{'function'} || &get_users_function();
6703: my $domain = $args->{'domain'} || &determinedomain();
6704: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
6705: my $url = join(':',$env{'user.name'},$env{'user.domain'},
6706: $Apache::lonnet::perlvar{'lonVersion'},
6707: #time(),
6708: $env{'environment.color.timestamp'},
6709: $function,$domain,$bgcolor);
6710:
6711: $url = '/adm/css/'.&escape($url).'.css';
6712:
6713: my $result =
6714: '<head>'.
6715: &font_settings();
6716:
6717: if (!$args->{'frameset'}) {
6718: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
6719: }
6720: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
6721: $result .= Apache::lonxml::display_title();
6722: }
6723: if (!$args->{'no_nav_bar'}
6724: && !$args->{'only_body'}
6725: && !$args->{'frameset'}) {
6726: $result .= &help_menu_js();
6727: }
6728:
6729: if (ref($args->{'redirect'})) {
6730: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
6731: $url = &Apache::lonenc::check_encrypt($url);
6732: if (!$inhibit_continue) {
6733: $env{'internal.head.redirect'} = $url;
6734: }
6735: $result.=<<ADDMETA
6736: <meta http-equiv="pragma" content="no-cache" />
6737: <meta http-equiv="Refresh" content="$time; url=$url" />
6738: ADDMETA
6739: }
6740: if (!defined($title)) {
6741: $title = 'The LearningOnline Network with CAPA';
6742: }
6743: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6744: $result .= '<title> LON-CAPA '.$title.'</title>'
6745: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
6746: .$head_extra;
6747: return $result.'</head>';
6748: }
6749:
6750: =pod
6751:
6752: =item * &font_settings()
6753:
6754: Returns neccessary <meta> to set the proper encoding
6755:
6756: Inputs: none
6757:
6758: =cut
6759:
6760: sub font_settings {
6761: my $headerstring='';
6762: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
6763: $headerstring.=
6764: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
6765: }
6766: return $headerstring;
6767: }
6768:
6769: =pod
6770:
6771: =item * &xml_begin()
6772:
6773: Returns the needed doctype and <html>
6774:
6775: Inputs: none
6776:
6777: =cut
6778:
6779: sub xml_begin {
6780: my $output='';
6781:
6782: if ($env{'browser.mathml'}) {
6783: $output='<?xml version="1.0"?>'
6784: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
6785: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
6786:
6787: # .'<!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">] >'
6788: .'<!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">'
6789: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
6790: .'xmlns="http://www.w3.org/1999/xhtml">';
6791: } else {
6792: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
6793: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
6794: }
6795: return $output;
6796: }
6797:
6798: =pod
6799:
6800: =item * &start_page()
6801:
6802: Returns a complete <html> .. <body> section for LON-CAPA web pages.
6803:
6804: Inputs:
6805:
6806: =over 4
6807:
6808: $title - optional title for the page
6809:
6810: $head_extra - optional extra HTML to incude inside the <head>
6811:
6812: $args - additional optional args supported are:
6813:
6814: =over 8
6815:
6816: only_body -> is true will set &bodytag() onlybodytag
6817: arg on
6818: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
6819: add_entries -> additional attributes to add to the <body>
6820: domain -> force to color decorate a page for a
6821: specific domain
6822: function -> force usage of a specific rolish color
6823: scheme
6824: redirect -> see &headtag()
6825: bgcolor -> override the default page bg color
6826: js_ready -> return a string ready for being used in
6827: a javascript writeln
6828: html_encode -> return a string ready for being used in
6829: a html attribute
6830: force_register -> if is true will turn on the &bodytag()
6831: $forcereg arg
6832: frameset -> if true will start with a <frameset>
6833: rather than <body>
6834: skip_phases -> hash ref of
6835: head -> skip the <html><head> generation
6836: body -> skip all <body> generation
6837: no_auto_mt_title -> prevent &mt()ing the title arg
6838: inherit_jsmath -> when creating popup window in a page,
6839: should it have jsmath forced on by the
6840: current page
6841: bread_crumbs -> Array containing breadcrumbs
6842: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
6843:
6844: =back
6845:
6846: =back
6847:
6848: =cut
6849:
6850: sub start_page {
6851: my ($title,$head_extra,$args) = @_;
6852: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6853: #SD
6854: #I don't see why we copy certain elements of %$args to %head_args
6855: #head args is passed to headtag() and this routine only reads those
6856: #keys that are needed. There doesn't happen any writes or any processing
6857: #of other keys.
6858: #proposal: just pass $args to headtag instead of \%head_args and delete
6859: #marked lines
6860: #<- MARK
6861: my %head_args;
6862: foreach my $arg ('redirect','force_register','domain','function',
6863: 'bgcolor','frameset','no_nav_bar','only_body',
6864: 'no_auto_mt_title') {
6865: if (defined($args->{$arg})) {
6866: $head_args{$arg} = $args->{$arg};
6867: }
6868: }
6869: #MARK ->
6870:
6871: $env{'internal.start_page'}++;
6872: my $result;
6873:
6874: if (! exists($args->{'skip_phases'}{'head'}) ) {
6875: $result .=
6876: &xml_begin() . &headtag($title,$head_extra,\%head_args);
6877: #replace prev line by
6878: # &xml_begin() . &headtag($title, $head_extra, $args);
6879: }
6880:
6881: if (! exists($args->{'skip_phases'}{'body'}) ) {
6882: if ($args->{'frameset'}) {
6883: my $attr_string = &make_attr_string($args->{'force_register'},
6884: $args->{'add_entries'});
6885: $result .= "\n<frameset $attr_string>\n";
6886: } else {
6887: $result .=
6888: &bodytag($title,
6889: $args->{'function'}, $args->{'add_entries'},
6890: $args->{'only_body'}, $args->{'domain'},
6891: $args->{'force_register'}, $args->{'no_nav_bar'},
6892: $args->{'bgcolor'}, $args);
6893: }
6894: }
6895:
6896: if ($args->{'js_ready'}) {
6897: $result = &js_ready($result);
6898: }
6899: if ($args->{'html_encode'}) {
6900: $result = &html_encode($result);
6901: }
6902:
6903: # Preparation for new and consistent functionlist at top of screen
6904: # if ($args->{'functionlist'}) {
6905: # $result .= &build_functionlist();
6906: #}
6907:
6908: # Don't add anything more if only_body wanted or in const space
6909: return $result if $args->{'only_body'}
6910: || $env{'request.state'} eq 'construct';
6911:
6912: #Breadcrumbs
6913: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
6914: &Apache::lonhtmlcommon::clear_breadcrumbs();
6915: #if any br links exists, add them to the breadcrumbs
6916: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6917: foreach my $crumb (@{$args->{'bread_crumbs'}}){
6918: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
6919: }
6920: }
6921:
6922: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
6923: if(exists($args->{'bread_crumbs_component'})){
6924: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
6925: }else{
6926: $result .= &Apache::lonhtmlcommon::breadcrumbs();
6927: }
6928: }
6929: return $result;
6930: }
6931:
6932: sub end_page {
6933: my ($args) = @_;
6934: $env{'internal.end_page'}++;
6935: my $result;
6936: if ($args->{'discussion'}) {
6937: my ($target,$parser);
6938: if (ref($args->{'discussion'})) {
6939: ($target,$parser) =($args->{'discussion'}{'target'},
6940: $args->{'discussion'}{'parser'});
6941: }
6942: $result .= &Apache::lonxml::xmlend($target,$parser);
6943: }
6944:
6945: if ($args->{'frameset'}) {
6946: $result .= '</frameset>';
6947: } else {
6948: $result .= &endbodytag($args);
6949: }
6950: $result .= "\n</html>";
6951:
6952: if ($args->{'js_ready'}) {
6953: $result = &js_ready($result);
6954: }
6955:
6956: if ($args->{'html_encode'}) {
6957: $result = &html_encode($result);
6958: }
6959:
6960: return $result;
6961: }
6962:
6963: sub html_encode {
6964: my ($result) = @_;
6965:
6966: $result = &HTML::Entities::encode($result,'<>&"');
6967:
6968: return $result;
6969: }
6970: sub js_ready {
6971: my ($result) = @_;
6972:
6973: $result =~ s/[\n\r]/ /xmsg;
6974: $result =~ s/\\/\\\\/xmsg;
6975: $result =~ s/'/\\'/xmsg;
6976: $result =~ s{</}{<\\/}xmsg;
6977:
6978: return $result;
6979: }
6980:
6981: sub validate_page {
6982: if ( exists($env{'internal.start_page'})
6983: && $env{'internal.start_page'} > 1) {
6984: &Apache::lonnet::logthis('start_page called multiple times '.
6985: $env{'internal.start_page'}.' '.
6986: $ENV{'request.filename'});
6987: }
6988: if ( exists($env{'internal.end_page'})
6989: && $env{'internal.end_page'} > 1) {
6990: &Apache::lonnet::logthis('end_page called multiple times '.
6991: $env{'internal.end_page'}.' '.
6992: $env{'request.filename'});
6993: }
6994: if ( exists($env{'internal.start_page'})
6995: && ! exists($env{'internal.end_page'})) {
6996: &Apache::lonnet::logthis('start_page called without end_page '.
6997: $env{'request.filename'});
6998: }
6999: if ( ! exists($env{'internal.start_page'})
7000: && exists($env{'internal.end_page'})) {
7001: &Apache::lonnet::logthis('end_page called without start_page'.
7002: $env{'request.filename'});
7003: }
7004: }
7005:
7006:
7007: sub start_scrollbox {
7008: my ($outerwidth,$width,$height,$id)=@_;
7009: unless ($outerwidth) { $outerwidth='520px'; }
7010: unless ($width) { $width='500px'; }
7011: unless ($height) { $height='200px'; }
7012: my ($table_id,$div_id);
7013: if ($id ne '') {
7014: $table_id = " id='table_$id'";
7015: $div_id = " id='div_$id'";
7016: }
7017: return "<table style='width: $outerwidth; border: 1px solid none;'$table_id><tr><td style='width: $width;' bgcolor='#FFFFFF'><div style='overflow:auto; width:$width; height: $height;'$div_id>";
7018: }
7019:
7020: sub end_scrollbox {
7021: return '</td></tr></table>';
7022: }
7023:
7024: sub simple_error_page {
7025: my ($r,$title,$msg) = @_;
7026: my $page =
7027: &Apache::loncommon::start_page($title).
7028: &mt($msg).
7029: &Apache::loncommon::end_page();
7030: if (ref($r)) {
7031: $r->print($page);
7032: return;
7033: }
7034: return $page;
7035: }
7036:
7037: {
7038: my @row_count;
7039:
7040: sub start_data_table_count {
7041: unshift(@row_count, 0);
7042: return;
7043: }
7044:
7045: sub end_data_table_count {
7046: shift(@row_count);
7047: return;
7048: }
7049:
7050: sub start_data_table {
7051: my ($add_class,$id) = @_;
7052: my $css_class = (join(' ','LC_data_table',$add_class));
7053: my $table_id;
7054: if (defined($id)) {
7055: $table_id = ' id="'.$id.'"';
7056: }
7057: &start_data_table_count();
7058: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
7059: }
7060:
7061: sub end_data_table {
7062: &end_data_table_count();
7063: return '</table>'."\n";;
7064: }
7065:
7066: sub start_data_table_row {
7067: my ($add_class, $id) = @_;
7068: $row_count[0]++;
7069: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7070: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7071: $id = (' id="'.$id.'"') unless ($id eq '');
7072: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7073: }
7074:
7075: sub continue_data_table_row {
7076: my ($add_class, $id) = @_;
7077: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7078: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7079: $id = (' id="'.$id.'"') unless ($id eq '');
7080: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7081: }
7082:
7083: sub end_data_table_row {
7084: return '</tr>'."\n";;
7085: }
7086:
7087: sub start_data_table_empty_row {
7088: # $row_count[0]++;
7089: return '<tr class="LC_empty_row" >'."\n";;
7090: }
7091:
7092: sub end_data_table_empty_row {
7093: return '</tr>'."\n";;
7094: }
7095:
7096: sub start_data_table_header_row {
7097: return '<tr class="LC_header_row">'."\n";;
7098: }
7099:
7100: sub end_data_table_header_row {
7101: return '</tr>'."\n";;
7102: }
7103:
7104: sub data_table_caption {
7105: my $caption = shift;
7106: return "<caption class=\"LC_caption\">$caption</caption>";
7107: }
7108: }
7109:
7110: =pod
7111:
7112: =item * &inhibit_menu_check($arg)
7113:
7114: Checks for a inhibitmenu state and generates output to preserve it
7115:
7116: Inputs: $arg - can be any of
7117: - undef - in which case the return value is a string
7118: to add into arguments list of a uri
7119: - 'input' - in which case the return value is a HTML
7120: <form> <input> field of type hidden to
7121: preserve the value
7122: - a url - in which case the return value is the url with
7123: the neccesary cgi args added to preserve the
7124: inhibitmenu state
7125: - a ref to a url - no return value, but the string is
7126: updated to include the neccessary cgi
7127: args to preserve the inhibitmenu state
7128:
7129: =cut
7130:
7131: sub inhibit_menu_check {
7132: my ($arg) = @_;
7133: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
7134: if ($arg eq 'input') {
7135: if ($env{'form.inhibitmenu'}) {
7136: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
7137: } else {
7138: return
7139: }
7140: }
7141: if ($env{'form.inhibitmenu'}) {
7142: if (ref($arg)) {
7143: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7144: } elsif ($arg eq '') {
7145: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
7146: } else {
7147: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7148: }
7149: }
7150: if (!ref($arg)) {
7151: return $arg;
7152: }
7153: }
7154:
7155: ###############################################
7156:
7157: =pod
7158:
7159: =back
7160:
7161: =head1 User Information Routines
7162:
7163: =over 4
7164:
7165: =item * &get_users_function()
7166:
7167: Used by &bodytag to determine the current users primary role.
7168: Returns either 'student','coordinator','admin', or 'author'.
7169:
7170: =cut
7171:
7172: ###############################################
7173: sub get_users_function {
7174: my $function = 'norole';
7175: if ($env{'request.role'}=~/^(st)/) {
7176: $function='student';
7177: }
7178: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
7179: $function='coordinator';
7180: }
7181: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
7182: $function='admin';
7183: }
7184: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
7185: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
7186: $function='author';
7187: }
7188: return $function;
7189: }
7190:
7191: ###############################################
7192:
7193: =pod
7194:
7195: =item * &show_course()
7196:
7197: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
7198: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
7199:
7200: Inputs:
7201: None
7202:
7203: Outputs:
7204: Scalar: 1 if 'Course' to be used, 0 otherwise.
7205:
7206: =cut
7207:
7208: ###############################################
7209: sub show_course {
7210: my $course = !$env{'user.adv'};
7211: if (!$env{'user.adv'}) {
7212: foreach my $env (keys(%env)) {
7213: next if ($env !~ m/^user\.priv\./);
7214: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
7215: $course = 0;
7216: last;
7217: }
7218: }
7219: }
7220: return $course;
7221: }
7222:
7223: ###############################################
7224:
7225: =pod
7226:
7227: =item * &check_user_status()
7228:
7229: Determines current status of supplied role for a
7230: specific user. Roles can be active, previous or future.
7231:
7232: Inputs:
7233: user's domain, user's username, course's domain,
7234: course's number, optional section ID.
7235:
7236: Outputs:
7237: role status: active, previous or future.
7238:
7239: =cut
7240:
7241: sub check_user_status {
7242: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
7243: my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
7244: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
7245: my @uroles = keys %userinfo;
7246: my $srchstr;
7247: my $active_chk = 'none';
7248: my $now = time;
7249: if (@uroles > 0) {
7250: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
7251: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
7252: } else {
7253: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
7254: }
7255: if (grep/^\Q$srchstr\E$/,@uroles) {
7256: my $role_end = 0;
7257: my $role_start = 0;
7258: $active_chk = 'active';
7259: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
7260: $role_end = $1;
7261: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
7262: $role_start = $1;
7263: }
7264: }
7265: if ($role_start > 0) {
7266: if ($now < $role_start) {
7267: $active_chk = 'future';
7268: }
7269: }
7270: if ($role_end > 0) {
7271: if ($now > $role_end) {
7272: $active_chk = 'previous';
7273: }
7274: }
7275: }
7276: }
7277: return $active_chk;
7278: }
7279:
7280: ###############################################
7281:
7282: =pod
7283:
7284: =item * &get_sections()
7285:
7286: Determines all the sections for a course including
7287: sections with students and sections containing other roles.
7288: Incoming parameters:
7289:
7290: 1. domain
7291: 2. course number
7292: 3. reference to array containing roles for which sections should
7293: be gathered (optional).
7294: 4. reference to array containing status types for which sections
7295: should be gathered (optional).
7296:
7297: If the third argument is undefined, sections are gathered for any role.
7298: If the fourth argument is undefined, sections are gathered for any status.
7299: Permissible values are 'active' or 'future' or 'previous'.
7300:
7301: Returns section hash (keys are section IDs, values are
7302: number of users in each section), subject to the
7303: optional roles filter, optional status filter
7304:
7305: =cut
7306:
7307: ###############################################
7308: sub get_sections {
7309: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
7310: if (!defined($cdom) || !defined($cnum)) {
7311: my $cid = $env{'request.course.id'};
7312:
7313: return if (!defined($cid));
7314:
7315: $cdom = $env{'course.'.$cid.'.domain'};
7316: $cnum = $env{'course.'.$cid.'.num'};
7317: }
7318:
7319: my %sectioncount;
7320: my $now = time;
7321:
7322: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
7323: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
7324: my $sec_index = &Apache::loncoursedata::CL_SECTION();
7325: my $status_index = &Apache::loncoursedata::CL_STATUS();
7326: my $start_index = &Apache::loncoursedata::CL_START();
7327: my $end_index = &Apache::loncoursedata::CL_END();
7328: my $status;
7329: while (my ($student,$data) = each(%$classlist)) {
7330: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
7331: $data->[$status_index],
7332: $data->[$start_index],
7333: $data->[$end_index]);
7334: if ($stu_status eq 'Active') {
7335: $status = 'active';
7336: } elsif ($end < $now) {
7337: $status = 'previous';
7338: } elsif ($start > $now) {
7339: $status = 'future';
7340: }
7341: if ($section ne '-1' && $section !~ /^\s*$/) {
7342: if ((!defined($possible_status)) || (($status ne '') &&
7343: (grep/^\Q$status\E$/,@{$possible_status}))) {
7344: $sectioncount{$section}++;
7345: }
7346: }
7347: }
7348: }
7349: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7350: foreach my $user (sort(keys(%courseroles))) {
7351: if ($user !~ /^(\w{2})/) { next; }
7352: my ($role) = ($user =~ /^(\w{2})/);
7353: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
7354: my ($section,$status);
7355: if ($role eq 'cr' &&
7356: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
7357: $section=$1;
7358: }
7359: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
7360: if (!defined($section) || $section eq '-1') { next; }
7361: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
7362: if ($end == -1 && $start == -1) {
7363: next; #deleted role
7364: }
7365: if (!defined($possible_status)) {
7366: $sectioncount{$section}++;
7367: } else {
7368: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
7369: $status = 'active';
7370: } elsif ($end < $now) {
7371: $status = 'future';
7372: } elsif ($start > $now) {
7373: $status = 'previous';
7374: }
7375: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
7376: $sectioncount{$section}++;
7377: }
7378: }
7379: }
7380: return %sectioncount;
7381: }
7382:
7383: ###############################################
7384:
7385: =pod
7386:
7387: =item * &get_course_users()
7388:
7389: Retrieves usernames:domains for users in the specified course
7390: with specific role(s), and access status.
7391:
7392: Incoming parameters:
7393: 1. course domain
7394: 2. course number
7395: 3. access status: users must have - either active,
7396: previous, future, or all.
7397: 4. reference to array of permissible roles
7398: 5. reference to array of section restrictions (optional)
7399: 6. reference to results object (hash of hashes).
7400: 7. reference to optional userdata hash
7401: 8. reference to optional statushash
7402: 9. flag if privileged users (except those set to unhide in
7403: course settings) should be excluded
7404: Keys of top level results hash are roles.
7405: Keys of inner hashes are username:domain, with
7406: values set to access type.
7407: Optional userdata hash returns an array with arguments in the
7408: same order as loncoursedata::get_classlist() for student data.
7409:
7410: Optional statushash returns
7411:
7412: Entries for end, start, section and status are blank because
7413: of the possibility of multiple values for non-student roles.
7414:
7415: =cut
7416:
7417: ###############################################
7418:
7419: sub get_course_users {
7420: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
7421: my %idx = ();
7422: my %seclists;
7423:
7424: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
7425: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
7426: $idx{end} = &Apache::loncoursedata::CL_END();
7427: $idx{start} = &Apache::loncoursedata::CL_START();
7428: $idx{id} = &Apache::loncoursedata::CL_ID();
7429: $idx{section} = &Apache::loncoursedata::CL_SECTION();
7430: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
7431: $idx{status} = &Apache::loncoursedata::CL_STATUS();
7432:
7433: if (grep(/^st$/,@{$roles})) {
7434: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
7435: my $now = time;
7436: foreach my $student (keys(%{$classlist})) {
7437: my $match = 0;
7438: my $secmatch = 0;
7439: my $section = $$classlist{$student}[$idx{section}];
7440: my $status = $$classlist{$student}[$idx{status}];
7441: if ($section eq '') {
7442: $section = 'none';
7443: }
7444: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7445: if (grep(/^all$/,@{$sections})) {
7446: $secmatch = 1;
7447: } elsif ($$classlist{$student}[$idx{section}] eq '') {
7448: if (grep(/^none$/,@{$sections})) {
7449: $secmatch = 1;
7450: }
7451: } else {
7452: if (grep(/^\Q$section\E$/,@{$sections})) {
7453: $secmatch = 1;
7454: }
7455: }
7456: if (!$secmatch) {
7457: next;
7458: }
7459: }
7460: if (defined($$types{'active'})) {
7461: if ($$classlist{$student}[$idx{status}] eq 'Active') {
7462: push(@{$$users{st}{$student}},'active');
7463: $match = 1;
7464: }
7465: }
7466: if (defined($$types{'previous'})) {
7467: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
7468: push(@{$$users{st}{$student}},'previous');
7469: $match = 1;
7470: }
7471: }
7472: if (defined($$types{'future'})) {
7473: if ($$classlist{$student}[$idx{status}] eq 'Future') {
7474: push(@{$$users{st}{$student}},'future');
7475: $match = 1;
7476: }
7477: }
7478: if ($match) {
7479: push(@{$seclists{$student}},$section);
7480: if (ref($userdata) eq 'HASH') {
7481: $$userdata{$student} = $$classlist{$student};
7482: }
7483: if (ref($statushash) eq 'HASH') {
7484: $statushash->{$student}{'st'}{$section} = $status;
7485: }
7486: }
7487: }
7488: }
7489: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
7490: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7491: my $now = time;
7492: my %displaystatus = ( previous => 'Expired',
7493: active => 'Active',
7494: future => 'Future',
7495: );
7496: my %nothide;
7497: if ($hidepriv) {
7498: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
7499: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
7500: if ($user !~ /:/) {
7501: $nothide{join(':',split(/[\@]/,$user))}=1;
7502: } else {
7503: $nothide{$user} = 1;
7504: }
7505: }
7506: }
7507: foreach my $person (sort(keys(%coursepersonnel))) {
7508: my $match = 0;
7509: my $secmatch = 0;
7510: my $status;
7511: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
7512: $user =~ s/:$//;
7513: my ($end,$start) = split(/:/,$coursepersonnel{$person});
7514: if ($end == -1 || $start == -1) {
7515: next;
7516: }
7517: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
7518: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
7519: my ($uname,$udom) = split(/:/,$user);
7520: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7521: if (grep(/^all$/,@{$sections})) {
7522: $secmatch = 1;
7523: } elsif ($usec eq '') {
7524: if (grep(/^none$/,@{$sections})) {
7525: $secmatch = 1;
7526: }
7527: } else {
7528: if (grep(/^\Q$usec\E$/,@{$sections})) {
7529: $secmatch = 1;
7530: }
7531: }
7532: if (!$secmatch) {
7533: next;
7534: }
7535: }
7536: if ($usec eq '') {
7537: $usec = 'none';
7538: }
7539: if ($uname ne '' && $udom ne '') {
7540: if ($hidepriv) {
7541: if ((&Apache::lonnet::privileged($uname,$udom)) &&
7542: (!$nothide{$uname.':'.$udom})) {
7543: next;
7544: }
7545: }
7546: if ($end > 0 && $end < $now) {
7547: $status = 'previous';
7548: } elsif ($start > $now) {
7549: $status = 'future';
7550: } else {
7551: $status = 'active';
7552: }
7553: foreach my $type (keys(%{$types})) {
7554: if ($status eq $type) {
7555: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
7556: push(@{$$users{$role}{$user}},$type);
7557: }
7558: $match = 1;
7559: }
7560: }
7561: if (($match) && (ref($userdata) eq 'HASH')) {
7562: if (!exists($$userdata{$uname.':'.$udom})) {
7563: &get_user_info($udom,$uname,\%idx,$userdata);
7564: }
7565: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
7566: push(@{$seclists{$uname.':'.$udom}},$usec);
7567: }
7568: if (ref($statushash) eq 'HASH') {
7569: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
7570: }
7571: }
7572: }
7573: }
7574: }
7575: if (grep(/^ow$/,@{$roles})) {
7576: if ((defined($cdom)) && (defined($cnum))) {
7577: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
7578: if ( defined($csettings{'internal.courseowner'}) ) {
7579: my $owner = $csettings{'internal.courseowner'};
7580: next if ($owner eq '');
7581: my ($ownername,$ownerdom);
7582: if ($owner =~ /^([^:]+):([^:]+)$/) {
7583: $ownername = $1;
7584: $ownerdom = $2;
7585: } else {
7586: $ownername = $owner;
7587: $ownerdom = $cdom;
7588: $owner = $ownername.':'.$ownerdom;
7589: }
7590: @{$$users{'ow'}{$owner}} = 'any';
7591: if (defined($userdata) &&
7592: !exists($$userdata{$owner})) {
7593: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
7594: if (!grep(/^none$/,@{$seclists{$owner}})) {
7595: push(@{$seclists{$owner}},'none');
7596: }
7597: if (ref($statushash) eq 'HASH') {
7598: $statushash->{$owner}{'ow'}{'none'} = 'Any';
7599: }
7600: }
7601: }
7602: }
7603: }
7604: foreach my $user (keys(%seclists)) {
7605: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
7606: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
7607: }
7608: }
7609: return;
7610: }
7611:
7612: sub get_user_info {
7613: my ($udom,$uname,$idx,$userdata) = @_;
7614: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
7615: &plainname($uname,$udom,'lastname');
7616: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
7617: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
7618: my %idhash = &Apache::lonnet::idrget($udom,($uname));
7619: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
7620: return;
7621: }
7622:
7623: ###############################################
7624:
7625: =pod
7626:
7627: =item * &get_user_quota()
7628:
7629: Retrieves quota assigned for storage of portfolio files for a user
7630:
7631: Incoming parameters:
7632: 1. user's username
7633: 2. user's domain
7634:
7635: Returns:
7636: 1. Disk quota (in Mb) assigned to student.
7637: 2. (Optional) Type of setting: custom or default
7638: (individually assigned or default for user's
7639: institutional status).
7640: 3. (Optional) - User's institutional status (e.g., faculty, staff
7641: or student - types as defined in localenroll::inst_usertypes
7642: for user's domain, which determines default quota for user.
7643: 4. (Optional) - Default quota which would apply to the user.
7644:
7645: If a value has been stored in the user's environment,
7646: it will return that, otherwise it returns the maximal default
7647: defined for the user's instituional status(es) in the domain.
7648:
7649: =cut
7650:
7651: ###############################################
7652:
7653:
7654: sub get_user_quota {
7655: my ($uname,$udom) = @_;
7656: my ($quota,$quotatype,$settingstatus,$defquota);
7657: if (!defined($udom)) {
7658: $udom = $env{'user.domain'};
7659: }
7660: if (!defined($uname)) {
7661: $uname = $env{'user.name'};
7662: }
7663: if (($udom eq '' || $uname eq '') ||
7664: ($udom eq 'public') && ($uname eq 'public')) {
7665: $quota = 0;
7666: $quotatype = 'default';
7667: $defquota = 0;
7668: } else {
7669: my $inststatus;
7670: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
7671: $quota = $env{'environment.portfolioquota'};
7672: $inststatus = $env{'environment.inststatus'};
7673: } else {
7674: my %userenv =
7675: &Apache::lonnet::get('environment',['portfolioquota',
7676: 'inststatus'],$udom,$uname);
7677: my ($tmp) = keys(%userenv);
7678: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7679: $quota = $userenv{'portfolioquota'};
7680: $inststatus = $userenv{'inststatus'};
7681: } else {
7682: undef(%userenv);
7683: }
7684: }
7685: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
7686: if ($quota eq '') {
7687: $quota = $defquota;
7688: $quotatype = 'default';
7689: } else {
7690: $quotatype = 'custom';
7691: }
7692: }
7693: if (wantarray) {
7694: return ($quota,$quotatype,$settingstatus,$defquota);
7695: } else {
7696: return $quota;
7697: }
7698: }
7699:
7700: ###############################################
7701:
7702: =pod
7703:
7704: =item * &default_quota()
7705:
7706: Retrieves default quota assigned for storage of user portfolio files,
7707: given an (optional) user's institutional status.
7708:
7709: Incoming parameters:
7710: 1. domain
7711: 2. (Optional) institutional status(es). This is a : separated list of
7712: status types (e.g., faculty, staff, student etc.)
7713: which apply to the user for whom the default is being retrieved.
7714: If the institutional status string in undefined, the domain
7715: default quota will be returned.
7716:
7717: Returns:
7718: 1. Default disk quota (in Mb) for user portfolios in the domain.
7719: 2. (Optional) institutional type which determined the value of the
7720: default quota.
7721:
7722: If a value has been stored in the domain's configuration db,
7723: it will return that, otherwise it returns 20 (for backwards
7724: compatibility with domains which have not set up a configuration
7725: db file; the original statically defined portfolio quota was 20 Mb).
7726:
7727: If the user's status includes multiple types (e.g., staff and student),
7728: the largest default quota which applies to the user determines the
7729: default quota returned.
7730:
7731: =back
7732:
7733: =cut
7734:
7735: ###############################################
7736:
7737:
7738: sub default_quota {
7739: my ($udom,$inststatus) = @_;
7740: my ($defquota,$settingstatus);
7741: my %quotahash = &Apache::lonnet::get_dom('configuration',
7742: ['quotas'],$udom);
7743: if (ref($quotahash{'quotas'}) eq 'HASH') {
7744: if ($inststatus ne '') {
7745: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
7746: foreach my $item (@statuses) {
7747: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7748: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
7749: if ($defquota eq '') {
7750: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7751: $settingstatus = $item;
7752: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
7753: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
7754: $settingstatus = $item;
7755: }
7756: }
7757: } else {
7758: if ($quotahash{'quotas'}{$item} ne '') {
7759: if ($defquota eq '') {
7760: $defquota = $quotahash{'quotas'}{$item};
7761: $settingstatus = $item;
7762: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
7763: $defquota = $quotahash{'quotas'}{$item};
7764: $settingstatus = $item;
7765: }
7766: }
7767: }
7768: }
7769: }
7770: if ($defquota eq '') {
7771: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
7772: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
7773: } else {
7774: $defquota = $quotahash{'quotas'}{'default'};
7775: }
7776: $settingstatus = 'default';
7777: }
7778: } else {
7779: $settingstatus = 'default';
7780: $defquota = 20;
7781: }
7782: if (wantarray) {
7783: return ($defquota,$settingstatus);
7784: } else {
7785: return $defquota;
7786: }
7787: }
7788:
7789: sub get_secgrprole_info {
7790: my ($cdom,$cnum,$needroles,$type) = @_;
7791: my %sections_count = &get_sections($cdom,$cnum);
7792: my @sections = (sort {$a <=> $b} keys(%sections_count));
7793: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
7794: my @groups = sort(keys(%curr_groups));
7795: my $allroles = [];
7796: my $rolehash;
7797: my $accesshash = {
7798: active => 'Currently has access',
7799: future => 'Will have future access',
7800: previous => 'Previously had access',
7801: };
7802: if ($needroles) {
7803: $rolehash = {'all' => 'all'};
7804: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7805: if (&Apache::lonnet::error(%user_roles)) {
7806: undef(%user_roles);
7807: }
7808: foreach my $item (keys(%user_roles)) {
7809: my ($role)=split(/\:/,$item,2);
7810: if ($role eq 'cr') { next; }
7811: if ($role =~ /^cr/) {
7812: $$rolehash{$role} = (split('/',$role))[3];
7813: } else {
7814: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
7815: }
7816: }
7817: foreach my $key (sort(keys(%{$rolehash}))) {
7818: push(@{$allroles},$key);
7819: }
7820: push (@{$allroles},'st');
7821: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
7822: }
7823: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
7824: }
7825:
7826: sub user_picker {
7827: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
7828: my $currdom = $dom;
7829: my %curr_selected = (
7830: srchin => 'dom',
7831: srchby => 'lastname',
7832: );
7833: my $srchterm;
7834: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
7835: if ($srch->{'srchby'} ne '') {
7836: $curr_selected{'srchby'} = $srch->{'srchby'};
7837: }
7838: if ($srch->{'srchin'} ne '') {
7839: $curr_selected{'srchin'} = $srch->{'srchin'};
7840: }
7841: if ($srch->{'srchtype'} ne '') {
7842: $curr_selected{'srchtype'} = $srch->{'srchtype'};
7843: }
7844: if ($srch->{'srchdomain'} ne '') {
7845: $currdom = $srch->{'srchdomain'};
7846: }
7847: $srchterm = $srch->{'srchterm'};
7848: }
7849: my %lt=&Apache::lonlocal::texthash(
7850: 'usr' => 'Search criteria',
7851: 'doma' => 'Domain/institution to search',
7852: 'uname' => 'username',
7853: 'lastname' => 'last name',
7854: 'lastfirst' => 'last name, first name',
7855: 'crs' => 'in this course',
7856: 'dom' => 'in selected LON-CAPA domain',
7857: 'alc' => 'all LON-CAPA',
7858: 'instd' => 'in institutional directory for selected domain',
7859: 'exact' => 'is',
7860: 'contains' => 'contains',
7861: 'begins' => 'begins with',
7862: 'youm' => "You must include some text to search for.",
7863: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
7864: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
7865: 'yomc' => "You must choose a domain when using an institutional directory search.",
7866: 'ymcd' => "You must choose a domain when using a domain search.",
7867: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
7868: 'whse' => "When searching by last,first you must include at least one character in the first name.",
7869: 'thfo' => "The following need to be corrected before the search can be run:",
7870: );
7871: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
7872: my $srchinsel = ' <select name="srchin">';
7873:
7874: my @srchins = ('crs','dom','alc','instd');
7875:
7876: foreach my $option (@srchins) {
7877: # FIXME 'alc' option unavailable until
7878: # loncreateuser::print_user_query_page()
7879: # has been completed.
7880: next if ($option eq 'alc');
7881: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
7882: next if ($option eq 'crs' && !$env{'request.course.id'});
7883: if ($curr_selected{'srchin'} eq $option) {
7884: $srchinsel .= '
7885: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7886: } else {
7887: $srchinsel .= '
7888: <option value="'.$option.'">'.$lt{$option}.'</option>';
7889: }
7890: }
7891: $srchinsel .= "\n </select>\n";
7892:
7893: my $srchbysel = ' <select name="srchby">';
7894: foreach my $option ('lastname','lastfirst','uname') {
7895: if ($curr_selected{'srchby'} eq $option) {
7896: $srchbysel .= '
7897: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7898: } else {
7899: $srchbysel .= '
7900: <option value="'.$option.'">'.$lt{$option}.'</option>';
7901: }
7902: }
7903: $srchbysel .= "\n </select>\n";
7904:
7905: my $srchtypesel = ' <select name="srchtype">';
7906: foreach my $option ('begins','contains','exact') {
7907: if ($curr_selected{'srchtype'} eq $option) {
7908: $srchtypesel .= '
7909: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7910: } else {
7911: $srchtypesel .= '
7912: <option value="'.$option.'">'.$lt{$option}.'</option>';
7913: }
7914: }
7915: $srchtypesel .= "\n </select>\n";
7916:
7917: my ($newuserscript,$new_user_create);
7918: my $context_dom = $env{'request.role.domain'};
7919: if ($context eq 'requestcrs') {
7920: if ($env{'form.coursedom'} ne '') {
7921: $context_dom = $env{'form.coursedom'};
7922: }
7923: }
7924: if ($forcenewuser) {
7925: if (ref($srch) eq 'HASH') {
7926: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
7927: if ($cancreate) {
7928: $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>';
7929: } else {
7930: my $helplink = 'javascript:helpMenu('."'display'".')';
7931: my %usertypetext = (
7932: official => 'institutional',
7933: unofficial => 'non-institutional',
7934: );
7935: $new_user_create = '<p class="LC_warning">'
7936: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
7937: .' '
7938: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
7939: ,'<a href="'.$helplink.'">','</a>')
7940: .'</p><br />';
7941: }
7942: }
7943: }
7944:
7945: $newuserscript = <<"ENDSCRIPT";
7946:
7947: function setSearch(createnew,callingForm) {
7948: if (createnew == 1) {
7949: for (var i=0; i<callingForm.srchby.length; i++) {
7950: if (callingForm.srchby.options[i].value == 'uname') {
7951: callingForm.srchby.selectedIndex = i;
7952: }
7953: }
7954: for (var i=0; i<callingForm.srchin.length; i++) {
7955: if ( callingForm.srchin.options[i].value == 'dom') {
7956: callingForm.srchin.selectedIndex = i;
7957: }
7958: }
7959: for (var i=0; i<callingForm.srchtype.length; i++) {
7960: if (callingForm.srchtype.options[i].value == 'exact') {
7961: callingForm.srchtype.selectedIndex = i;
7962: }
7963: }
7964: for (var i=0; i<callingForm.srchdomain.length; i++) {
7965: if (callingForm.srchdomain.options[i].value == '$context_dom') {
7966: callingForm.srchdomain.selectedIndex = i;
7967: }
7968: }
7969: }
7970: }
7971: ENDSCRIPT
7972:
7973: }
7974:
7975: my $output = <<"END_BLOCK";
7976: <script type="text/javascript">
7977: // <![CDATA[
7978: function validateEntry(callingForm) {
7979:
7980: var checkok = 1;
7981: var srchin;
7982: for (var i=0; i<callingForm.srchin.length; i++) {
7983: if ( callingForm.srchin[i].checked ) {
7984: srchin = callingForm.srchin[i].value;
7985: }
7986: }
7987:
7988: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7989: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7990: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7991: var srchterm = callingForm.srchterm.value;
7992: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7993: var msg = "";
7994:
7995: if (srchterm == "") {
7996: checkok = 0;
7997: msg += "$lt{'youm'}\\n";
7998: }
7999:
8000: if (srchtype== 'begins') {
8001: if (srchterm.length < 2) {
8002: checkok = 0;
8003: msg += "$lt{'thte'}\\n";
8004: }
8005: }
8006:
8007: if (srchtype== 'contains') {
8008: if (srchterm.length < 3) {
8009: checkok = 0;
8010: msg += "$lt{'thet'}\\n";
8011: }
8012: }
8013: if (srchin == 'instd') {
8014: if (srchdomain == '') {
8015: checkok = 0;
8016: msg += "$lt{'yomc'}\\n";
8017: }
8018: }
8019: if (srchin == 'dom') {
8020: if (srchdomain == '') {
8021: checkok = 0;
8022: msg += "$lt{'ymcd'}\\n";
8023: }
8024: }
8025: if (srchby == 'lastfirst') {
8026: if (srchterm.indexOf(",") == -1) {
8027: checkok = 0;
8028: msg += "$lt{'whus'}\\n";
8029: }
8030: if (srchterm.indexOf(",") == srchterm.length -1) {
8031: checkok = 0;
8032: msg += "$lt{'whse'}\\n";
8033: }
8034: }
8035: if (checkok == 0) {
8036: alert("$lt{'thfo'}\\n"+msg);
8037: return;
8038: }
8039: if (checkok == 1) {
8040: callingForm.submit();
8041: }
8042: }
8043:
8044: $newuserscript
8045:
8046: // ]]>
8047: </script>
8048:
8049: $new_user_create
8050:
8051: END_BLOCK
8052:
8053: $output .= &Apache::lonhtmlcommon::start_pick_box().
8054: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8055: $domform.
8056: &Apache::lonhtmlcommon::row_closure().
8057: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8058: $srchbysel.
8059: $srchtypesel.
8060: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8061: $srchinsel.
8062: &Apache::lonhtmlcommon::row_closure(1).
8063: &Apache::lonhtmlcommon::end_pick_box().
8064: '<br />';
8065: return $output;
8066: }
8067:
8068: sub user_rule_check {
8069: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
8070: my $response;
8071: if (ref($usershash) eq 'HASH') {
8072: foreach my $user (keys(%{$usershash})) {
8073: my ($uname,$udom) = split(/:/,$user);
8074: next if ($udom eq '' || $uname eq '');
8075: my ($id,$newuser);
8076: if (ref($usershash->{$user}) eq 'HASH') {
8077: $newuser = $usershash->{$user}->{'newuser'};
8078: $id = $usershash->{$user}->{'id'};
8079: }
8080: my $inst_response;
8081: if (ref($checks) eq 'HASH') {
8082: if (defined($checks->{'username'})) {
8083: ($inst_response,%{$inst_results->{$user}}) =
8084: &Apache::lonnet::get_instuser($udom,$uname);
8085: } elsif (defined($checks->{'id'})) {
8086: ($inst_response,%{$inst_results->{$user}}) =
8087: &Apache::lonnet::get_instuser($udom,undef,$id);
8088: }
8089: } else {
8090: ($inst_response,%{$inst_results->{$user}}) =
8091: &Apache::lonnet::get_instuser($udom,$uname);
8092: return;
8093: }
8094: if (!$got_rules->{$udom}) {
8095: my %domconfig = &Apache::lonnet::get_dom('configuration',
8096: ['usercreation'],$udom);
8097: if (ref($domconfig{'usercreation'}) eq 'HASH') {
8098: foreach my $item ('username','id') {
8099: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
8100: $$curr_rules{$udom}{$item} =
8101: $domconfig{'usercreation'}{$item.'_rule'};
8102: }
8103: }
8104: }
8105: $got_rules->{$udom} = 1;
8106: }
8107: foreach my $item (keys(%{$checks})) {
8108: if (ref($$curr_rules{$udom}) eq 'HASH') {
8109: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
8110: if (@{$$curr_rules{$udom}{$item}} > 0) {
8111: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
8112: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
8113: if ($rule_check{$rule}) {
8114: $$rulematch{$user}{$item} = $rule;
8115: if ($inst_response eq 'ok') {
8116: if (ref($inst_results) eq 'HASH') {
8117: if (ref($inst_results->{$user}) eq 'HASH') {
8118: if (keys(%{$inst_results->{$user}}) == 0) {
8119: $$alerts{$item}{$udom}{$uname} = 1;
8120: }
8121: }
8122: }
8123: }
8124: last;
8125: }
8126: }
8127: }
8128: }
8129: }
8130: }
8131: }
8132: }
8133: return;
8134: }
8135:
8136: sub user_rule_formats {
8137: my ($domain,$domdesc,$curr_rules,$check) = @_;
8138: my %text = (
8139: 'username' => 'Usernames',
8140: 'id' => 'IDs',
8141: );
8142: my $output;
8143: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
8144: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
8145: if (@{$ruleorder} > 0) {
8146: $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>';
8147: foreach my $rule (@{$ruleorder}) {
8148: if (ref($curr_rules) eq 'ARRAY') {
8149: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
8150: if (ref($rules->{$rule}) eq 'HASH') {
8151: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
8152: $rules->{$rule}{'desc'}.'</li>';
8153: }
8154: }
8155: }
8156: }
8157: $output .= '</ul>';
8158: }
8159: }
8160: return $output;
8161: }
8162:
8163: sub instrule_disallow_msg {
8164: my ($checkitem,$domdesc,$count,$mode) = @_;
8165: my $response;
8166: my %text = (
8167: item => 'username',
8168: items => 'usernames',
8169: match => 'matches',
8170: do => 'does',
8171: action => 'a username',
8172: one => 'one',
8173: );
8174: if ($count > 1) {
8175: $text{'item'} = 'usernames';
8176: $text{'match'} ='match';
8177: $text{'do'} = 'do';
8178: $text{'action'} = 'usernames',
8179: $text{'one'} = 'ones';
8180: }
8181: if ($checkitem eq 'id') {
8182: $text{'items'} = 'IDs';
8183: $text{'item'} = 'ID';
8184: $text{'action'} = 'an ID';
8185: if ($count > 1) {
8186: $text{'item'} = 'IDs';
8187: $text{'action'} = 'IDs';
8188: }
8189: }
8190: $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 />';
8191: if ($mode eq 'upload') {
8192: if ($checkitem eq 'username') {
8193: $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'}.");
8194: } elsif ($checkitem eq 'id') {
8195: $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.");
8196: }
8197: } elsif ($mode eq 'selfcreate') {
8198: if ($checkitem eq 'id') {
8199: $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.");
8200: }
8201: } else {
8202: if ($checkitem eq 'username') {
8203: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
8204: } elsif ($checkitem eq 'id') {
8205: $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.");
8206: }
8207: }
8208: return $response;
8209: }
8210:
8211: sub personal_data_fieldtitles {
8212: my %fieldtitles = &Apache::lonlocal::texthash (
8213: id => 'Student/Employee ID',
8214: permanentemail => 'E-mail address',
8215: lastname => 'Last Name',
8216: firstname => 'First Name',
8217: middlename => 'Middle Name',
8218: generation => 'Generation',
8219: gen => 'Generation',
8220: inststatus => 'Affiliation',
8221: );
8222: return %fieldtitles;
8223: }
8224:
8225: sub sorted_inst_types {
8226: my ($dom) = @_;
8227: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
8228: my $othertitle = &mt('All users');
8229: if ($env{'request.course.id'}) {
8230: $othertitle = &mt('Any users');
8231: }
8232: my @types;
8233: if (ref($order) eq 'ARRAY') {
8234: @types = @{$order};
8235: }
8236: if (@types == 0) {
8237: if (ref($usertypes) eq 'HASH') {
8238: @types = sort(keys(%{$usertypes}));
8239: }
8240: }
8241: if (keys(%{$usertypes}) > 0) {
8242: $othertitle = &mt('Other users');
8243: }
8244: return ($othertitle,$usertypes,\@types);
8245: }
8246:
8247: sub get_institutional_codes {
8248: my ($settings,$allcourses,$LC_code) = @_;
8249: # Get complete list of course sections to update
8250: my @currsections = ();
8251: my @currxlists = ();
8252: my $coursecode = $$settings{'internal.coursecode'};
8253:
8254: if ($$settings{'internal.sectionnums'} ne '') {
8255: @currsections = split(/,/,$$settings{'internal.sectionnums'});
8256: }
8257:
8258: if ($$settings{'internal.crosslistings'} ne '') {
8259: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
8260: }
8261:
8262: if (@currxlists > 0) {
8263: foreach (@currxlists) {
8264: if (m/^([^:]+):(\w*)$/) {
8265: unless (grep/^$1$/,@{$allcourses}) {
8266: push @{$allcourses},$1;
8267: $$LC_code{$1} = $2;
8268: }
8269: }
8270: }
8271: }
8272:
8273: if (@currsections > 0) {
8274: foreach (@currsections) {
8275: if (m/^(\w+):(\w*)$/) {
8276: my $sec = $coursecode.$1;
8277: my $lc_sec = $2;
8278: unless (grep/^$sec$/,@{$allcourses}) {
8279: push @{$allcourses},$sec;
8280: $$LC_code{$sec} = $lc_sec;
8281: }
8282: }
8283: }
8284: }
8285: return;
8286: }
8287:
8288: sub get_standard_codeitems {
8289: return ('Year','Semester','Department','Number','Section');
8290: }
8291:
8292: =pod
8293:
8294: =head1 Slot Helpers
8295:
8296: =over 4
8297:
8298: =item * sorted_slots()
8299:
8300: Sorts an array of slot names in order of slot start time (earliest first).
8301:
8302: Inputs:
8303:
8304: =over 4
8305:
8306: slotsarr - Reference to array of unsorted slot names.
8307:
8308: slots - Reference to hash of hash, where outer hash keys are slot names.
8309:
8310: =back
8311:
8312: Returns:
8313:
8314: =over 4
8315:
8316: sorted - An array of slot names sorted by the start time of the slot.
8317:
8318: =back
8319:
8320: =back
8321:
8322: =cut
8323:
8324:
8325: sub sorted_slots {
8326: my ($slotsarr,$slots) = @_;
8327: my @sorted;
8328: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
8329: @sorted =
8330: sort {
8331: if (ref($slots->{$a}) && ref($slots->{$b})) {
8332: return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
8333: }
8334: if (ref($slots->{$a})) { return -1;}
8335: if (ref($slots->{$b})) { return 1;}
8336: return 0;
8337: } @{$slotsarr};
8338: }
8339: return @sorted;
8340: }
8341:
8342:
8343: =pod
8344:
8345: =head1 HTTP Helpers
8346:
8347: =over 4
8348:
8349: =item * &get_unprocessed_cgi($query,$possible_names)
8350:
8351: Modify the %env hash to contain unprocessed CGI form parameters held in
8352: $query. The parameters listed in $possible_names (an array reference),
8353: will be set in $env{'form.name'} if they do not already exist.
8354:
8355: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
8356: $possible_names is an ref to an array of form element names. As an example:
8357: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
8358: will result in $env{'form.uname'} and $env{'form.udom'} being set.
8359:
8360: =cut
8361:
8362: sub get_unprocessed_cgi {
8363: my ($query,$possible_names)= @_;
8364: # $Apache::lonxml::debug=1;
8365: foreach my $pair (split(/&/,$query)) {
8366: my ($name, $value) = split(/=/,$pair);
8367: $name = &unescape($name);
8368: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
8369: $value =~ tr/+/ /;
8370: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
8371: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
8372: }
8373: }
8374: }
8375:
8376: =pod
8377:
8378: =item * &cacheheader()
8379:
8380: returns cache-controlling header code
8381:
8382: =cut
8383:
8384: sub cacheheader {
8385: unless ($env{'request.method'} eq 'GET') { return ''; }
8386: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
8387: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
8388: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
8389: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
8390: return $output;
8391: }
8392:
8393: =pod
8394:
8395: =item * &no_cache($r)
8396:
8397: specifies header code to not have cache
8398:
8399: =cut
8400:
8401: sub no_cache {
8402: my ($r) = @_;
8403: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
8404: $env{'request.method'} ne 'GET') { return ''; }
8405: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
8406: $r->no_cache(1);
8407: $r->header_out("Expires" => $date);
8408: $r->header_out("Pragma" => "no-cache");
8409: }
8410:
8411: sub content_type {
8412: my ($r,$type,$charset) = @_;
8413: if ($r) {
8414: # Note that printout.pl calls this with undef for $r.
8415: &no_cache($r);
8416: }
8417: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
8418: unless ($charset) {
8419: $charset=&Apache::lonlocal::current_encoding;
8420: }
8421: if ($charset) { $type.='; charset='.$charset; }
8422: if ($r) {
8423: $r->content_type($type);
8424: } else {
8425: print("Content-type: $type\n\n");
8426: }
8427: }
8428:
8429: =pod
8430:
8431: =item * &add_to_env($name,$value)
8432:
8433: adds $name to the %env hash with value
8434: $value, if $name already exists, the entry is converted to an array
8435: reference and $value is added to the array.
8436:
8437: =cut
8438:
8439: sub add_to_env {
8440: my ($name,$value)=@_;
8441: if (defined($env{$name})) {
8442: if (ref($env{$name})) {
8443: #already have multiple values
8444: push(@{ $env{$name} },$value);
8445: } else {
8446: #first time seeing multiple values, convert hash entry to an arrayref
8447: my $first=$env{$name};
8448: undef($env{$name});
8449: push(@{ $env{$name} },$first,$value);
8450: }
8451: } else {
8452: $env{$name}=$value;
8453: }
8454: }
8455:
8456: =pod
8457:
8458: =item * &get_env_multiple($name)
8459:
8460: gets $name from the %env hash, it seemlessly handles the cases where multiple
8461: values may be defined and end up as an array ref.
8462:
8463: returns an array of values
8464:
8465: =cut
8466:
8467: sub get_env_multiple {
8468: my ($name) = @_;
8469: my @values;
8470: if (defined($env{$name})) {
8471: # exists is it an array
8472: if (ref($env{$name})) {
8473: @values=@{ $env{$name} };
8474: } else {
8475: $values[0]=$env{$name};
8476: }
8477: }
8478: return(@values);
8479: }
8480:
8481: sub ask_for_embedded_content {
8482: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
8483: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
8484: my $num = 0;
8485: my $numremref = 0;
8486: my $numinvalid = 0;
8487: my $numpathchg = 0;
8488: my $numexisting = 0;
8489: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
8490: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8491: my $current_path='/';
8492: if ($env{'form.currentpath'}) {
8493: $current_path = $env{'form.currentpath'};
8494: }
8495: if ($actionurl eq '/adm/coursegrp_portfolio') {
8496: $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8497: $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
8498: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
8499: } else {
8500: $udom = $env{'user.domain'};
8501: $uname = $env{'user.name'};
8502: $url = '/userfiles/portfolio';
8503: }
8504: $toplevel = $url.'/';
8505: $url .= $current_path;
8506: $getpropath = 1;
8507: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
8508: ($actionurl eq '/adm/imsimport')) {
8509: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
8510: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
8511: $toplevel = $url;
8512: if ($rest ne '') {
8513: $url .= $rest;
8514: }
8515: } elsif ($actionurl eq '/adm/coursedocs') {
8516: if (ref($args) eq 'HASH') {
8517: $url = $args->{'docs_url'};
8518: $toplevel = $url;
8519: }
8520: }
8521: my $now = time();
8522: foreach my $embed_file (keys(%{$allfiles})) {
8523: my $absolutepath;
8524: if ($embed_file =~ m{^\w+://}) {
8525: $newfiles{$embed_file} = 1;
8526: $mapping{$embed_file} = $embed_file;
8527: } else {
8528: if ($embed_file =~ m{^/}) {
8529: $absolutepath = $embed_file;
8530: $embed_file =~ s{^(/+)}{};
8531: }
8532: if ($embed_file =~ m{/}) {
8533: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
8534: $path = &check_for_traversal($path,$url,$toplevel);
8535: my $item = $fname;
8536: if ($path ne '') {
8537: $item = $path.'/'.$fname;
8538: $subdependencies{$path}{$fname} = 1;
8539: } else {
8540: $dependencies{$item} = 1;
8541: }
8542: if ($absolutepath) {
8543: $mapping{$item} = $absolutepath;
8544: } else {
8545: $mapping{$item} = $embed_file;
8546: }
8547: } else {
8548: $dependencies{$embed_file} = 1;
8549: if ($absolutepath) {
8550: $mapping{$embed_file} = $absolutepath;
8551: } else {
8552: $mapping{$embed_file} = $embed_file;
8553: }
8554: }
8555: }
8556: }
8557: foreach my $path (keys(%subdependencies)) {
8558: my %currsubfile;
8559: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8560: my ($sublistref,$listerror) =
8561: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
8562: if (ref($sublistref) eq 'ARRAY') {
8563: foreach my $line (@{$sublistref}) {
8564: my ($file_name,$rest) = split(/\&/,$line,2);
8565: $currsubfile{$file_name} = 1;
8566: }
8567: }
8568: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
8569: if (opendir(my $dir,$url.'/'.$path)) {
8570: my @subdir_list = grep(!/^\./,readdir($dir));
8571: map {$currsubfile{$_} = 1;} @subdir_list;
8572: }
8573: }
8574: foreach my $file (keys(%{$subdependencies{$path}})) {
8575: if ($currsubfile{$file}) {
8576: my $item = $path.'/'.$file;
8577: unless ($mapping{$item} eq $item) {
8578: $pathchanges{$item} = 1;
8579: }
8580: $existing{$item} = 1;
8581: $numexisting ++;
8582: } else {
8583: $newfiles{$path.'/'.$file} = 1;
8584: }
8585: }
8586: }
8587: my %currfile;
8588: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8589: my ($dirlistref,$listerror) =
8590: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
8591: if (ref($dirlistref) eq 'ARRAY') {
8592: foreach my $line (@{$dirlistref}) {
8593: my ($file_name,$rest) = split(/\&/,$line,2);
8594: $currfile{$file_name} = 1;
8595: }
8596: }
8597: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
8598: if (opendir(my $dir,$url)) {
8599: my @dir_list = grep(!/^\./,readdir($dir));
8600: map {$currfile{$_} = 1;} @dir_list;
8601: }
8602: }
8603: foreach my $file (keys(%dependencies)) {
8604: if ($currfile{$file}) {
8605: unless ($mapping{$file} eq $file) {
8606: $pathchanges{$file} = 1;
8607: }
8608: $existing{$file} = 1;
8609: $numexisting ++;
8610: } else {
8611: $newfiles{$file} = 1;
8612: }
8613: }
8614: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
8615: $upload_output .= &start_data_table_row().
8616: '<td><span class="LC_filename">'.$embed_file.'</span>';
8617: unless ($mapping{$embed_file} eq $embed_file) {
8618: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
8619: }
8620: $upload_output .= '</td><td>';
8621: if ($args->{'ignore_remote_references'}
8622: && $embed_file =~ m{^\w+://}) {
8623: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
8624: $numremref++;
8625: } elsif ($args->{'error_on_invalid_names'}
8626: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
8627:
8628: $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
8629: $numinvalid++;
8630: } else {
8631: $upload_output .= &embedded_file_element('upload_embedded',$num,
8632: $embed_file,\%mapping,
8633: $allfiles,$codebase);
8634: $num++;
8635: }
8636: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
8637: }
8638: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
8639: $upload_output .= &start_data_table_row().
8640: '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
8641: '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
8642: &Apache::loncommon::end_data_table_row()."\n";
8643: }
8644: if ($upload_output) {
8645: $upload_output = &start_data_table().
8646: $upload_output.
8647: &end_data_table()."\n";
8648: }
8649: my $applies = 0;
8650: if ($numremref) {
8651: $applies ++;
8652: }
8653: if ($numinvalid) {
8654: $applies ++;
8655: }
8656: if ($numexisting) {
8657: $applies ++;
8658: }
8659: if ($num) {
8660: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
8661: ' method="post" enctype="multipart/form-data">'."\n".
8662: $state.
8663: '<h3>'.&mt('Upload embedded files').
8664: ':</h3>'.$upload_output.'<br />'."\n".
8665: '<input type ="hidden" name="number_embedded_items" value="'.
8666: $num.'" />'."\n";
8667: if ($actionurl eq '') {
8668: $output .= '<input type="hidden" name="phase" value="three" />';
8669: }
8670: } elsif ($applies) {
8671: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
8672: if ($applies > 1) {
8673: $output .=
8674: &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
8675: if ($numremref) {
8676: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
8677: }
8678: if ($numinvalid) {
8679: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
8680: }
8681: if ($numexisting) {
8682: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
8683: }
8684: $output .= '</ul><br />';
8685: } elsif ($numremref) {
8686: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
8687: } elsif ($numinvalid) {
8688: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
8689: } elsif ($numexisting) {
8690: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
8691: }
8692: $output .= $upload_output.'<br />';
8693: }
8694: my ($pathchange_output,$chgcount);
8695: $chgcount = $num;
8696: if (keys(%pathchanges) > 0) {
8697: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
8698: if ($num) {
8699: $output .= &embedded_file_element('pathchange',$chgcount,
8700: $embed_file,\%mapping,
8701: $allfiles,$codebase);
8702: } else {
8703: $pathchange_output .=
8704: &start_data_table_row().
8705: '<td><input type ="checkbox" name="namechange" value="'.
8706: $chgcount.'" checked="checked" /></td>'.
8707: '<td>'.$mapping{$embed_file}.'</td>'.
8708: '<td>'.$embed_file.
8709: &embedded_file_element('pathchange',$numpathchg,$embed_file,
8710: \%mapping,$allfiles,$codebase).
8711: '</td>'.&end_data_table_row();
8712: }
8713: $numpathchg ++;
8714: $chgcount ++;
8715: }
8716: }
8717: if ($num) {
8718: if ($numpathchg) {
8719: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
8720: $numpathchg.'" />'."\n";
8721: }
8722: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
8723: ($actionurl eq '/adm/imsimport')) {
8724: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
8725: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
8726: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
8727: }
8728: $output .= '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
8729: &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
8730: } elsif ($numpathchg) {
8731: my %pathchange = ();
8732: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
8733: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8734: $output .= '<p>'.&mt('or').'</p>';
8735: }
8736: }
8737: return ($output,$num,$numpathchg);
8738: }
8739:
8740: sub embedded_file_element {
8741: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
8742: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
8743: (ref($codebase) eq 'HASH'));
8744: my $output;
8745: if ($context eq 'upload_embedded') {
8746: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
8747: }
8748: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
8749: &escape($embed_file).'" />';
8750: unless (($context eq 'upload_embedded') &&
8751: ($mapping->{$embed_file} eq $embed_file)) {
8752: $output .='
8753: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
8754: }
8755: my $attrib;
8756: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
8757: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
8758: }
8759: $output .=
8760: "\n\t\t".
8761: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
8762: $attrib.'" />';
8763: if (exists($codebase->{$mapping->{$embed_file}})) {
8764: $output .=
8765: "\n\t\t".
8766: '<input name="codebase_'.$num.'" type="hidden" value="'.
8767: &escape($codebase->{$mapping->{$embed_file}}).'" />';
8768: }
8769: return $output;
8770: }
8771:
8772: sub upload_embedded {
8773: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
8774: $current_disk_usage,$hiddenstate,$actionurl) = @_;
8775: my (%pathchange,$output,$modifyform,$footer,$returnflag);
8776: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
8777: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
8778: my $orig_uploaded_filename =
8779: $env{'form.embedded_item_'.$i.'.filename'};
8780: foreach my $type ('orig','ref','attrib','codebase') {
8781: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
8782: $env{'form.embedded_'.$type.'_'.$i} =
8783: &unescape($env{'form.embedded_'.$type.'_'.$i});
8784: }
8785: }
8786: my ($path,$fname) =
8787: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
8788: # no path, whole string is fname
8789: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
8790: $fname = &Apache::lonnet::clean_filename($fname);
8791: # See if there is anything left
8792: next if ($fname eq '');
8793:
8794: # Check if file already exists as a file or directory.
8795: my ($state,$msg);
8796: if ($context eq 'portfolio') {
8797: my $port_path = $dirpath;
8798: if ($group ne '') {
8799: $port_path = "groups/$group/$port_path";
8800: }
8801: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
8802: $fname,$group,'embedded_item_'.$i,
8803: $dir_root,$port_path,$disk_quota,
8804: $current_disk_usage,$uname,$udom);
8805: if ($state eq 'will_exceed_quota'
8806: || $state eq 'file_locked') {
8807: $output .= $msg;
8808: next;
8809: }
8810: } elsif (($context eq 'author') || ($context eq 'testbank')) {
8811: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
8812: if ($state eq 'exists') {
8813: $output .= $msg;
8814: next;
8815: }
8816: }
8817: # Check if extension is valid
8818: if (($fname =~ /\.(\w+)$/) &&
8819: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
8820: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
8821: next;
8822: } elsif (($fname =~ /\.(\w+)$/) &&
8823: (!defined(&Apache::loncommon::fileembstyle($1)))) {
8824: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
8825: next;
8826: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
8827: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
8828: next;
8829: }
8830:
8831: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
8832: if ($context eq 'portfolio') {
8833: my $result;
8834: if ($state eq 'existingfile') {
8835: $result=
8836: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
8837: $dirpath.$env{'form.currentpath'}.$path);
8838: } else {
8839: $result=
8840: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
8841: $dirpath.
8842: $env{'form.currentpath'}.$path);
8843: if ($result !~ m|^/uploaded/|) {
8844: $output .= '<span class="LC_error">'
8845: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
8846: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
8847: .'</span><br />';
8848: next;
8849: } else {
8850: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
8851: $path.$fname.'</span>').'<br />';
8852: }
8853: }
8854: } elsif ($context eq 'coursedoc') {
8855: my $result =
8856: &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
8857: $dirpath.'/'.$path);
8858: if ($result !~ m|^/uploaded/|) {
8859: $output .= '<span class="LC_error">'
8860: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
8861: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
8862: .'</span><br />';
8863: next;
8864: } else {
8865: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
8866: $path.$fname.'</span>').'<br />';
8867: }
8868: } else {
8869: # Save the file
8870: my $target = $env{'form.embedded_item_'.$i};
8871: my $fullpath = $dir_root.$dirpath.'/'.$path;
8872: my $dest = $fullpath.$fname;
8873: my $url = $url_root.$dirpath.'/'.$path.$fname;
8874: my @parts=split(/\//,"$dirpath/$path");
8875: my $count;
8876: my $filepath = $dir_root;
8877: foreach my $subdir (@parts) {
8878: $filepath .= "/$subdir";
8879: if (!-e $filepath) {
8880: mkdir($filepath,0770);
8881: }
8882: }
8883: my $fh;
8884: if (!open($fh,'>'.$dest)) {
8885: &Apache::lonnet::logthis('Failed to create '.$dest);
8886: $output .= '<span class="LC_error">'.
8887: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8888: '</span><br />';
8889: } else {
8890: if (!print $fh $env{'form.embedded_item_'.$i}) {
8891: &Apache::lonnet::logthis('Failed to write to '.$dest);
8892: $output .= '<span class="LC_error">'.
8893: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
8894: '</span><br />';
8895: } else {
8896: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
8897: $url.'</span>').'<br />';
8898: unless ($context eq 'testbank') {
8899: $footer .= &mt('View embedded file: [_1]',
8900: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
8901: }
8902: }
8903: close($fh);
8904: }
8905: }
8906: if ($env{'form.embedded_ref_'.$i}) {
8907: $pathchange{$i} = 1;
8908: }
8909: }
8910: if ($output) {
8911: $output = '<p>'.$output.'</p>';
8912: }
8913: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
8914: $returnflag = 'ok';
8915: if (keys(%pathchange) > 0) {
8916: if ($context eq 'portfolio') {
8917: $output .= '<p>'.&mt('or').'</p>';
8918: } elsif ($context eq 'testbank') {
8919: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
8920: $returnflag = 'modify_orightml';
8921: }
8922: }
8923: return ($output.$footer,$returnflag);
8924: }
8925:
8926: sub modify_html_form {
8927: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
8928: my $end = 0;
8929: my $modifyform;
8930: if ($context eq 'upload_embedded') {
8931: return unless (ref($pathchange) eq 'HASH');
8932: if ($env{'form.number_embedded_items'}) {
8933: $end += $env{'form.number_embedded_items'};
8934: }
8935: if ($env{'form.number_pathchange_items'}) {
8936: $end += $env{'form.number_pathchange_items'};
8937: }
8938: if ($end) {
8939: for (my $i=0; $i<$end; $i++) {
8940: if ($i < $env{'form.number_embedded_items'}) {
8941: next unless($pathchange->{$i});
8942: }
8943: $modifyform .=
8944: &start_data_table_row().
8945: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
8946: 'checked="checked" /></td>'.
8947: '<td>'.$env{'form.embedded_ref_'.$i}.
8948: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
8949: &escape($env{'form.embedded_ref_'.$i}).'" />'.
8950: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
8951: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
8952: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
8953: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
8954: '<td>'.$env{'form.embedded_orig_'.$i}.
8955: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
8956: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
8957: &end_data_table_row();
8958: }
8959: }
8960: } else {
8961: $modifyform = $pathchgtable;
8962: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
8963: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
8964: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8965: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
8966: }
8967: }
8968: if ($modifyform) {
8969: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
8970: '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
8971: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
8972: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
8973: '</ol></p>'."\n".'<p>'.
8974: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
8975: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
8976: &start_data_table()."\n".
8977: &start_data_table_header_row().
8978: '<th>'.&mt('Change?').'</th>'.
8979: '<th>'.&mt('Current reference').'</th>'.
8980: '<th>'.&mt('Required reference').'</th>'.
8981: &end_data_table_header_row()."\n".
8982: $modifyform.
8983: &end_data_table().'<br />'."\n".$hiddenstate.
8984: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
8985: '</form>'."\n";
8986: }
8987: return;
8988: }
8989:
8990: sub modify_html_refs {
8991: my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
8992: my $container;
8993: if ($context eq 'portfolio') {
8994: $container = $env{'form.container'};
8995: } elsif ($context eq 'coursedoc') {
8996: $container = $env{'form.primaryurl'};
8997: } else {
8998: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
8999: }
9000: my (%allfiles,%codebase,$output,$content);
9001: my @changes = &get_env_multiple('form.namechange');
9002: return unless (@changes > 0);
9003: if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
9004: return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
9005: $content = &Apache::lonnet::getfile($container);
9006: return if ($content eq '-1');
9007: } else {
9008: return unless ($container =~ /^\Q$dir_root\E/);
9009: if (open(my $fh,"<$container")) {
9010: $content = join('', <$fh>);
9011: close($fh);
9012: } else {
9013: return;
9014: }
9015: }
9016: my ($count,$codebasecount) = (0,0);
9017: my $mm = new File::MMagic;
9018: my $mime_type = $mm->checktype_contents($content);
9019: if ($mime_type eq 'text/html') {
9020: my $parse_result =
9021: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
9022: \%codebase,\$content);
9023: if ($parse_result eq 'ok') {
9024: foreach my $i (@changes) {
9025: my $orig = &unescape($env{'form.embedded_orig_'.$i});
9026: my $ref = &unescape($env{'form.embedded_ref_'.$i});
9027: if ($allfiles{$ref}) {
9028: my $newname = $orig;
9029: my ($attrib_regexp,$codebase);
9030: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
9031: if ($attrib_regexp =~ /:/) {
9032: $attrib_regexp =~ s/\:/|/g;
9033: }
9034: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
9035: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
9036: $count += $numchg;
9037: }
9038: if ($env{'form.embedded_codebase_'.$i} ne '') {
9039: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
9040: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
9041: $codebasecount ++;
9042: }
9043: }
9044: }
9045: if ($count || $codebasecount) {
9046: my $saveresult;
9047: if ($context eq 'portfolio' || $context eq 'coursedoc') {
9048: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
9049: if ($url eq $container) {
9050: my ($fname) = ($container =~ m{/([^/]+)$});
9051: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9052: $count,'<span class="LC_filename">'.
9053: $fname.'</span>').'</p>';
9054: } else {
9055: $output = '<p class="LC_error">'.
9056: &mt('Error: update failed for: [_1].',
9057: '<span class="LC_filename">'.
9058: $container.'</span>').'</p>';
9059: }
9060: } else {
9061: if (open(my $fh,">$container")) {
9062: print $fh $content;
9063: close($fh);
9064: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9065: $count,'<span class="LC_filename">'.
9066: $container.'</span>').'</p>';
9067: } else {
9068: $output = '<p class="LC_error">'.
9069: &mt('Error: could not update [_1].',
9070: '<span class="LC_filename">'.
9071: $container.'</span>').'</p>';
9072: }
9073: }
9074: }
9075: } else {
9076: &logthis('Failed to parse '.$container.
9077: ' to modify references: '.$parse_result);
9078: }
9079: }
9080: return $output;
9081: }
9082:
9083: sub check_for_existing {
9084: my ($path,$fname,$element) = @_;
9085: my ($state,$msg);
9086: if (-d $path.'/'.$fname) {
9087: $state = 'exists';
9088: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9089: } elsif (-e $path.'/'.$fname) {
9090: $state = 'exists';
9091: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9092: }
9093: if ($state eq 'exists') {
9094: $msg = '<span class="LC_error">'.$msg.'</span><br />';
9095: }
9096: return ($state,$msg);
9097: }
9098:
9099: sub check_for_upload {
9100: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
9101: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
9102: my $filesize = length($env{'form.'.$element});
9103: if (!$filesize) {
9104: my $msg = '<span class="LC_error">'.
9105: &mt('Unable to upload [_1]. (size = [_2] bytes)',
9106: '<span class="LC_filename">'.$fname.'</span>',
9107: $filesize).'<br />'.
9108: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
9109: '</span>';
9110: return ('zero_bytes',$msg);
9111: }
9112: $filesize = $filesize/1000; #express in k (1024?)
9113: my $getpropath = 1;
9114: my ($dirlistref,$listerror) =
9115: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
9116: my $found_file = 0;
9117: my $locked_file = 0;
9118: my @lockers;
9119: my $navmap;
9120: if ($env{'request.course.id'}) {
9121: $navmap = Apache::lonnavmaps::navmap->new();
9122: }
9123: if (ref($dirlistref) eq 'ARRAY') {
9124: foreach my $line (@{$dirlistref}) {
9125: my ($file_name,$rest)=split(/\&/,$line,2);
9126: if ($file_name eq $fname){
9127: $file_name = $path.$file_name;
9128: if ($group ne '') {
9129: $file_name = $group.$file_name;
9130: }
9131: $found_file = 1;
9132: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
9133: foreach my $lock (@lockers) {
9134: if (ref($lock) eq 'ARRAY') {
9135: my ($symb,$crsid) = @{$lock};
9136: if ($crsid eq $env{'request.course.id'}) {
9137: if (ref($navmap)) {
9138: my $res = $navmap->getBySymb($symb);
9139: foreach my $part (@{$res->parts()}) {
9140: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
9141: unless (($slot_status == $res->RESERVED) ||
9142: ($slot_status == $res->RESERVED_LOCATION)) {
9143: $locked_file = 1;
9144: }
9145: }
9146: } else {
9147: $locked_file = 1;
9148: }
9149: } else {
9150: $locked_file = 1;
9151: }
9152: }
9153: }
9154: } else {
9155: my @info = split(/\&/,$rest);
9156: my $currsize = $info[6]/1000;
9157: if ($currsize < $filesize) {
9158: my $extra = $filesize - $currsize;
9159: if (($current_disk_usage + $extra) > $disk_quota) {
9160: my $msg = '<span class="LC_error">'.
9161: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
9162: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
9163: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9164: $disk_quota,$current_disk_usage);
9165: return ('will_exceed_quota',$msg);
9166: }
9167: }
9168: }
9169: }
9170: }
9171: }
9172: if (($current_disk_usage + $filesize) > $disk_quota){
9173: my $msg = '<span class="LC_error">'.
9174: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
9175: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
9176: return ('will_exceed_quota',$msg);
9177: } elsif ($found_file) {
9178: if ($locked_file) {
9179: my $msg = '<span class="LC_error">';
9180: $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>');
9181: $msg .= '</span><br />';
9182: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
9183: return ('file_locked',$msg);
9184: } else {
9185: my $msg = '<span class="LC_error">';
9186: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
9187: $msg .= '</span>';
9188: return ('existingfile',$msg);
9189: }
9190: }
9191: }
9192:
9193: sub check_for_traversal {
9194: my ($path,$url,$toplevel) = @_;
9195: my @parts=split(/\//,$path);
9196: my $cleanpath;
9197: my $fullpath = $url;
9198: for (my $i=0;$i<@parts;$i++) {
9199: next if ($parts[$i] eq '.');
9200: if ($parts[$i] eq '..') {
9201: $fullpath =~ s{([^/]+/)$}{};
9202: } else {
9203: $fullpath .= $parts[$i].'/';
9204: }
9205: }
9206: if ($fullpath =~ /^\Q$url\E(.*)$/) {
9207: $cleanpath = $1;
9208: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
9209: my $curr_toprel = $1;
9210: my @parts = split(/\//,$curr_toprel);
9211: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
9212: my @urlparts = split(/\//,$url_toprel);
9213: my $doubledots;
9214: my $startdiff = -1;
9215: for (my $i=0; $i<@urlparts; $i++) {
9216: if ($startdiff == -1) {
9217: unless ($urlparts[$i] eq $parts[$i]) {
9218: $startdiff = $i;
9219: $doubledots .= '../';
9220: }
9221: } else {
9222: $doubledots .= '../';
9223: }
9224: }
9225: if ($startdiff > -1) {
9226: $cleanpath = $doubledots;
9227: for (my $i=$startdiff; $i<@parts; $i++) {
9228: $cleanpath .= $parts[$i].'/';
9229: }
9230: }
9231: }
9232: $cleanpath =~ s{(/)$}{};
9233: return $cleanpath;
9234: }
9235:
9236: =pod
9237:
9238: =item * &get_turnedin_filepath()
9239:
9240: Determines path in a user's portfolio file for storage of files uploaded
9241: to a specific essayresponse or dropbox item.
9242:
9243: Inputs: 3 required + 1 optional.
9244: $symb is symb for resource, $uname and $udom are for current user (required).
9245: $caller is optional (can be "submission", if routine is called when storing
9246: an upoaded file when "Submit Answer" button was pressed).
9247:
9248: Returns array containing $path and $multiresp.
9249: $path is path in portfolio. $multiresp is 1 if this resource contains more
9250: than one file upload item. Callers of routine should append partid as a
9251: subdirectory to $path in cases where $multiresp is 1.
9252:
9253: Called by: homework/essayresponse.pm and homework/structuretags.pm
9254:
9255: =cut
9256:
9257: sub get_turnedin_filepath {
9258: my ($symb,$uname,$udom,$caller) = @_;
9259: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
9260: my $turnindir;
9261: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
9262: $turnindir = $userhash{'turnindir'};
9263: my ($path,$multiresp);
9264: if ($turnindir eq '') {
9265: if ($caller eq 'submission') {
9266: $turnindir = &mt('turned in');
9267: $turnindir =~ s/\W+/_/g;
9268: my %newhash = (
9269: 'turnindir' => $turnindir,
9270: );
9271: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
9272: }
9273: }
9274: if ($turnindir ne '') {
9275: $path = '/'.$turnindir.'/';
9276: my ($multipart,$turnin,@pathitems);
9277: my $navmap = Apache::lonnavmaps::navmap->new();
9278: if (defined($navmap)) {
9279: my $mapres = $navmap->getResourceByUrl($map);
9280: if (ref($mapres)) {
9281: my $pcslist = $mapres->map_hierarchy();
9282: if ($pcslist ne '') {
9283: foreach my $pc (split(/,/,$pcslist)) {
9284: my $res = $navmap->getByMapPc($pc);
9285: if (ref($res)) {
9286: my $title = $res->compTitle();
9287: $title =~ s/\W+/_/g;
9288: if ($title ne '') {
9289: push(@pathitems,$title);
9290: }
9291: }
9292: }
9293: }
9294: my $maptitle = $mapres->compTitle();
9295: $maptitle =~ s/\W+/_/g;
9296: if ($maptitle ne '') {
9297: push(@pathitems,$maptitle);
9298: }
9299: unless ($env{'request.state'} eq 'construct') {
9300: my $res = $navmap->getBySymb($symb);
9301: if (ref($res)) {
9302: my $partlist = $res->parts();
9303: my $totaluploads = 0;
9304: if (ref($partlist) eq 'ARRAY') {
9305: foreach my $part (@{$partlist}) {
9306: my @types = $res->responseType($part);
9307: my @ids = $res->responseIds($part);
9308: for (my $i=0; $i < scalar(@ids); $i++) {
9309: if ($types[$i] eq 'essay') {
9310: my $partid = $part.'_'.$ids[$i];
9311: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
9312: $totaluploads ++;
9313: }
9314: }
9315: }
9316: }
9317: if ($totaluploads > 1) {
9318: $multiresp = 1;
9319: }
9320: }
9321: }
9322: }
9323: } else {
9324: return;
9325: }
9326: } else {
9327: return;
9328: }
9329: my $restitle=&Apache::lonnet::gettitle($symb);
9330: $restitle =~ s/\W+/_/g;
9331: if ($restitle eq '') {
9332: $restitle = ($resurl =~ m{/[^/]+$});
9333: if ($restitle eq '') {
9334: $restitle = time;
9335: }
9336: }
9337: push(@pathitems,$restitle);
9338: $path .= join('/',@pathitems);
9339: }
9340: return ($path,$multiresp);
9341: }
9342:
9343: =pod
9344:
9345: =back
9346:
9347: =head1 CSV Upload/Handling functions
9348:
9349: =over 4
9350:
9351: =item * &upfile_store($r)
9352:
9353: Store uploaded file, $r should be the HTTP Request object,
9354: needs $env{'form.upfile'}
9355: returns $datatoken to be put into hidden field
9356:
9357: =cut
9358:
9359: sub upfile_store {
9360: my $r=shift;
9361: $env{'form.upfile'}=~s/\r/\n/gs;
9362: $env{'form.upfile'}=~s/\f/\n/gs;
9363: $env{'form.upfile'}=~s/\n+/\n/gs;
9364: $env{'form.upfile'}=~s/\n+$//gs;
9365:
9366: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
9367: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
9368: {
9369: my $datafile = $r->dir_config('lonDaemons').
9370: '/tmp/'.$datatoken.'.tmp';
9371: if ( open(my $fh,">$datafile") ) {
9372: print $fh $env{'form.upfile'};
9373: close($fh);
9374: }
9375: }
9376: return $datatoken;
9377: }
9378:
9379: =pod
9380:
9381: =item * &load_tmp_file($r)
9382:
9383: Load uploaded file from tmp, $r should be the HTTP Request object,
9384: needs $env{'form.datatoken'},
9385: sets $env{'form.upfile'} to the contents of the file
9386:
9387: =cut
9388:
9389: sub load_tmp_file {
9390: my $r=shift;
9391: my @studentdata=();
9392: {
9393: my $studentfile = $r->dir_config('lonDaemons').
9394: '/tmp/'.$env{'form.datatoken'}.'.tmp';
9395: if ( open(my $fh,"<$studentfile") ) {
9396: @studentdata=<$fh>;
9397: close($fh);
9398: }
9399: }
9400: $env{'form.upfile'}=join('',@studentdata);
9401: }
9402:
9403: =pod
9404:
9405: =item * &upfile_record_sep()
9406:
9407: Separate uploaded file into records
9408: returns array of records,
9409: needs $env{'form.upfile'} and $env{'form.upfiletype'}
9410:
9411: =cut
9412:
9413: sub upfile_record_sep {
9414: if ($env{'form.upfiletype'} eq 'xml') {
9415: } else {
9416: my @records;
9417: foreach my $line (split(/\n/,$env{'form.upfile'})) {
9418: if ($line=~/^\s*$/) { next; }
9419: push(@records,$line);
9420: }
9421: return @records;
9422: }
9423: }
9424:
9425: =pod
9426:
9427: =item * &record_sep($record)
9428:
9429: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
9430:
9431: =cut
9432:
9433: sub takeleft {
9434: my $index=shift;
9435: return substr('0000'.$index,-4,4);
9436: }
9437:
9438: sub record_sep {
9439: my $record=shift;
9440: my %components=();
9441: if ($env{'form.upfiletype'} eq 'xml') {
9442: } elsif ($env{'form.upfiletype'} eq 'space') {
9443: my $i=0;
9444: foreach my $field (split(/\s+/,$record)) {
9445: $field=~s/^(\"|\')//;
9446: $field=~s/(\"|\')$//;
9447: $components{&takeleft($i)}=$field;
9448: $i++;
9449: }
9450: } elsif ($env{'form.upfiletype'} eq 'tab') {
9451: my $i=0;
9452: foreach my $field (split(/\t/,$record)) {
9453: $field=~s/^(\"|\')//;
9454: $field=~s/(\"|\')$//;
9455: $components{&takeleft($i)}=$field;
9456: $i++;
9457: }
9458: } else {
9459: my $separator=',';
9460: if ($env{'form.upfiletype'} eq 'semisv') {
9461: $separator=';';
9462: }
9463: my $i=0;
9464: # the character we are looking for to indicate the end of a quote or a record
9465: my $looking_for=$separator;
9466: # do not add the characters to the fields
9467: my $ignore=0;
9468: # we just encountered a separator (or the beginning of the record)
9469: my $just_found_separator=1;
9470: # store the field we are working on here
9471: my $field='';
9472: # work our way through all characters in record
9473: foreach my $character ($record=~/(.)/g) {
9474: if ($character eq $looking_for) {
9475: if ($character ne $separator) {
9476: # Found the end of a quote, again looking for separator
9477: $looking_for=$separator;
9478: $ignore=1;
9479: } else {
9480: # Found a separator, store away what we got
9481: $components{&takeleft($i)}=$field;
9482: $i++;
9483: $just_found_separator=1;
9484: $ignore=0;
9485: $field='';
9486: }
9487: next;
9488: }
9489: # single or double quotation marks after a separator indicate beginning of a quote
9490: # we are now looking for the end of the quote and need to ignore separators
9491: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
9492: $looking_for=$character;
9493: next;
9494: }
9495: # ignore would be true after we reached the end of a quote
9496: if ($ignore) { next; }
9497: if (($just_found_separator) && ($character=~/\s/)) { next; }
9498: $field.=$character;
9499: $just_found_separator=0;
9500: }
9501: # catch the very last entry, since we never encountered the separator
9502: $components{&takeleft($i)}=$field;
9503: }
9504: return %components;
9505: }
9506:
9507: ######################################################
9508: ######################################################
9509:
9510: =pod
9511:
9512: =item * &upfile_select_html()
9513:
9514: Return HTML code to select a file from the users machine and specify
9515: the file type.
9516:
9517: =cut
9518:
9519: ######################################################
9520: ######################################################
9521: sub upfile_select_html {
9522: my %Types = (
9523: csv => &mt('CSV (comma separated values, spreadsheet)'),
9524: semisv => &mt('Semicolon separated values'),
9525: space => &mt('Space separated'),
9526: tab => &mt('Tabulator separated'),
9527: # xml => &mt('HTML/XML'),
9528: );
9529: my $Str = '<input type="file" name="upfile" size="50" />'.
9530: '<br />'.&mt('Type').': <select name="upfiletype">';
9531: foreach my $type (sort(keys(%Types))) {
9532: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
9533: }
9534: $Str .= "</select>\n";
9535: return $Str;
9536: }
9537:
9538: sub get_samples {
9539: my ($records,$toget) = @_;
9540: my @samples=({});
9541: my $got=0;
9542: foreach my $rec (@$records) {
9543: my %temp = &record_sep($rec);
9544: if (! grep(/\S/, values(%temp))) { next; }
9545: if (%temp) {
9546: $samples[$got]=\%temp;
9547: $got++;
9548: if ($got == $toget) { last; }
9549: }
9550: }
9551: return \@samples;
9552: }
9553:
9554: ######################################################
9555: ######################################################
9556:
9557: =pod
9558:
9559: =item * &csv_print_samples($r,$records)
9560:
9561: Prints a table of sample values from each column uploaded $r is an
9562: Apache Request ref, $records is an arrayref from
9563: &Apache::loncommon::upfile_record_sep
9564:
9565: =cut
9566:
9567: ######################################################
9568: ######################################################
9569: sub csv_print_samples {
9570: my ($r,$records) = @_;
9571: my $samples = &get_samples($records,5);
9572:
9573: $r->print(&mt('Samples').'<br />'.&start_data_table().
9574: &start_data_table_header_row());
9575: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
9576: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
9577: $r->print(&end_data_table_header_row());
9578: foreach my $hash (@$samples) {
9579: $r->print(&start_data_table_row());
9580: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
9581: $r->print('<td>');
9582: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
9583: $r->print('</td>');
9584: }
9585: $r->print(&end_data_table_row());
9586: }
9587: $r->print(&end_data_table().'<br />'."\n");
9588: }
9589:
9590: ######################################################
9591: ######################################################
9592:
9593: =pod
9594:
9595: =item * &csv_print_select_table($r,$records,$d)
9596:
9597: Prints a table to create associations between values and table columns.
9598:
9599: $r is an Apache Request ref,
9600: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
9601: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
9602:
9603: =cut
9604:
9605: ######################################################
9606: ######################################################
9607: sub csv_print_select_table {
9608: my ($r,$records,$d) = @_;
9609: my $i=0;
9610: my $samples = &get_samples($records,1);
9611: $r->print(&mt('Associate columns with student attributes.')."\n".
9612: &start_data_table().&start_data_table_header_row().
9613: '<th>'.&mt('Attribute').'</th>'.
9614: '<th>'.&mt('Column').'</th>'.
9615: &end_data_table_header_row()."\n");
9616: foreach my $array_ref (@$d) {
9617: my ($value,$display,$defaultcol)=@{ $array_ref };
9618: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
9619:
9620: $r->print('<td><select name="f'.$i.'"'.
9621: ' onchange="javascript:flip(this.form,'.$i.');">');
9622: $r->print('<option value="none"></option>');
9623: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
9624: $r->print('<option value="'.$sample.'"'.
9625: ($sample eq $defaultcol ? ' selected="selected" ' : '').
9626: '>'.&mt('Column [_1]',($sample+1)).'</option>');
9627: }
9628: $r->print('</select></td>'.&end_data_table_row()."\n");
9629: $i++;
9630: }
9631: $r->print(&end_data_table());
9632: $i--;
9633: return $i;
9634: }
9635:
9636: ######################################################
9637: ######################################################
9638:
9639: =pod
9640:
9641: =item * &csv_samples_select_table($r,$records,$d)
9642:
9643: Prints a table of sample values from the upload and can make associate samples to internal names.
9644:
9645: $r is an Apache Request ref,
9646: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
9647: $d is an array of 2 element arrays (internal name, displayed name)
9648:
9649: =cut
9650:
9651: ######################################################
9652: ######################################################
9653: sub csv_samples_select_table {
9654: my ($r,$records,$d) = @_;
9655: my $i=0;
9656: #
9657: my $max_samples = 5;
9658: my $samples = &get_samples($records,$max_samples);
9659: $r->print(&start_data_table().
9660: &start_data_table_header_row().'<th>'.
9661: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
9662: &end_data_table_header_row());
9663:
9664: foreach my $key (sort(keys(%{ $samples->[0] }))) {
9665: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
9666: ' onchange="javascript:flip(this.form,'.$i.');">');
9667: foreach my $option (@$d) {
9668: my ($value,$display,$defaultcol)=@{ $option };
9669: $r->print('<option value="'.$value.'"'.
9670: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
9671: $display.'</option>');
9672: }
9673: $r->print('</select></td><td>');
9674: foreach my $line (0..($max_samples-1)) {
9675: if (defined($samples->[$line]{$key})) {
9676: $r->print($samples->[$line]{$key}."<br />\n");
9677: }
9678: }
9679: $r->print('</td>'.&end_data_table_row());
9680: $i++;
9681: }
9682: $r->print(&end_data_table());
9683: $i--;
9684: return($i);
9685: }
9686:
9687: ######################################################
9688: ######################################################
9689:
9690: =pod
9691:
9692: =item * &clean_excel_name($name)
9693:
9694: Returns a replacement for $name which does not contain any illegal characters.
9695:
9696: =cut
9697:
9698: ######################################################
9699: ######################################################
9700: sub clean_excel_name {
9701: my ($name) = @_;
9702: $name =~ s/[:\*\?\/\\]//g;
9703: if (length($name) > 31) {
9704: $name = substr($name,0,31);
9705: }
9706: return $name;
9707: }
9708:
9709: =pod
9710:
9711: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
9712:
9713: Returns either 1 or undef
9714:
9715: 1 if the part is to be hidden, undef if it is to be shown
9716:
9717: Arguments are:
9718:
9719: $id the id of the part to be checked
9720: $symb, optional the symb of the resource to check
9721: $udom, optional the domain of the user to check for
9722: $uname, optional the username of the user to check for
9723:
9724: =cut
9725:
9726: sub check_if_partid_hidden {
9727: my ($id,$symb,$udom,$uname) = @_;
9728: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
9729: $symb,$udom,$uname);
9730: my $truth=1;
9731: #if the string starts with !, then the list is the list to show not hide
9732: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
9733: my @hiddenlist=split(/,/,$hiddenparts);
9734: foreach my $checkid (@hiddenlist) {
9735: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
9736: }
9737: return !$truth;
9738: }
9739:
9740:
9741: ############################################################
9742: ############################################################
9743:
9744: =pod
9745:
9746: =back
9747:
9748: =head1 cgi-bin script and graphing routines
9749:
9750: =over 4
9751:
9752: =item * &get_cgi_id()
9753:
9754: Inputs: none
9755:
9756: Returns an id which can be used to pass environment variables
9757: to various cgi-bin scripts. These environment variables will
9758: be removed from the users environment after a given time by
9759: the routine &Apache::lonnet::transfer_profile_to_env.
9760:
9761: =cut
9762:
9763: ############################################################
9764: ############################################################
9765: my $uniq=0;
9766: sub get_cgi_id {
9767: $uniq=($uniq+1)%100000;
9768: return (time.'_'.$$.'_'.$uniq);
9769: }
9770:
9771: ############################################################
9772: ############################################################
9773:
9774: =pod
9775:
9776: =item * &DrawBarGraph()
9777:
9778: Facilitates the plotting of data in a (stacked) bar graph.
9779: Puts plot definition data into the users environment in order for
9780: graph.png to plot it. Returns an <img> tag for the plot.
9781: The bars on the plot are labeled '1','2',...,'n'.
9782:
9783: Inputs:
9784:
9785: =over 4
9786:
9787: =item $Title: string, the title of the plot
9788:
9789: =item $xlabel: string, text describing the X-axis of the plot
9790:
9791: =item $ylabel: string, text describing the Y-axis of the plot
9792:
9793: =item $Max: scalar, the maximum Y value to use in the plot
9794: If $Max is < any data point, the graph will not be rendered.
9795:
9796: =item $colors: array ref holding the colors to be used for the data sets when
9797: they are plotted. If undefined, default values will be used.
9798:
9799: =item $labels: array ref holding the labels to use on the x-axis for the bars.
9800:
9801: =item @Values: An array of array references. Each array reference holds data
9802: to be plotted in a stacked bar chart.
9803:
9804: =item If the final element of @Values is a hash reference the key/value
9805: pairs will be added to the graph definition.
9806:
9807: =back
9808:
9809: Returns:
9810:
9811: An <img> tag which references graph.png and the appropriate identifying
9812: information for the plot.
9813:
9814: =cut
9815:
9816: ############################################################
9817: ############################################################
9818: sub DrawBarGraph {
9819: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
9820: #
9821: if (! defined($colors)) {
9822: $colors = ['#33ff00',
9823: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
9824: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
9825: ];
9826: }
9827: my $extra_settings = {};
9828: if (ref($Values[-1]) eq 'HASH') {
9829: $extra_settings = pop(@Values);
9830: }
9831: #
9832: my $identifier = &get_cgi_id();
9833: my $id = 'cgi.'.$identifier;
9834: if (! @Values || ref($Values[0]) ne 'ARRAY') {
9835: return '';
9836: }
9837: #
9838: my @Labels;
9839: if (defined($labels)) {
9840: @Labels = @$labels;
9841: } else {
9842: for (my $i=0;$i<@{$Values[0]};$i++) {
9843: push (@Labels,$i+1);
9844: }
9845: }
9846: #
9847: my $NumBars = scalar(@{$Values[0]});
9848: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
9849: my %ValuesHash;
9850: my $NumSets=1;
9851: foreach my $array (@Values) {
9852: next if (! ref($array));
9853: $ValuesHash{$id.'.data.'.$NumSets++} =
9854: join(',',@$array);
9855: }
9856: #
9857: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
9858: if ($NumBars < 3) {
9859: $width = 120+$NumBars*32;
9860: $xskip = 1;
9861: $bar_width = 30;
9862: } elsif ($NumBars < 5) {
9863: $width = 120+$NumBars*20;
9864: $xskip = 1;
9865: $bar_width = 20;
9866: } elsif ($NumBars < 10) {
9867: $width = 120+$NumBars*15;
9868: $xskip = 1;
9869: $bar_width = 15;
9870: } elsif ($NumBars <= 25) {
9871: $width = 120+$NumBars*11;
9872: $xskip = 5;
9873: $bar_width = 8;
9874: } elsif ($NumBars <= 50) {
9875: $width = 120+$NumBars*8;
9876: $xskip = 5;
9877: $bar_width = 4;
9878: } else {
9879: $width = 120+$NumBars*8;
9880: $xskip = 5;
9881: $bar_width = 4;
9882: }
9883: #
9884: $Max = 1 if ($Max < 1);
9885: if ( int($Max) < $Max ) {
9886: $Max++;
9887: $Max = int($Max);
9888: }
9889: $Title = '' if (! defined($Title));
9890: $xlabel = '' if (! defined($xlabel));
9891: $ylabel = '' if (! defined($ylabel));
9892: $ValuesHash{$id.'.title'} = &escape($Title);
9893: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
9894: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
9895: $ValuesHash{$id.'.y_max_value'} = $Max;
9896: $ValuesHash{$id.'.NumBars'} = $NumBars;
9897: $ValuesHash{$id.'.NumSets'} = $NumSets;
9898: $ValuesHash{$id.'.PlotType'} = 'bar';
9899: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9900: $ValuesHash{$id.'.height'} = $height;
9901: $ValuesHash{$id.'.width'} = $width;
9902: $ValuesHash{$id.'.xskip'} = $xskip;
9903: $ValuesHash{$id.'.bar_width'} = $bar_width;
9904: $ValuesHash{$id.'.labels'} = join(',',@Labels);
9905: #
9906: # Deal with other parameters
9907: while (my ($key,$value) = each(%$extra_settings)) {
9908: $ValuesHash{$id.'.'.$key} = $value;
9909: }
9910: #
9911: &Apache::lonnet::appenv(\%ValuesHash);
9912: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
9913: }
9914:
9915: ############################################################
9916: ############################################################
9917:
9918: =pod
9919:
9920: =item * &DrawXYGraph()
9921:
9922: Facilitates the plotting of data in an XY graph.
9923: Puts plot definition data into the users environment in order for
9924: graph.png to plot it. Returns an <img> tag for the plot.
9925:
9926: Inputs:
9927:
9928: =over 4
9929:
9930: =item $Title: string, the title of the plot
9931:
9932: =item $xlabel: string, text describing the X-axis of the plot
9933:
9934: =item $ylabel: string, text describing the Y-axis of the plot
9935:
9936: =item $Max: scalar, the maximum Y value to use in the plot
9937: If $Max is < any data point, the graph will not be rendered.
9938:
9939: =item $colors: Array ref containing the hex color codes for the data to be
9940: plotted in. If undefined, default values will be used.
9941:
9942: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
9943:
9944: =item $Ydata: Array ref containing Array refs.
9945: Each of the contained arrays will be plotted as a separate curve.
9946:
9947: =item %Values: hash indicating or overriding any default values which are
9948: passed to graph.png.
9949: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
9950:
9951: =back
9952:
9953: Returns:
9954:
9955: An <img> tag which references graph.png and the appropriate identifying
9956: information for the plot.
9957:
9958: =cut
9959:
9960: ############################################################
9961: ############################################################
9962: sub DrawXYGraph {
9963: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
9964: #
9965: # Create the identifier for the graph
9966: my $identifier = &get_cgi_id();
9967: my $id = 'cgi.'.$identifier;
9968: #
9969: $Title = '' if (! defined($Title));
9970: $xlabel = '' if (! defined($xlabel));
9971: $ylabel = '' if (! defined($ylabel));
9972: my %ValuesHash =
9973: (
9974: $id.'.title' => &escape($Title),
9975: $id.'.xlabel' => &escape($xlabel),
9976: $id.'.ylabel' => &escape($ylabel),
9977: $id.'.y_max_value'=> $Max,
9978: $id.'.labels' => join(',',@$Xlabels),
9979: $id.'.PlotType' => 'XY',
9980: );
9981: #
9982: if (defined($colors) && ref($colors) eq 'ARRAY') {
9983: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
9984: }
9985: #
9986: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
9987: return '';
9988: }
9989: my $NumSets=1;
9990: foreach my $array (@{$Ydata}){
9991: next if (! ref($array));
9992: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
9993: }
9994: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
9995: #
9996: # Deal with other parameters
9997: while (my ($key,$value) = each(%Values)) {
9998: $ValuesHash{$id.'.'.$key} = $value;
9999: }
10000: #
10001: &Apache::lonnet::appenv(\%ValuesHash);
10002: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10003: }
10004:
10005: ############################################################
10006: ############################################################
10007:
10008: =pod
10009:
10010: =item * &DrawXYYGraph()
10011:
10012: Facilitates the plotting of data in an XY graph with two Y axes.
10013: Puts plot definition data into the users environment in order for
10014: graph.png to plot it. Returns an <img> tag for the plot.
10015:
10016: Inputs:
10017:
10018: =over 4
10019:
10020: =item $Title: string, the title of the plot
10021:
10022: =item $xlabel: string, text describing the X-axis of the plot
10023:
10024: =item $ylabel: string, text describing the Y-axis of the plot
10025:
10026: =item $colors: Array ref containing the hex color codes for the data to be
10027: plotted in. If undefined, default values will be used.
10028:
10029: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
10030:
10031: =item $Ydata1: The first data set
10032:
10033: =item $Min1: The minimum value of the left Y-axis
10034:
10035: =item $Max1: The maximum value of the left Y-axis
10036:
10037: =item $Ydata2: The second data set
10038:
10039: =item $Min2: The minimum value of the right Y-axis
10040:
10041: =item $Max2: The maximum value of the left Y-axis
10042:
10043: =item %Values: hash indicating or overriding any default values which are
10044: passed to graph.png.
10045: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
10046:
10047: =back
10048:
10049: Returns:
10050:
10051: An <img> tag which references graph.png and the appropriate identifying
10052: information for the plot.
10053:
10054: =cut
10055:
10056: ############################################################
10057: ############################################################
10058: sub DrawXYYGraph {
10059: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
10060: $Ydata2,$Min2,$Max2,%Values)=@_;
10061: #
10062: # Create the identifier for the graph
10063: my $identifier = &get_cgi_id();
10064: my $id = 'cgi.'.$identifier;
10065: #
10066: $Title = '' if (! defined($Title));
10067: $xlabel = '' if (! defined($xlabel));
10068: $ylabel = '' if (! defined($ylabel));
10069: my %ValuesHash =
10070: (
10071: $id.'.title' => &escape($Title),
10072: $id.'.xlabel' => &escape($xlabel),
10073: $id.'.ylabel' => &escape($ylabel),
10074: $id.'.labels' => join(',',@$Xlabels),
10075: $id.'.PlotType' => 'XY',
10076: $id.'.NumSets' => 2,
10077: $id.'.two_axes' => 1,
10078: $id.'.y1_max_value' => $Max1,
10079: $id.'.y1_min_value' => $Min1,
10080: $id.'.y2_max_value' => $Max2,
10081: $id.'.y2_min_value' => $Min2,
10082: );
10083: #
10084: if (defined($colors) && ref($colors) eq 'ARRAY') {
10085: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
10086: }
10087: #
10088: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
10089: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
10090: return '';
10091: }
10092: my $NumSets=1;
10093: foreach my $array ($Ydata1,$Ydata2){
10094: next if (! ref($array));
10095: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
10096: }
10097: #
10098: # Deal with other parameters
10099: while (my ($key,$value) = each(%Values)) {
10100: $ValuesHash{$id.'.'.$key} = $value;
10101: }
10102: #
10103: &Apache::lonnet::appenv(\%ValuesHash);
10104: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
10105: }
10106:
10107: ############################################################
10108: ############################################################
10109:
10110: =pod
10111:
10112: =back
10113:
10114: =head1 Statistics helper routines?
10115:
10116: Bad place for them but what the hell.
10117:
10118: =over 4
10119:
10120: =item * &chartlink()
10121:
10122: Returns a link to the chart for a specific student.
10123:
10124: Inputs:
10125:
10126: =over 4
10127:
10128: =item $linktext: The text of the link
10129:
10130: =item $sname: The students username
10131:
10132: =item $sdomain: The students domain
10133:
10134: =back
10135:
10136: =back
10137:
10138: =cut
10139:
10140: ############################################################
10141: ############################################################
10142: sub chartlink {
10143: my ($linktext, $sname, $sdomain) = @_;
10144: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
10145: '&SelectedStudent='.&escape($sname.':'.$sdomain).
10146: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
10147: '">'.$linktext.'</a>';
10148: }
10149:
10150: #######################################################
10151: #######################################################
10152:
10153: =pod
10154:
10155: =head1 Course Environment Routines
10156:
10157: =over 4
10158:
10159: =item * &restore_course_settings()
10160:
10161: =item * &store_course_settings()
10162:
10163: Restores/Store indicated form parameters from the course environment.
10164: Will not overwrite existing values of the form parameters.
10165:
10166: Inputs:
10167: a scalar describing the data (e.g. 'chart', 'problem_analysis')
10168:
10169: a hash ref describing the data to be stored. For example:
10170:
10171: %Save_Parameters = ('Status' => 'scalar',
10172: 'chartoutputmode' => 'scalar',
10173: 'chartoutputdata' => 'scalar',
10174: 'Section' => 'array',
10175: 'Group' => 'array',
10176: 'StudentData' => 'array',
10177: 'Maps' => 'array');
10178:
10179: Returns: both routines return nothing
10180:
10181: =back
10182:
10183: =cut
10184:
10185: #######################################################
10186: #######################################################
10187: sub store_course_settings {
10188: return &store_settings($env{'request.course.id'},@_);
10189: }
10190:
10191: sub store_settings {
10192: # save to the environment
10193: # appenv the same items, just to be safe
10194: my $udom = $env{'user.domain'};
10195: my $uname = $env{'user.name'};
10196: my ($context,$prefix,$Settings) = @_;
10197: my %SaveHash;
10198: my %AppHash;
10199: while (my ($setting,$type) = each(%$Settings)) {
10200: my $basename = join('.','internal',$context,$prefix,$setting);
10201: my $envname = 'environment.'.$basename;
10202: if (exists($env{'form.'.$setting})) {
10203: # Save this value away
10204: if ($type eq 'scalar' &&
10205: (! exists($env{$envname}) ||
10206: $env{$envname} ne $env{'form.'.$setting})) {
10207: $SaveHash{$basename} = $env{'form.'.$setting};
10208: $AppHash{$envname} = $env{'form.'.$setting};
10209: } elsif ($type eq 'array') {
10210: my $stored_form;
10211: if (ref($env{'form.'.$setting})) {
10212: $stored_form = join(',',
10213: map {
10214: &escape($_);
10215: } sort(@{$env{'form.'.$setting}}));
10216: } else {
10217: $stored_form =
10218: &escape($env{'form.'.$setting});
10219: }
10220: # Determine if the array contents are the same.
10221: if ($stored_form ne $env{$envname}) {
10222: $SaveHash{$basename} = $stored_form;
10223: $AppHash{$envname} = $stored_form;
10224: }
10225: }
10226: }
10227: }
10228: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
10229: $udom,$uname);
10230: if ($put_result !~ /^(ok|delayed)/) {
10231: &Apache::lonnet::logthis('unable to save form parameters, '.
10232: 'got error:'.$put_result);
10233: }
10234: # Make sure these settings stick around in this session, too
10235: &Apache::lonnet::appenv(\%AppHash);
10236: return;
10237: }
10238:
10239: sub restore_course_settings {
10240: return &restore_settings($env{'request.course.id'},@_);
10241: }
10242:
10243: sub restore_settings {
10244: my ($context,$prefix,$Settings) = @_;
10245: while (my ($setting,$type) = each(%$Settings)) {
10246: next if (exists($env{'form.'.$setting}));
10247: my $envname = 'environment.internal.'.$context.'.'.$prefix.
10248: '.'.$setting;
10249: if (exists($env{$envname})) {
10250: if ($type eq 'scalar') {
10251: $env{'form.'.$setting} = $env{$envname};
10252: } elsif ($type eq 'array') {
10253: $env{'form.'.$setting} = [
10254: map {
10255: &unescape($_);
10256: } split(',',$env{$envname})
10257: ];
10258: }
10259: }
10260: }
10261: }
10262:
10263: #######################################################
10264: #######################################################
10265:
10266: =pod
10267:
10268: =head1 Domain E-mail Routines
10269:
10270: =over 4
10271:
10272: =item * &build_recipient_list()
10273:
10274: Build recipient lists for five types of e-mail:
10275: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10276: (d) Help requests, (e) Course requests needing approval, generated by
10277: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10278: loncoursequeueadmin.pm respectively.
10279:
10280: Inputs:
10281: defmail (scalar - email address of default recipient),
10282: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
10283: defdom (domain for which to retrieve configuration settings),
10284: origmail (scalar - email address of recipient from loncapa.conf,
10285: i.e., predates configuration by DC via domainprefs.pm
10286:
10287: Returns: comma separated list of addresses to which to send e-mail.
10288:
10289: =back
10290:
10291: =cut
10292:
10293: ############################################################
10294: ############################################################
10295: sub build_recipient_list {
10296: my ($defmail,$mailing,$defdom,$origmail) = @_;
10297: my @recipients;
10298: my $otheremails;
10299: my %domconfig =
10300: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10301: if (ref($domconfig{'contacts'}) eq 'HASH') {
10302: if (exists($domconfig{'contacts'}{$mailing})) {
10303: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10304: my @contacts = ('adminemail','supportemail');
10305: foreach my $item (@contacts) {
10306: if ($domconfig{'contacts'}{$mailing}{$item}) {
10307: my $addr = $domconfig{'contacts'}{$item};
10308: if (!grep(/^\Q$addr\E$/,@recipients)) {
10309: push(@recipients,$addr);
10310: }
10311: }
10312: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10313: }
10314: }
10315: } elsif ($origmail ne '') {
10316: push(@recipients,$origmail);
10317: }
10318: } elsif ($origmail ne '') {
10319: push(@recipients,$origmail);
10320: }
10321: if (defined($defmail)) {
10322: if ($defmail ne '') {
10323: push(@recipients,$defmail);
10324: }
10325: }
10326: if ($otheremails) {
10327: my @others;
10328: if ($otheremails =~ /,/) {
10329: @others = split(/,/,$otheremails);
10330: } else {
10331: push(@others,$otheremails);
10332: }
10333: foreach my $addr (@others) {
10334: if (!grep(/^\Q$addr\E$/,@recipients)) {
10335: push(@recipients,$addr);
10336: }
10337: }
10338: }
10339: my $recipientlist = join(',',@recipients);
10340: return $recipientlist;
10341: }
10342:
10343: ############################################################
10344: ############################################################
10345:
10346: =pod
10347:
10348: =head1 Course Catalog Routines
10349:
10350: =over 4
10351:
10352: =item * &gather_categories()
10353:
10354: Converts category definitions - keys of categories hash stored in
10355: coursecategories in configuration.db on the primary library server in a
10356: domain - to an array. Also generates javascript and idx hash used to
10357: generate Domain Coordinator interface for editing Course Categories.
10358:
10359: Inputs:
10360:
10361: categories (reference to hash of category definitions).
10362:
10363: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10364: categories and subcategories).
10365:
10366: idx (reference to hash of counters used in Domain Coordinator interface for
10367: editing Course Categories).
10368:
10369: jsarray (reference to array of categories used to create Javascript arrays for
10370: Domain Coordinator interface for editing Course Categories).
10371:
10372: Returns: nothing
10373:
10374: Side effects: populates cats, idx and jsarray.
10375:
10376: =cut
10377:
10378: sub gather_categories {
10379: my ($categories,$cats,$idx,$jsarray) = @_;
10380: my %counters;
10381: my $num = 0;
10382: foreach my $item (keys(%{$categories})) {
10383: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10384: if ($container eq '' && $depth == 0) {
10385: $cats->[$depth][$categories->{$item}] = $cat;
10386: } else {
10387: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10388: }
10389: my ($escitem,$tail) = split(/:/,$item,2);
10390: if ($counters{$tail} eq '') {
10391: $counters{$tail} = $num;
10392: $num ++;
10393: }
10394: if (ref($idx) eq 'HASH') {
10395: $idx->{$item} = $counters{$tail};
10396: }
10397: if (ref($jsarray) eq 'ARRAY') {
10398: push(@{$jsarray->[$counters{$tail}]},$item);
10399: }
10400: }
10401: return;
10402: }
10403:
10404: =pod
10405:
10406: =item * &extract_categories()
10407:
10408: Used to generate breadcrumb trails for course categories.
10409:
10410: Inputs:
10411:
10412: categories (reference to hash of category definitions).
10413:
10414: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10415: categories and subcategories).
10416:
10417: trails (reference to array of breacrumb trails for each category).
10418:
10419: allitems (reference to hash - key is category key
10420: (format: escaped(name):escaped(parent category):depth in hierarchy).
10421:
10422: idx (reference to hash of counters used in Domain Coordinator interface for
10423: editing Course Categories).
10424:
10425: jsarray (reference to array of categories used to create Javascript arrays for
10426: Domain Coordinator interface for editing Course Categories).
10427:
10428: subcats (reference to hash of arrays containing all subcategories within each
10429: category, -recursive)
10430:
10431: Returns: nothing
10432:
10433: Side effects: populates trails and allitems hash references.
10434:
10435: =cut
10436:
10437: sub extract_categories {
10438: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10439: if (ref($categories) eq 'HASH') {
10440: &gather_categories($categories,$cats,$idx,$jsarray);
10441: if (ref($cats->[0]) eq 'ARRAY') {
10442: for (my $i=0; $i<@{$cats->[0]}; $i++) {
10443: my $name = $cats->[0][$i];
10444: my $item = &escape($name).'::0';
10445: my $trailstr;
10446: if ($name eq 'instcode') {
10447: $trailstr = &mt('Official courses (with institutional codes)');
10448: } elsif ($name eq 'communities') {
10449: $trailstr = &mt('Communities');
10450: } else {
10451: $trailstr = $name;
10452: }
10453: if ($allitems->{$item} eq '') {
10454: push(@{$trails},$trailstr);
10455: $allitems->{$item} = scalar(@{$trails})-1;
10456: }
10457: my @parents = ($name);
10458: if (ref($cats->[1]{$name}) eq 'ARRAY') {
10459: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10460: my $category = $cats->[1]{$name}[$j];
10461: if (ref($subcats) eq 'HASH') {
10462: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10463: }
10464: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10465: }
10466: } else {
10467: if (ref($subcats) eq 'HASH') {
10468: $subcats->{$item} = [];
10469: }
10470: }
10471: }
10472: }
10473: }
10474: return;
10475: }
10476:
10477: =pod
10478:
10479: =item *&recurse_categories()
10480:
10481: Recursively used to generate breadcrumb trails for course categories.
10482:
10483: Inputs:
10484:
10485: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10486: categories and subcategories).
10487:
10488: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10489:
10490: category (current course category, for which breadcrumb trail is being generated).
10491:
10492: trails (reference to array of breadcrumb trails for each category).
10493:
10494: allitems (reference to hash - key is category key
10495: (format: escaped(name):escaped(parent category):depth in hierarchy).
10496:
10497: parents (array containing containers directories for current category,
10498: back to top level).
10499:
10500: Returns: nothing
10501:
10502: Side effects: populates trails and allitems hash references
10503:
10504: =cut
10505:
10506: sub recurse_categories {
10507: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10508: my $shallower = $depth - 1;
10509: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10510: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10511: my $name = $cats->[$depth]{$category}[$k];
10512: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10513: my $trailstr = join(' -> ',(@{$parents},$category));
10514: if ($allitems->{$item} eq '') {
10515: push(@{$trails},$trailstr);
10516: $allitems->{$item} = scalar(@{$trails})-1;
10517: }
10518: my $deeper = $depth+1;
10519: push(@{$parents},$category);
10520: if (ref($subcats) eq 'HASH') {
10521: my $subcat = &escape($name).':'.$category.':'.$depth;
10522: for (my $j=@{$parents}; $j>=0; $j--) {
10523: my $higher;
10524: if ($j > 0) {
10525: $higher = &escape($parents->[$j]).':'.
10526: &escape($parents->[$j-1]).':'.$j;
10527: } else {
10528: $higher = &escape($parents->[$j]).'::'.$j;
10529: }
10530: push(@{$subcats->{$higher}},$subcat);
10531: }
10532: }
10533: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10534: $subcats);
10535: pop(@{$parents});
10536: }
10537: } else {
10538: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10539: my $trailstr = join(' -> ',(@{$parents},$category));
10540: if ($allitems->{$item} eq '') {
10541: push(@{$trails},$trailstr);
10542: $allitems->{$item} = scalar(@{$trails})-1;
10543: }
10544: }
10545: return;
10546: }
10547:
10548: =pod
10549:
10550: =item *&assign_categories_table()
10551:
10552: Create a datatable for display of hierarchical categories in a domain,
10553: with checkboxes to allow a course to be categorized.
10554:
10555: Inputs:
10556:
10557: cathash - reference to hash of categories defined for the domain (from
10558: configuration.db)
10559:
10560: currcat - scalar with an & separated list of categories assigned to a course.
10561:
10562: type - scalar contains course type (Course or Community).
10563:
10564: Returns: $output (markup to be displayed)
10565:
10566: =cut
10567:
10568: sub assign_categories_table {
10569: my ($cathash,$currcat,$type) = @_;
10570: my $output;
10571: if (ref($cathash) eq 'HASH') {
10572: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10573: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10574: $maxdepth = scalar(@cats);
10575: if (@cats > 0) {
10576: my $itemcount = 0;
10577: if (ref($cats[0]) eq 'ARRAY') {
10578: my @currcategories;
10579: if ($currcat ne '') {
10580: @currcategories = split('&',$currcat);
10581: }
10582: my $table;
10583: for (my $i=0; $i<@{$cats[0]}; $i++) {
10584: my $parent = $cats[0][$i];
10585: next if ($parent eq 'instcode');
10586: if ($type eq 'Community') {
10587: next unless ($parent eq 'communities');
10588: } else {
10589: next if ($parent eq 'communities');
10590: }
10591: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10592: my $item = &escape($parent).'::0';
10593: my $checked = '';
10594: if (@currcategories > 0) {
10595: if (grep(/^\Q$item\E$/,@currcategories)) {
10596: $checked = ' checked="checked"';
10597: }
10598: }
10599: my $parent_title = $parent;
10600: if ($parent eq 'communities') {
10601: $parent_title = &mt('Communities');
10602: }
10603: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10604: '<input type="checkbox" name="usecategory" value="'.
10605: $item.'"'.$checked.' />'.$parent_title.'</span>'.
10606: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10607: my $depth = 1;
10608: push(@path,$parent);
10609: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10610: pop(@path);
10611: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10612: $itemcount ++;
10613: }
10614: if ($itemcount) {
10615: $output = &Apache::loncommon::start_data_table().
10616: $table.
10617: &Apache::loncommon::end_data_table();
10618: }
10619: }
10620: }
10621: }
10622: return $output;
10623: }
10624:
10625: =pod
10626:
10627: =item *&assign_category_rows()
10628:
10629: Create a datatable row for display of nested categories in a domain,
10630: with checkboxes to allow a course to be categorized,called recursively.
10631:
10632: Inputs:
10633:
10634: itemcount - track row number for alternating colors
10635:
10636: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10637: categories and subcategories.
10638:
10639: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10640:
10641: parent - parent of current category item
10642:
10643: path - Array containing all categories back up through the hierarchy from the
10644: current category to the top level.
10645:
10646: currcategories - reference to array of current categories assigned to the course
10647:
10648: Returns: $output (markup to be displayed).
10649:
10650: =cut
10651:
10652: sub assign_category_rows {
10653: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10654: my ($text,$name,$item,$chgstr);
10655: if (ref($cats) eq 'ARRAY') {
10656: my $maxdepth = scalar(@{$cats});
10657: if (ref($cats->[$depth]) eq 'HASH') {
10658: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10659: my $numchildren = @{$cats->[$depth]{$parent}};
10660: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10661: $text .= '<td><table class="LC_datatable">';
10662: for (my $j=0; $j<$numchildren; $j++) {
10663: $name = $cats->[$depth]{$parent}[$j];
10664: $item = &escape($name).':'.&escape($parent).':'.$depth;
10665: my $deeper = $depth+1;
10666: my $checked = '';
10667: if (ref($currcategories) eq 'ARRAY') {
10668: if (@{$currcategories} > 0) {
10669: if (grep(/^\Q$item\E$/,@{$currcategories})) {
10670: $checked = ' checked="checked"';
10671: }
10672: }
10673: }
10674: $text .= '<tr><td><span class="LC_nobreak"><label>'.
10675: '<input type="checkbox" name="usecategory" value="'.
10676: $item.'"'.$checked.' />'.$name.'</label></span>'.
10677: '<input type="hidden" name="catname" value="'.$name.'" />'.
10678: '</td><td>';
10679: if (ref($path) eq 'ARRAY') {
10680: push(@{$path},$name);
10681: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10682: pop(@{$path});
10683: }
10684: $text .= '</td></tr>';
10685: }
10686: $text .= '</table></td>';
10687: }
10688: }
10689: }
10690: return $text;
10691: }
10692:
10693: ############################################################
10694: ############################################################
10695:
10696:
10697: sub commit_customrole {
10698: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10699: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10700: ($start?', '.&mt('starting').' '.localtime($start):'').
10701: ($end?', ending '.localtime($end):'').': <b>'.
10702: &Apache::lonnet::assigncustomrole(
10703: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10704: '</b><br />';
10705: return $output;
10706: }
10707:
10708: sub commit_standardrole {
10709: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10710: my ($output,$logmsg,$linefeed);
10711: if ($context eq 'auto') {
10712: $linefeed = "\n";
10713: } else {
10714: $linefeed = "<br />\n";
10715: }
10716: if ($three eq 'st') {
10717: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10718: $one,$two,$sec,$context);
10719: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
10720: ($result eq 'unknown_course') || ($result eq 'refused')) {
10721: $output = $logmsg.' '.&mt('Error: ').$result."\n";
10722: } else {
10723: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10724: ($start?', '.&mt('starting').' '.localtime($start):'').
10725: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10726: if ($context eq 'auto') {
10727: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10728: } else {
10729: $output .= '<b>'.$result.'</b>'.$linefeed.
10730: &mt('Add to classlist').': <b>ok</b>';
10731: }
10732: $output .= $linefeed;
10733: }
10734: } else {
10735: $output = &mt('Assigning').' '.$three.' in '.$url.
10736: ($start?', '.&mt('starting').' '.localtime($start):'').
10737: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10738: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10739: if ($context eq 'auto') {
10740: $output .= $result.$linefeed;
10741: } else {
10742: $output .= '<b>'.$result.'</b>'.$linefeed;
10743: }
10744: }
10745: return $output;
10746: }
10747:
10748: sub commit_studentrole {
10749: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10750: my ($result,$linefeed,$oldsecurl,$newsecurl);
10751: if ($context eq 'auto') {
10752: $linefeed = "\n";
10753: } else {
10754: $linefeed = '<br />'."\n";
10755: }
10756: if (defined($one) && defined($two)) {
10757: my $cid=$one.'_'.$two;
10758: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10759: my $secchange = 0;
10760: my $expire_role_result;
10761: my $modify_section_result;
10762: if ($oldsec ne '-1') {
10763: if ($oldsec ne $sec) {
10764: $secchange = 1;
10765: my $now = time;
10766: my $uurl='/'.$cid;
10767: $uurl=~s/\_/\//g;
10768: if ($oldsec) {
10769: $uurl.='/'.$oldsec;
10770: }
10771: $oldsecurl = $uurl;
10772: $expire_role_result =
10773: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10774: if ($env{'request.course.sec'} ne '') {
10775: if ($expire_role_result eq 'refused') {
10776: my @roles = ('st');
10777: my @statuses = ('previous');
10778: my @roledoms = ($one);
10779: my $withsec = 1;
10780: my %roleshash =
10781: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10782: \@statuses,\@roles,\@roledoms,$withsec);
10783: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10784: my ($oldstart,$oldend) =
10785: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10786: if ($oldend > 0 && $oldend <= $now) {
10787: $expire_role_result = 'ok';
10788: }
10789: }
10790: }
10791: }
10792: $result = $expire_role_result;
10793: }
10794: }
10795: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10796: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10797: if ($modify_section_result =~ /^ok/) {
10798: if ($secchange == 1) {
10799: if ($sec eq '') {
10800: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10801: } else {
10802: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10803: }
10804: } elsif ($oldsec eq '-1') {
10805: if ($sec eq '') {
10806: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10807: } else {
10808: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10809: }
10810: } else {
10811: if ($sec eq '') {
10812: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10813: } else {
10814: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10815: }
10816: }
10817: } else {
10818: if ($secchange) {
10819: $$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;
10820: } else {
10821: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10822: }
10823: }
10824: $result = $modify_section_result;
10825: } elsif ($secchange == 1) {
10826: if ($oldsec eq '') {
10827: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10828: } else {
10829: $$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;
10830: }
10831: if ($expire_role_result eq 'refused') {
10832: my $newsecurl = '/'.$cid;
10833: $newsecurl =~ s/\_/\//g;
10834: if ($sec ne '') {
10835: $newsecurl.='/'.$sec;
10836: }
10837: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10838: if ($sec eq '') {
10839: $$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;
10840: } else {
10841: $$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;
10842: }
10843: }
10844: }
10845: }
10846: } else {
10847: $$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;
10848: $result = "error: incomplete course id\n";
10849: }
10850: return $result;
10851: }
10852:
10853: ############################################################
10854: ############################################################
10855:
10856: sub check_clone {
10857: my ($args,$linefeed) = @_;
10858: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10859: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10860: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10861: my $clonemsg;
10862: my $can_clone = 0;
10863: my $lctype = lc($args->{'crstype'});
10864: if ($lctype ne 'community') {
10865: $lctype = 'course';
10866: }
10867: if ($clonehome eq 'no_host') {
10868: if ($args->{'crstype'} eq 'Community') {
10869: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10870: } else {
10871: $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'});
10872: }
10873: } else {
10874: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10875: if ($args->{'crstype'} eq 'Community') {
10876: if ($clonedesc{'type'} ne 'Community') {
10877: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10878: return ($can_clone, $clonemsg, $cloneid, $clonehome);
10879: }
10880: }
10881: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
10882: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10883: $can_clone = 1;
10884: } else {
10885: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10886: $args->{'clonedomain'},$args->{'clonecourse'});
10887: my @cloners = split(/,/,$clonehash{'cloners'});
10888: if (grep(/^\*$/,@cloners)) {
10889: $can_clone = 1;
10890: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10891: $can_clone = 1;
10892: } else {
10893: my $ccrole = 'cc';
10894: if ($args->{'crstype'} eq 'Community') {
10895: $ccrole = 'co';
10896: }
10897: my %roleshash =
10898: &Apache::lonnet::get_my_roles($args->{'ccuname'},
10899: $args->{'ccdomain'},
10900: 'userroles',['active'],[$ccrole],
10901: [$args->{'clonedomain'}]);
10902: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10903: $can_clone = 1;
10904: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10905: $can_clone = 1;
10906: } else {
10907: if ($args->{'crstype'} eq 'Community') {
10908: $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
10909: } else {
10910: $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'});
10911: }
10912: }
10913: }
10914: }
10915: }
10916: return ($can_clone, $clonemsg, $cloneid, $clonehome);
10917: }
10918:
10919: sub construct_course {
10920: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10921: my $outcome;
10922: my $linefeed = '<br />'."\n";
10923: if ($context eq 'auto') {
10924: $linefeed = "\n";
10925: }
10926:
10927: #
10928: # Are we cloning?
10929: #
10930: my ($can_clone, $clonemsg, $cloneid, $clonehome);
10931: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10932: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10933: if ($context ne 'auto') {
10934: if ($clonemsg ne '') {
10935: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10936: }
10937: }
10938: $outcome .= $clonemsg.$linefeed;
10939:
10940: if (!$can_clone) {
10941: return (0,$outcome);
10942: }
10943: }
10944:
10945: #
10946: # Open course
10947: #
10948: my $crstype = lc($args->{'crstype'});
10949: my %cenv=();
10950: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10951: $args->{'cdescr'},
10952: $args->{'curl'},
10953: $args->{'course_home'},
10954: $args->{'nonstandard'},
10955: $args->{'crscode'},
10956: $args->{'ccuname'}.':'.
10957: $args->{'ccdomain'},
10958: $args->{'crstype'},
10959: $cnum,$context,$category);
10960:
10961: # Note: The testing routines depend on this being output; see
10962: # Utils::Course. This needs to at least be output as a comment
10963: # if anyone ever decides to not show this, and Utils::Course::new
10964: # will need to be suitably modified.
10965: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10966: if ($$courseid =~ /^error:/) {
10967: return (0,$outcome);
10968: }
10969:
10970: #
10971: # Check if created correctly
10972: #
10973: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10974: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10975: if ($crsuhome eq 'no_host') {
10976: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10977: return (0,$outcome);
10978: }
10979: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10980:
10981: #
10982: # Do the cloning
10983: #
10984: if ($can_clone && $cloneid) {
10985: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10986: if ($context ne 'auto') {
10987: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10988: }
10989: $outcome .= $clonemsg.$linefeed;
10990: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10991: # Copy all files
10992: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10993: # Restore URL
10994: $cenv{'url'}=$oldcenv{'url'};
10995: # Restore title
10996: $cenv{'description'}=$oldcenv{'description'};
10997: # Restore creation date, creator and creation context.
10998: $cenv{'internal.created'}=$oldcenv{'internal.created'};
10999: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
11000: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
11001: # Mark as cloned
11002: $cenv{'clonedfrom'}=$cloneid;
11003: # Need to clone grading mode
11004: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
11005: $cenv{'grading'}=$newenv{'grading'};
11006: # Do not clone these environment entries
11007: &Apache::lonnet::del('environment',
11008: ['default_enrollment_start_date',
11009: 'default_enrollment_end_date',
11010: 'question.email',
11011: 'policy.email',
11012: 'comment.email',
11013: 'pch.users.denied',
11014: 'plc.users.denied',
11015: 'hidefromcat',
11016: 'categories'],
11017: $$crsudom,$$crsunum);
11018: }
11019:
11020: #
11021: # Set environment (will override cloned, if existing)
11022: #
11023: my @sections = ();
11024: my @xlists = ();
11025: if ($args->{'crstype'}) {
11026: $cenv{'type'}=$args->{'crstype'};
11027: }
11028: if ($args->{'crsid'}) {
11029: $cenv{'courseid'}=$args->{'crsid'};
11030: }
11031: if ($args->{'crscode'}) {
11032: $cenv{'internal.coursecode'}=$args->{'crscode'};
11033: }
11034: if ($args->{'crsquota'} ne '') {
11035: $cenv{'internal.coursequota'}=$args->{'crsquota'};
11036: } else {
11037: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
11038: }
11039: if ($args->{'ccuname'}) {
11040: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
11041: ':'.$args->{'ccdomain'};
11042: } else {
11043: $cenv{'internal.courseowner'} = $args->{'curruser'};
11044: }
11045: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
11046: if ($args->{'crssections'}) {
11047: $cenv{'internal.sectionnums'} = '';
11048: if ($args->{'crssections'} =~ m/,/) {
11049: @sections = split/,/,$args->{'crssections'};
11050: } else {
11051: $sections[0] = $args->{'crssections'};
11052: }
11053: if (@sections > 0) {
11054: foreach my $item (@sections) {
11055: my ($sec,$gp) = split/:/,$item;
11056: my $class = $args->{'crscode'}.$sec;
11057: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
11058: $cenv{'internal.sectionnums'} .= $item.',';
11059: unless ($addcheck eq 'ok') {
11060: push @badclasses, $class;
11061: }
11062: }
11063: $cenv{'internal.sectionnums'} =~ s/,$//;
11064: }
11065: }
11066: # do not hide course coordinator from staff listing,
11067: # even if privileged
11068: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11069: # add crosslistings
11070: if ($args->{'crsxlist'}) {
11071: $cenv{'internal.crosslistings'}='';
11072: if ($args->{'crsxlist'} =~ m/,/) {
11073: @xlists = split/,/,$args->{'crsxlist'};
11074: } else {
11075: $xlists[0] = $args->{'crsxlist'};
11076: }
11077: if (@xlists > 0) {
11078: foreach my $item (@xlists) {
11079: my ($xl,$gp) = split/:/,$item;
11080: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
11081: $cenv{'internal.crosslistings'} .= $item.',';
11082: unless ($addcheck eq 'ok') {
11083: push @badclasses, $xl;
11084: }
11085: }
11086: $cenv{'internal.crosslistings'} =~ s/,$//;
11087: }
11088: }
11089: if ($args->{'autoadds'}) {
11090: $cenv{'internal.autoadds'}=$args->{'autoadds'};
11091: }
11092: if ($args->{'autodrops'}) {
11093: $cenv{'internal.autodrops'}=$args->{'autodrops'};
11094: }
11095: # check for notification of enrollment changes
11096: my @notified = ();
11097: if ($args->{'notify_owner'}) {
11098: if ($args->{'ccuname'} ne '') {
11099: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
11100: }
11101: }
11102: if ($args->{'notify_dc'}) {
11103: if ($uname ne '') {
11104: push(@notified,$uname.':'.$udom);
11105: }
11106: }
11107: if (@notified > 0) {
11108: my $notifylist;
11109: if (@notified > 1) {
11110: $notifylist = join(',',@notified);
11111: } else {
11112: $notifylist = $notified[0];
11113: }
11114: $cenv{'internal.notifylist'} = $notifylist;
11115: }
11116: if (@badclasses > 0) {
11117: my %lt=&Apache::lonlocal::texthash(
11118: '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',
11119: 'dnhr' => 'does not have rights to access enrollment in these classes',
11120: 'adby' => 'as determined by the policies of your institution on access to official classlists'
11121: );
11122: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
11123: ' ('.$lt{'adby'}.')';
11124: if ($context eq 'auto') {
11125: $outcome .= $badclass_msg.$linefeed;
11126: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
11127: foreach my $item (@badclasses) {
11128: if ($context eq 'auto') {
11129: $outcome .= " - $item\n";
11130: } else {
11131: $outcome .= "<li>$item</li>\n";
11132: }
11133: }
11134: if ($context eq 'auto') {
11135: $outcome .= $linefeed;
11136: } else {
11137: $outcome .= "</ul><br /><br /></div>\n";
11138: }
11139: }
11140: }
11141: if ($args->{'no_end_date'}) {
11142: $args->{'endaccess'} = 0;
11143: }
11144: $cenv{'internal.autostart'}=$args->{'enrollstart'};
11145: $cenv{'internal.autoend'}=$args->{'enrollend'};
11146: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
11147: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
11148: if ($args->{'showphotos'}) {
11149: $cenv{'internal.showphotos'}=$args->{'showphotos'};
11150: }
11151: $cenv{'internal.authtype'} = $args->{'authtype'};
11152: $cenv{'internal.autharg'} = $args->{'autharg'};
11153: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
11154: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
11155: 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');
11156: if ($context eq 'auto') {
11157: $outcome .= $krb_msg;
11158: } else {
11159: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
11160: }
11161: $outcome .= $linefeed;
11162: }
11163: }
11164: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
11165: if ($args->{'setpolicy'}) {
11166: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11167: }
11168: if ($args->{'setcontent'}) {
11169: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
11170: }
11171: }
11172: if ($args->{'reshome'}) {
11173: $cenv{'reshome'}=$args->{'reshome'}.'/';
11174: $cenv{'reshome'}=~s/\/+$/\//;
11175: }
11176: #
11177: # course has keyed access
11178: #
11179: if ($args->{'setkeys'}) {
11180: $cenv{'keyaccess'}='yes';
11181: }
11182: # if specified, key authority is not course, but user
11183: # only active if keyaccess is yes
11184: if ($args->{'keyauth'}) {
11185: my ($user,$domain) = split(':',$args->{'keyauth'});
11186: $user = &LONCAPA::clean_username($user);
11187: $domain = &LONCAPA::clean_username($domain);
11188: if ($user ne '' && $domain ne '') {
11189: $cenv{'keyauth'}=$user.':'.$domain;
11190: }
11191: }
11192:
11193: if ($args->{'disresdis'}) {
11194: $cenv{'pch.roles.denied'}='st';
11195: }
11196: if ($args->{'disablechat'}) {
11197: $cenv{'plc.roles.denied'}='st';
11198: }
11199:
11200: # Record we've not yet viewed the Course Initialization Helper for this
11201: # course
11202: $cenv{'course.helper.not.run'} = 1;
11203: #
11204: # Use new Randomseed
11205: #
11206: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
11207: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
11208: #
11209: # The encryption code and receipt prefix for this course
11210: #
11211: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
11212: $cenv{'internal.encpref'}=100+int(9*rand(99));
11213: #
11214: # By default, use standard grading
11215: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
11216:
11217: $outcome .= $linefeed.&mt('Setting environment').': '.
11218: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
11219: #
11220: # Open all assignments
11221: #
11222: if ($args->{'openall'}) {
11223: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
11224: my %storecontent = ($storeunder => time,
11225: $storeunder.'.type' => 'date_start');
11226:
11227: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
11228: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
11229: }
11230: #
11231: # Set first page
11232: #
11233: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11234: || ($cloneid)) {
11235: use LONCAPA::map;
11236: $outcome .= &mt('Setting first resource').': ';
11237:
11238: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11239: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11240:
11241: $outcome .= ($fatal?$errtext:'read ok').' - ';
11242: my $title; my $url;
11243: if ($args->{'firstres'} eq 'syl') {
11244: $title=&mt('Syllabus');
11245: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11246: } else {
11247: $title=&mt('Table of Contents');
11248: $url='/adm/navmaps';
11249: }
11250:
11251: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11252: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11253:
11254: if ($errtext) { $fatal=2; }
11255: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11256: }
11257:
11258: return (1,$outcome);
11259: }
11260:
11261: ############################################################
11262: ############################################################
11263:
11264: #SD
11265: # only Community and Course, or anything else?
11266: sub course_type {
11267: my ($cid) = @_;
11268: if (!defined($cid)) {
11269: $cid = $env{'request.course.id'};
11270: }
11271: if (defined($env{'course.'.$cid.'.type'})) {
11272: return $env{'course.'.$cid.'.type'};
11273: } else {
11274: return 'Course';
11275: }
11276: }
11277:
11278: sub group_term {
11279: my $crstype = &course_type();
11280: my %names = (
11281: 'Course' => 'group',
11282: 'Community' => 'group',
11283: );
11284: return $names{$crstype};
11285: }
11286:
11287: sub course_types {
11288: my @types = ('official','unofficial','community');
11289: my %typename = (
11290: official => 'Official course',
11291: unofficial => 'Unofficial course',
11292: community => 'Community',
11293: );
11294: return (\@types,\%typename);
11295: }
11296:
11297: sub icon {
11298: my ($file)=@_;
11299: my $curfext = lc((split(/\./,$file))[-1]);
11300: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11301: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11302: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11303: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11304: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11305: $curfext.".gif") {
11306: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11307: $curfext.".gif";
11308: }
11309: }
11310: return &lonhttpdurl($iconname);
11311: }
11312:
11313: sub lonhttpdurl {
11314: #
11315: # Had been used for "small fry" static images on separate port 8080.
11316: # Modify here if lightweight http functionality desired again.
11317: # Currently eliminated due to increasing firewall issues.
11318: #
11319: my ($url)=@_;
11320: return $url;
11321: }
11322:
11323: sub connection_aborted {
11324: my ($r)=@_;
11325: $r->print(" ");$r->rflush();
11326: my $c = $r->connection;
11327: return $c->aborted();
11328: }
11329:
11330: # Escapes strings that may have embedded 's that will be put into
11331: # strings as 'strings'.
11332: sub escape_single {
11333: my ($input) = @_;
11334: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
11335: $input =~ s/\'/\\\'/g; # Esacpe the 's....
11336: return $input;
11337: }
11338:
11339: # Same as escape_single, but escape's "'s This
11340: # can be used for "strings"
11341: sub escape_double {
11342: my ($input) = @_;
11343: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
11344: $input =~ s/\"/\\\"/g; # Esacpe the "s....
11345: return $input;
11346: }
11347:
11348: # Escapes the last element of a full URL.
11349: sub escape_url {
11350: my ($url) = @_;
11351: my @urlslices = split(/\//, $url,-1);
11352: my $lastitem = &escape(pop(@urlslices));
11353: return join('/',@urlslices).'/'.$lastitem;
11354: }
11355:
11356: sub compare_arrays {
11357: my ($arrayref1,$arrayref2) = @_;
11358: my (@difference,%count);
11359: @difference = ();
11360: %count = ();
11361: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11362: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11363: foreach my $element (keys(%count)) {
11364: if ($count{$element} == 1) {
11365: push(@difference,$element);
11366: }
11367: }
11368: }
11369: return @difference;
11370: }
11371:
11372: # -------------------------------------------------------- Initialize user login
11373: sub init_user_environment {
11374: my ($r, $username, $domain, $authhost, $form, $args) = @_;
11375: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11376:
11377: my $public=($username eq 'public' && $domain eq 'public');
11378:
11379: # See if old ID present, if so, remove
11380:
11381: my ($filename,$cookie,$userroles);
11382: my $now=time;
11383:
11384: if ($public) {
11385: my $max_public=100;
11386: my $oldest;
11387: my $oldest_time=0;
11388: for(my $next=1;$next<=$max_public;$next++) {
11389: if (-e $lonids."/publicuser_$next.id") {
11390: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11391: if ($mtime<$oldest_time || !$oldest_time) {
11392: $oldest_time=$mtime;
11393: $oldest=$next;
11394: }
11395: } else {
11396: $cookie="publicuser_$next";
11397: last;
11398: }
11399: }
11400: if (!$cookie) { $cookie="publicuser_$oldest"; }
11401: } else {
11402: # if this isn't a robot, kill any existing non-robot sessions
11403: if (!$args->{'robot'}) {
11404: opendir(DIR,$lonids);
11405: while ($filename=readdir(DIR)) {
11406: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11407: unlink($lonids.'/'.$filename);
11408: }
11409: }
11410: closedir(DIR);
11411: }
11412: # Give them a new cookie
11413: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11414: : $now.$$.int(rand(10000)));
11415: $cookie="$username\_$id\_$domain\_$authhost";
11416:
11417: # Initialize roles
11418:
11419: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11420: }
11421: # ------------------------------------ Check browser type and MathML capability
11422:
11423: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11424: $clientunicode,$clientos) = &decode_user_agent($r);
11425:
11426: # ------------------------------------------------------------- Get environment
11427:
11428: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11429: my ($tmp) = keys(%userenv);
11430: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11431: } else {
11432: undef(%userenv);
11433: }
11434: if (($userenv{'interface'}) && (!$form->{'interface'})) {
11435: $form->{'interface'}=$userenv{'interface'};
11436: }
11437: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11438:
11439: # --------------- Do not trust query string to be put directly into environment
11440: foreach my $option ('interface','localpath','localres') {
11441: $form->{$option}=~s/[\n\r\=]//gs;
11442: }
11443: # --------------------------------------------------------- Write first profile
11444:
11445: {
11446: my %initial_env =
11447: ("user.name" => $username,
11448: "user.domain" => $domain,
11449: "user.home" => $authhost,
11450: "browser.type" => $clientbrowser,
11451: "browser.version" => $clientversion,
11452: "browser.mathml" => $clientmathml,
11453: "browser.unicode" => $clientunicode,
11454: "browser.os" => $clientos,
11455: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
11456: "request.course.fn" => '',
11457: "request.course.uri" => '',
11458: "request.course.sec" => '',
11459: "request.role" => 'cm',
11460: "request.role.adv" => $env{'user.adv'},
11461: "request.host" => $ENV{'REMOTE_ADDR'},);
11462:
11463: if ($form->{'localpath'}) {
11464: $initial_env{"browser.localpath"} = $form->{'localpath'};
11465: $initial_env{"browser.localres"} = $form->{'localres'};
11466: }
11467:
11468: if ($form->{'interface'}) {
11469: $form->{'interface'}=~s/\W//gs;
11470: $initial_env{"browser.interface"} = $form->{'interface'};
11471: $env{'browser.interface'}=$form->{'interface'};
11472: }
11473:
11474: my %is_adv = ( is_adv => $env{'user.adv'} );
11475: my %domdef;
11476: unless ($domain eq 'public') {
11477: %domdef = &Apache::lonnet::get_domain_defaults($domain);
11478: }
11479:
11480: foreach my $tool ('aboutme','blog','portfolio') {
11481: $userenv{'availabletools.'.$tool} =
11482: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11483: undef,\%userenv,\%domdef,\%is_adv);
11484: }
11485:
11486: foreach my $crstype ('official','unofficial','community') {
11487: $userenv{'canrequest.'.$crstype} =
11488: &Apache::lonnet::usertools_access($username,$domain,$crstype,
11489: 'reload','requestcourses',
11490: \%userenv,\%domdef,\%is_adv);
11491: }
11492:
11493: $env{'user.environment'} = "$lonids/$cookie.id";
11494:
11495: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11496: &GDBM_WRCREAT(),0640)) {
11497: &_add_to_env(\%disk_env,\%initial_env);
11498: &_add_to_env(\%disk_env,\%userenv,'environment.');
11499: &_add_to_env(\%disk_env,$userroles);
11500: if (ref($args->{'extra_env'})) {
11501: &_add_to_env(\%disk_env,$args->{'extra_env'});
11502: }
11503: untie(%disk_env);
11504: } else {
11505: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11506: 'Could not create environment storage in lonauth: '.$!.'</span>');
11507: return 'error: '.$!;
11508: }
11509: }
11510: $env{'request.role'}='cm';
11511: $env{'request.role.adv'}=$env{'user.adv'};
11512: $env{'browser.type'}=$clientbrowser;
11513:
11514: return $cookie;
11515:
11516: }
11517:
11518: sub _add_to_env {
11519: my ($idf,$env_data,$prefix) = @_;
11520: if (ref($env_data) eq 'HASH') {
11521: while (my ($key,$value) = each(%$env_data)) {
11522: $idf->{$prefix.$key} = $value;
11523: $env{$prefix.$key} = $value;
11524: }
11525: }
11526: }
11527:
11528: # --- Get the symbolic name of a problem and the url
11529: sub get_symb {
11530: my ($request,$silent) = @_;
11531: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11532: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11533: if ($symb eq '') {
11534: if (!$silent) {
11535: $request->print("Unable to handle ambiguous references:$url:.");
11536: return ();
11537: }
11538: }
11539: &Apache::lonenc::check_decrypt(\$symb);
11540: return ($symb);
11541: }
11542:
11543: # --------------------------------------------------------------Get annotation
11544:
11545: sub get_annotation {
11546: my ($symb,$enc) = @_;
11547:
11548: my $key = $symb;
11549: if (!$enc) {
11550: $key =
11551: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11552: }
11553: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11554: return $annotation{$key};
11555: }
11556:
11557: sub clean_symb {
11558: my ($symb,$delete_enc) = @_;
11559:
11560: &Apache::lonenc::check_decrypt(\$symb);
11561: my $enc = $env{'request.enc'};
11562: if ($delete_enc) {
11563: delete($env{'request.enc'});
11564: }
11565:
11566: return ($symb,$enc);
11567: }
11568:
11569: sub build_release_hashes {
11570: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11571: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11572: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11573: (ref($randomizetry) eq 'HASH'));
11574: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11575: my ($item,$name,$value) = split(/:/,$key);
11576: if ($item eq 'parameter') {
11577: if (ref($checkparms->{$name}) eq 'ARRAY') {
11578: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11579: push(@{$checkparms->{$name}},$value);
11580: }
11581: } else {
11582: push(@{$checkparms->{$name}},$value);
11583: }
11584: } elsif ($item eq 'resourcetag') {
11585: if ($name eq 'responsetype') {
11586: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11587: }
11588: } elsif ($item eq 'course') {
11589: if ($name eq 'crstype') {
11590: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11591: }
11592: }
11593: }
11594: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11595: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11596: return;
11597: }
11598:
11599: =pod
11600:
11601: =back
11602:
11603: =cut
11604:
11605: 1;
11606: __END__;
11607:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>