File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1066:
download - view:
text,
annotated -
select for diffs
Fri Apr 6 01:23:11 2012 UTC (12 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Extraction of contents of archive files (zip, tar etc.) from a file
uploaded directly to a course.
- Add new routine: &cleanup_empty_dirs()
to remove empty directories remaining after processing user's selections
for display, treating as a dependency or discard, for each item extracted
from the archive file.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1066 2012/04/06 01:23:11 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use LONCAPA qw(:DEFAULT :match);
71: use DateTime::TimeZone;
72: use DateTime::Locale::Catalog;
73:
74: # ---------------------------------------------- Designs
75: use vars qw(%defaultdesign);
76:
77: my $readit;
78:
79:
80: ##
81: ## Global Variables
82: ##
83:
84:
85: # ----------------------------------------------- SSI with retries:
86: #
87:
88: =pod
89:
90: =head1 Server Side include with retries:
91:
92: =over 4
93:
94: =item * &ssi_with_retries(resource,retries form)
95:
96: Performs an ssi with some number of retries. Retries continue either
97: until the result is ok or until the retry count supplied by the
98: caller is exhausted.
99:
100: Inputs:
101:
102: =over 4
103:
104: resource - Identifies the resource to insert.
105:
106: retries - Count of the number of retries allowed.
107:
108: form - Hash that identifies the rendering options.
109:
110: =back
111:
112: Returns:
113:
114: =over 4
115:
116: content - The content of the response. If retries were exhausted this is empty.
117:
118: response - The response from the last attempt (which may or may not have been successful.
119:
120: =back
121:
122: =back
123:
124: =cut
125:
126: sub ssi_with_retries {
127: my ($resource, $retries, %form) = @_;
128:
129:
130: my $ok = 0; # True if we got a good response.
131: my $content;
132: my $response;
133:
134: # Try to get the ssi done. within the retries count:
135:
136: do {
137: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
138: $ok = $response->is_success;
139: if (!$ok) {
140: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
141: }
142: $retries--;
143: } while (!$ok && ($retries > 0));
144:
145: if (!$ok) {
146: $content = ''; # On error return an empty content.
147: }
148: return ($content, $response);
149:
150: }
151:
152:
153:
154: # ----------------------------------------------- Filetypes/Languages/Copyright
155: my %language;
156: my %supported_language;
157: my %latex_language; # For choosing hyphenation in <transl..>
158: my %latex_language_bykey; # for choosing hyphenation from metadata
159: my %cprtag;
160: my %scprtag;
161: my %fe; my %fd; my %fm;
162: my %category_extensions;
163:
164: # ---------------------------------------------- Thesaurus variables
165: #
166: # %Keywords:
167: # A hash used by &keyword to determine if a word is considered a keyword.
168: # $thesaurus_db_file
169: # Scalar containing the full path to the thesaurus database.
170:
171: my %Keywords;
172: my $thesaurus_db_file;
173:
174: #
175: # Initialize values from language.tab, copyright.tab, filetypes.tab,
176: # thesaurus.tab, and filecategories.tab.
177: #
178: BEGIN {
179: # Variable initialization
180: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
181: #
182: unless ($readit) {
183: # ------------------------------------------------------------------- languages
184: {
185: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
186: '/language.tab';
187: if ( open(my $fh,"<$langtabfile") ) {
188: while (my $line = <$fh>) {
189: next if ($line=~/^\#/);
190: chomp($line);
191: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
192: $language{$key}=$val.' - '.$enc;
193: if ($sup) {
194: $supported_language{$key}=$sup;
195: }
196: if ($latex) {
197: $latex_language_bykey{$key} = $latex;
198: $latex_language{$two} = $latex;
199: }
200: }
201: close($fh);
202: }
203: }
204: # ------------------------------------------------------------------ copyrights
205: {
206: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
207: '/copyright.tab';
208: if ( open (my $fh,"<$copyrightfile") ) {
209: while (my $line = <$fh>) {
210: next if ($line=~/^\#/);
211: chomp($line);
212: my ($key,$val)=(split(/\s+/,$line,2));
213: $cprtag{$key}=$val;
214: }
215: close($fh);
216: }
217: }
218: # ----------------------------------------------------------- source copyrights
219: {
220: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
221: '/source_copyright.tab';
222: if ( open (my $fh,"<$sourcecopyrightfile") ) {
223: while (my $line = <$fh>) {
224: next if ($line =~ /^\#/);
225: chomp($line);
226: my ($key,$val)=(split(/\s+/,$line,2));
227: $scprtag{$key}=$val;
228: }
229: close($fh);
230: }
231: }
232:
233: # -------------------------------------------------------------- default domain designs
234: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
235: my $designfile = $designdir.'/default.tab';
236: if ( open (my $fh,"<$designfile") ) {
237: while (my $line = <$fh>) {
238: next if ($line =~ /^\#/);
239: chomp($line);
240: my ($key,$val)=(split(/\=/,$line));
241: if ($val) { $defaultdesign{$key}=$val; }
242: }
243: close($fh);
244: }
245:
246: # ------------------------------------------------------------- file categories
247: {
248: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
249: '/filecategories.tab';
250: if ( open (my $fh,"<$categoryfile") ) {
251: while (my $line = <$fh>) {
252: next if ($line =~ /^\#/);
253: chomp($line);
254: my ($extension,$category)=(split(/\s+/,$line,2));
255: push @{$category_extensions{lc($category)}},$extension;
256: }
257: close($fh);
258: }
259:
260: }
261: # ------------------------------------------------------------------ file types
262: {
263: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
264: '/filetypes.tab';
265: if ( open (my $fh,"<$typesfile") ) {
266: while (my $line = <$fh>) {
267: next if ($line =~ /^\#/);
268: chomp($line);
269: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
270: if ($descr ne '') {
271: $fe{$ending}=lc($emb);
272: $fd{$ending}=$descr;
273: if ($mime ne 'unk') { $fm{$ending}=$mime; }
274: }
275: }
276: close($fh);
277: }
278: }
279: &Apache::lonnet::logthis(
280: "<span style='color:yellow;'>INFO: Read file types</span>");
281: $readit=1;
282: } # end of unless($readit)
283:
284: }
285:
286: ###############################################################
287: ## HTML and Javascript Helper Functions ##
288: ###############################################################
289:
290: =pod
291:
292: =head1 HTML and Javascript Functions
293:
294: =over 4
295:
296: =item * &browser_and_searcher_javascript()
297:
298: X<browsing, javascript>X<searching, javascript>Returns a string
299: containing javascript with two functions, C<openbrowser> and
300: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
301: tags.
302:
303: =item * &openbrowser(formname,elementname,only,omit) [javascript]
304:
305: inputs: formname, elementname, only, omit
306:
307: formname and elementname indicate the name of the html form and name of
308: the element that the results of the browsing selection are to be placed in.
309:
310: Specifying 'only' will restrict the browser to displaying only files
311: with the given extension. Can be a comma separated list.
312:
313: Specifying 'omit' will restrict the browser to NOT displaying files
314: with the given extension. Can be a comma separated list.
315:
316: =item * &opensearcher(formname,elementname) [javascript]
317:
318: Inputs: formname, elementname
319:
320: formname and elementname specify the name of the html form and the name
321: of the element the selection from the search results will be placed in.
322:
323: =cut
324:
325: sub browser_and_searcher_javascript {
326: my ($mode)=@_;
327: if (!defined($mode)) { $mode='edit'; }
328: my $resurl=&escape_single(&lastresurl());
329: return <<END;
330: // <!-- BEGIN LON-CAPA Internal
331: var editbrowser = null;
332: function openbrowser(formname,elementname,only,omit,titleelement) {
333: var url = '$resurl/?';
334: if (editbrowser == null) {
335: url += 'launch=1&';
336: }
337: url += 'catalogmode=interactive&';
338: url += 'mode=$mode&';
339: url += 'inhibitmenu=yes&';
340: url += 'form=' + formname + '&';
341: if (only != null) {
342: url += 'only=' + only + '&';
343: } else {
344: url += 'only=&';
345: }
346: if (omit != null) {
347: url += 'omit=' + omit + '&';
348: } else {
349: url += 'omit=&';
350: }
351: if (titleelement != null) {
352: url += 'titleelement=' + titleelement + '&';
353: } else {
354: url += 'titleelement=&';
355: }
356: url += 'element=' + elementname + '';
357: var title = 'Browser';
358: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
359: options += ',width=700,height=600';
360: editbrowser = open(url,title,options,'1');
361: editbrowser.focus();
362: }
363: var editsearcher;
364: function opensearcher(formname,elementname,titleelement) {
365: var url = '/adm/searchcat?';
366: if (editsearcher == null) {
367: url += 'launch=1&';
368: }
369: url += 'catalogmode=interactive&';
370: url += 'mode=$mode&';
371: url += 'form=' + formname + '&';
372: if (titleelement != null) {
373: url += 'titleelement=' + titleelement + '&';
374: } else {
375: url += 'titleelement=&';
376: }
377: url += 'element=' + elementname + '';
378: var title = 'Search';
379: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
380: options += ',width=700,height=600';
381: editsearcher = open(url,title,options,'1');
382: editsearcher.focus();
383: }
384: // END LON-CAPA Internal -->
385: END
386: }
387:
388: sub lastresurl {
389: if ($env{'environment.lastresurl'}) {
390: return $env{'environment.lastresurl'}
391: } else {
392: return '/res';
393: }
394: }
395:
396: sub storeresurl {
397: my $resurl=&Apache::lonnet::clutter(shift);
398: unless ($resurl=~/^\/res/) { return 0; }
399: $resurl=~s/\/$//;
400: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
401: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
402: return 1;
403: }
404:
405: sub studentbrowser_javascript {
406: unless (
407: (($env{'request.course.id'}) &&
408: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
409: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
410: '/'.$env{'request.course.sec'})
411: ))
412: || ($env{'request.role'}=~/^(au|dc|su)/)
413: ) { return ''; }
414: return (<<'ENDSTDBRW');
415: <script type="text/javascript" language="Javascript">
416: // <![CDATA[
417: var stdeditbrowser;
418: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
419: var url = '/adm/pickstudent?';
420: var filter;
421: if (!ignorefilter) {
422: eval('filter=document.'+formname+'.'+uname+'.value;');
423: }
424: if (filter != null) {
425: if (filter != '') {
426: url += 'filter='+filter+'&';
427: }
428: }
429: url += 'form=' + formname + '&unameelement='+uname+
430: '&udomelement='+udom+
431: '&clicker='+clicker;
432: if (roleflag) { url+="&roles=1"; }
433: if (courseadvonly) { url+="&courseadvonly=1"; }
434: var title = 'Student_Browser';
435: var options = 'scrollbars=1,resizable=1,menubar=0';
436: options += ',width=700,height=600';
437: stdeditbrowser = open(url,title,options,'1');
438: stdeditbrowser.focus();
439: }
440: // ]]>
441: </script>
442: ENDSTDBRW
443: }
444:
445: sub resourcebrowser_javascript {
446: unless ($env{'request.course.id'}) { return ''; }
447: return (<<'ENDRESBRW');
448: <script type="text/javascript" language="Javascript">
449: // <![CDATA[
450: var reseditbrowser;
451: function openresbrowser(formname,reslink) {
452: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
453: var title = 'Resource_Browser';
454: var options = 'scrollbars=1,resizable=1,menubar=0';
455: options += ',width=700,height=500';
456: reseditbrowser = open(url,title,options,'1');
457: reseditbrowser.focus();
458: }
459: // ]]>
460: </script>
461: ENDRESBRW
462: }
463:
464: sub selectstudent_link {
465: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
466: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
467: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
468: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
469: if ($env{'request.course.id'}) {
470: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
471: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
472: '/'.$env{'request.course.sec'})) {
473: return '';
474: }
475: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
476: if ($courseadvonly) {
477: $callargs .= ",'',1,1";
478: }
479: return '<span class="LC_nobreak">'.
480: '<a href="javascript:openstdbrowser('.$callargs.');">'.
481: &mt('Select User').'</a></span>';
482: }
483: if ($env{'request.role'}=~/^(au|dc|su)/) {
484: $callargs .= ",'',1";
485: return '<span class="LC_nobreak">'.
486: '<a href="javascript:openstdbrowser('.$callargs.');">'.
487: &mt('Select User').'</a></span>';
488: }
489: return '';
490: }
491:
492: sub selectresource_link {
493: my ($form,$reslink,$arg)=@_;
494:
495: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
496: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
497: unless ($env{'request.course.id'}) { return $arg; }
498: return '<span class="LC_nobreak">'.
499: '<a href="javascript:openresbrowser('.$callargs.');">'.
500: $arg.'</a></span>';
501: }
502:
503:
504:
505: sub authorbrowser_javascript {
506: return <<"ENDAUTHORBRW";
507: <script type="text/javascript" language="JavaScript">
508: // <![CDATA[
509: var stdeditbrowser;
510:
511: function openauthorbrowser(formname,udom) {
512: var url = '/adm/pickauthor?';
513: url += 'form='+formname+'&roledom='+udom;
514: var title = 'Author_Browser';
515: var options = 'scrollbars=1,resizable=1,menubar=0';
516: options += ',width=700,height=600';
517: stdeditbrowser = open(url,title,options,'1');
518: stdeditbrowser.focus();
519: }
520:
521: // ]]>
522: </script>
523: ENDAUTHORBRW
524: }
525:
526: sub coursebrowser_javascript {
527: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
528: my $wintitle = 'Course_Browser';
529: if ($crstype eq 'Community') {
530: $wintitle = 'Community_Browser';
531: }
532: my $id_functions = &javascript_index_functions();
533: my $output = '
534: <script type="text/javascript" language="JavaScript">
535: // <![CDATA[
536: var stdeditbrowser;'."\n";
537:
538: $output .= <<"ENDSTDBRW";
539: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
540: var url = '/adm/pickcourse?';
541: var formid = getFormIdByName(formname);
542: var domainfilter = getDomainFromSelectbox(formname,udom);
543: if (domainfilter != null) {
544: if (domainfilter != '') {
545: url += 'domainfilter='+domainfilter+'&';
546: }
547: }
548: url += 'form=' + formname + '&cnumelement='+uname+
549: '&cdomelement='+udom+
550: '&cnameelement='+desc;
551: if (extra_element !=null && extra_element != '') {
552: if (formname == 'rolechoice' || formname == 'studentform') {
553: url += '&roleelement='+extra_element;
554: if (domainfilter == null || domainfilter == '') {
555: url += '&domainfilter='+extra_element;
556: }
557: }
558: else {
559: if (formname == 'portform') {
560: url += '&setroles='+extra_element;
561: } else {
562: if (formname == 'rules') {
563: url += '&fixeddom='+extra_element;
564: }
565: }
566: }
567: }
568: if (type != null && type != '') {
569: url += '&type='+type;
570: }
571: if (type_elem != null && type_elem != '') {
572: url += '&typeelement='+type_elem;
573: }
574: if (formname == 'ccrs') {
575: var ownername = document.forms[formid].ccuname.value;
576: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
577: url += '&cloner='+ownername+':'+ownerdom;
578: }
579: if (multflag !=null && multflag != '') {
580: url += '&multiple='+multflag;
581: }
582: var title = '$wintitle';
583: var options = 'scrollbars=1,resizable=1,menubar=0';
584: options += ',width=700,height=600';
585: stdeditbrowser = open(url,title,options,'1');
586: stdeditbrowser.focus();
587: }
588: $id_functions
589: ENDSTDBRW
590: if (($sec_element ne '') || ($role_element ne '')) {
591: $output .= &setsec_javascript($sec_element,$formname,$role_element);
592: }
593: $output .= '
594: // ]]>
595: </script>';
596: return $output;
597: }
598:
599: sub javascript_index_functions {
600: return <<"ENDJS";
601:
602: function getFormIdByName(formname) {
603: for (var i=0;i<document.forms.length;i++) {
604: if (document.forms[i].name == formname) {
605: return i;
606: }
607: }
608: return -1;
609: }
610:
611: function getIndexByName(formid,item) {
612: for (var i=0;i<document.forms[formid].elements.length;i++) {
613: if (document.forms[formid].elements[i].name == item) {
614: return i;
615: }
616: }
617: return -1;
618: }
619:
620: function getDomainFromSelectbox(formname,udom) {
621: var userdom;
622: var formid = getFormIdByName(formname);
623: if (formid > -1) {
624: var domid = getIndexByName(formid,udom);
625: if (domid > -1) {
626: if (document.forms[formid].elements[domid].type == 'select-one') {
627: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
628: }
629: if (document.forms[formid].elements[domid].type == 'hidden') {
630: userdom=document.forms[formid].elements[domid].value;
631: }
632: }
633: }
634: return userdom;
635: }
636:
637: ENDJS
638:
639: }
640:
641: sub javascript_array_indexof {
642: return <<ENDJS;
643: <script type="text/javascript" language="JavaScript">
644: // <![CDATA[
645:
646: if (!Array.prototype.indexOf) {
647: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
648: "use strict";
649: if (this === void 0 || this === null) {
650: throw new TypeError();
651: }
652: var t = Object(this);
653: var len = t.length >>> 0;
654: if (len === 0) {
655: return -1;
656: }
657: var n = 0;
658: if (arguments.length > 0) {
659: n = Number(arguments[1]);
660: if (n !== n) { // shortcut for verifying if it's NaN
661: n = 0;
662: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
663: n = (n > 0 || -1) * Math.floor(Math.abs(n));
664: }
665: }
666: if (n >= len) {
667: return -1;
668: }
669: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
670: for (; k < len; k++) {
671: if (k in t && t[k] === searchElement) {
672: return k;
673: }
674: }
675: return -1;
676: }
677: }
678:
679: // ]]>
680: </script>
681:
682: ENDJS
683:
684: }
685:
686: sub userbrowser_javascript {
687: my $id_functions = &javascript_index_functions();
688: return <<"ENDUSERBRW";
689:
690: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
691: var url = '/adm/pickuser?';
692: var userdom = getDomainFromSelectbox(formname,udom);
693: if (userdom != null) {
694: if (userdom != '') {
695: url += 'srchdom='+userdom+'&';
696: }
697: }
698: url += 'form=' + formname + '&unameelement='+uname+
699: '&udomelement='+udom+
700: '&ulastelement='+ulast+
701: '&ufirstelement='+ufirst+
702: '&uemailelement='+uemail+
703: '&hideudomelement='+hideudom+
704: '&coursedom='+crsdom;
705: if ((caller != null) && (caller != undefined)) {
706: url += '&caller='+caller;
707: }
708: var title = 'User_Browser';
709: var options = 'scrollbars=1,resizable=1,menubar=0';
710: options += ',width=700,height=600';
711: var stdeditbrowser = open(url,title,options,'1');
712: stdeditbrowser.focus();
713: }
714:
715: function fix_domain (formname,udom,origdom,uname) {
716: var formid = getFormIdByName(formname);
717: if (formid > -1) {
718: var unameid = getIndexByName(formid,uname);
719: var domid = getIndexByName(formid,udom);
720: var hidedomid = getIndexByName(formid,origdom);
721: if (hidedomid > -1) {
722: var fixeddom = document.forms[formid].elements[hidedomid].value;
723: var unameval = document.forms[formid].elements[unameid].value;
724: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
725: if (domid > -1) {
726: var slct = document.forms[formid].elements[domid];
727: if (slct.type == 'select-one') {
728: var i;
729: for (i=0;i<slct.length;i++) {
730: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
731: }
732: }
733: if (slct.type == 'hidden') {
734: slct.value = fixeddom;
735: }
736: }
737: }
738: }
739: }
740: return;
741: }
742:
743: $id_functions
744: ENDUSERBRW
745: }
746:
747: sub setsec_javascript {
748: my ($sec_element,$formname,$role_element) = @_;
749: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
750: $communityrolestr);
751: if ($role_element ne '') {
752: my @allroles = ('st','ta','ep','in','ad');
753: foreach my $crstype ('Course','Community') {
754: if ($crstype eq 'Community') {
755: foreach my $role (@allroles) {
756: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
757: }
758: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
759: } else {
760: foreach my $role (@allroles) {
761: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
762: }
763: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
764: }
765: }
766: $rolestr = '"'.join('","',@allroles).'"';
767: $courserolestr = '"'.join('","',@courserolenames).'"';
768: $communityrolestr = '"'.join('","',@communityrolenames).'"';
769: }
770: my $setsections = qq|
771: function setSect(sectionlist) {
772: var sectionsArray = new Array();
773: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
774: sectionsArray = sectionlist.split(",");
775: }
776: var numSections = sectionsArray.length;
777: document.$formname.$sec_element.length = 0;
778: if (numSections == 0) {
779: document.$formname.$sec_element.multiple=false;
780: document.$formname.$sec_element.size=1;
781: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
782: } else {
783: if (numSections == 1) {
784: document.$formname.$sec_element.multiple=false;
785: document.$formname.$sec_element.size=1;
786: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
787: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
788: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
789: } else {
790: for (var i=0; i<numSections; i++) {
791: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
792: }
793: document.$formname.$sec_element.multiple=true
794: if (numSections < 3) {
795: document.$formname.$sec_element.size=numSections;
796: } else {
797: document.$formname.$sec_element.size=3;
798: }
799: document.$formname.$sec_element.options[0].selected = false
800: }
801: }
802: }
803:
804: function setRole(crstype) {
805: |;
806: if ($role_element eq '') {
807: $setsections .= ' return;
808: }
809: ';
810: } else {
811: $setsections .= qq|
812: var elementLength = document.$formname.$role_element.length;
813: var allroles = Array($rolestr);
814: var courserolenames = Array($courserolestr);
815: var communityrolenames = Array($communityrolestr);
816: if (elementLength != undefined) {
817: if (document.$formname.$role_element.options[5].value == 'cc') {
818: if (crstype == 'Course') {
819: return;
820: } else {
821: allroles[5] = 'co';
822: for (var i=0; i<6; i++) {
823: document.$formname.$role_element.options[i].value = allroles[i];
824: document.$formname.$role_element.options[i].text = communityrolenames[i];
825: }
826: }
827: } else {
828: if (crstype == 'Community') {
829: return;
830: } else {
831: allroles[5] = 'cc';
832: for (var i=0; i<6; i++) {
833: document.$formname.$role_element.options[i].value = allroles[i];
834: document.$formname.$role_element.options[i].text = courserolenames[i];
835: }
836: }
837: }
838: }
839: return;
840: }
841: |;
842: }
843: return $setsections;
844: }
845:
846: sub selectcourse_link {
847: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
848: $typeelement) = @_;
849: my $type = $selecttype;
850: my $linktext = &mt('Select Course');
851: if ($selecttype eq 'Community') {
852: $linktext = &mt('Select Community');
853: } elsif ($selecttype eq 'Course/Community') {
854: $linktext = &mt('Select Course/Community');
855: $type = '';
856: } elsif ($selecttype eq 'Select') {
857: $linktext = &mt('Select');
858: $type = '';
859: }
860: return '<span class="LC_nobreak">'
861: ."<a href='"
862: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
863: .'","'.$udomele.'","'.$desc.'","'.$extra_element
864: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
865: ."'>".$linktext.'</a>'
866: .'</span>';
867: }
868:
869: sub selectauthor_link {
870: my ($form,$udom)=@_;
871: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
872: &mt('Select Author').'</a>';
873: }
874:
875: sub selectuser_link {
876: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
877: $coursedom,$linktext,$caller) = @_;
878: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
879: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
880: ');">'.$linktext.'</a>';
881: }
882:
883: sub check_uncheck_jscript {
884: my $jscript = <<"ENDSCRT";
885: function checkAll(field) {
886: if (field.length > 0) {
887: for (i = 0; i < field.length; i++) {
888: field[i].checked = true ;
889: }
890: } else {
891: field.checked = true
892: }
893: }
894:
895: function uncheckAll(field) {
896: if (field.length > 0) {
897: for (i = 0; i < field.length; i++) {
898: field[i].checked = false ;
899: }
900: } else {
901: field.checked = false ;
902: }
903: }
904: ENDSCRT
905: return $jscript;
906: }
907:
908: sub select_timezone {
909: my ($name,$selected,$onchange,$includeempty)=@_;
910: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
911: if ($includeempty) {
912: $output .= '<option value=""';
913: if (($selected eq '') || ($selected eq 'local')) {
914: $output .= ' selected="selected" ';
915: }
916: $output .= '> </option>';
917: }
918: my @timezones = DateTime::TimeZone->all_names;
919: foreach my $tzone (@timezones) {
920: $output.= '<option value="'.$tzone.'"';
921: if ($tzone eq $selected) {
922: $output.=' selected="selected"';
923: }
924: $output.=">$tzone</option>\n";
925: }
926: $output.="</select>";
927: return $output;
928: }
929:
930: sub select_datelocale {
931: my ($name,$selected,$onchange,$includeempty)=@_;
932: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
933: if ($includeempty) {
934: $output .= '<option value=""';
935: if ($selected eq '') {
936: $output .= ' selected="selected" ';
937: }
938: $output .= '> </option>';
939: }
940: my (@possibles,%locale_names);
941: my @locales = DateTime::Locale::Catalog::Locales;
942: foreach my $locale (@locales) {
943: if (ref($locale) eq 'HASH') {
944: my $id = $locale->{'id'};
945: if ($id ne '') {
946: my $en_terr = $locale->{'en_territory'};
947: my $native_terr = $locale->{'native_territory'};
948: my @languages = &Apache::lonlocal::preferred_languages();
949: if (grep(/^en$/,@languages) || !@languages) {
950: if ($en_terr ne '') {
951: $locale_names{$id} = '('.$en_terr.')';
952: } elsif ($native_terr ne '') {
953: $locale_names{$id} = $native_terr;
954: }
955: } else {
956: if ($native_terr ne '') {
957: $locale_names{$id} = $native_terr.' ';
958: } elsif ($en_terr ne '') {
959: $locale_names{$id} = '('.$en_terr.')';
960: }
961: }
962: push (@possibles,$id);
963: }
964: }
965: }
966: foreach my $item (sort(@possibles)) {
967: $output.= '<option value="'.$item.'"';
968: if ($item eq $selected) {
969: $output.=' selected="selected"';
970: }
971: $output.=">$item";
972: if ($locale_names{$item} ne '') {
973: $output.=" $locale_names{$item}</option>\n";
974: }
975: $output.="</option>\n";
976: }
977: $output.="</select>";
978: return $output;
979: }
980:
981: sub select_language {
982: my ($name,$selected,$includeempty) = @_;
983: my %langchoices;
984: if ($includeempty) {
985: %langchoices = ('' => 'No language preference');
986: }
987: foreach my $id (&languageids()) {
988: my $code = &supportedlanguagecode($id);
989: if ($code) {
990: $langchoices{$code} = &plainlanguagedescription($id);
991: }
992: }
993: return &select_form($selected,$name,\%langchoices);
994: }
995:
996: =pod
997:
998: =item * &linked_select_forms(...)
999:
1000: linked_select_forms returns a string containing a <script></script> block
1001: and html for two <select> menus. The select menus will be linked in that
1002: changing the value of the first menu will result in new values being placed
1003: in the second menu. The values in the select menu will appear in alphabetical
1004: order unless a defined order is provided.
1005:
1006: linked_select_forms takes the following ordered inputs:
1007:
1008: =over 4
1009:
1010: =item * $formname, the name of the <form> tag
1011:
1012: =item * $middletext, the text which appears between the <select> tags
1013:
1014: =item * $firstdefault, the default value for the first menu
1015:
1016: =item * $firstselectname, the name of the first <select> tag
1017:
1018: =item * $secondselectname, the name of the second <select> tag
1019:
1020: =item * $hashref, a reference to a hash containing the data for the menus.
1021:
1022: =item * $menuorder, the order of values in the first menu
1023:
1024: =back
1025:
1026: Below is an example of such a hash. Only the 'text', 'default', and
1027: 'select2' keys must appear as stated. keys(%menu) are the possible
1028: values for the first select menu. The text that coincides with the
1029: first menu value is given in $menu{$choice1}->{'text'}. The values
1030: and text for the second menu are given in the hash pointed to by
1031: $menu{$choice1}->{'select2'}.
1032:
1033: my %menu = ( A1 => { text =>"Choice A1" ,
1034: default => "B3",
1035: select2 => {
1036: B1 => "Choice B1",
1037: B2 => "Choice B2",
1038: B3 => "Choice B3",
1039: B4 => "Choice B4"
1040: },
1041: order => ['B4','B3','B1','B2'],
1042: },
1043: A2 => { text =>"Choice A2" ,
1044: default => "C2",
1045: select2 => {
1046: C1 => "Choice C1",
1047: C2 => "Choice C2",
1048: C3 => "Choice C3"
1049: },
1050: order => ['C2','C1','C3'],
1051: },
1052: A3 => { text =>"Choice A3" ,
1053: default => "D6",
1054: select2 => {
1055: D1 => "Choice D1",
1056: D2 => "Choice D2",
1057: D3 => "Choice D3",
1058: D4 => "Choice D4",
1059: D5 => "Choice D5",
1060: D6 => "Choice D6",
1061: D7 => "Choice D7"
1062: },
1063: order => ['D4','D3','D2','D1','D7','D6','D5'],
1064: }
1065: );
1066:
1067: =cut
1068:
1069: sub linked_select_forms {
1070: my ($formname,
1071: $middletext,
1072: $firstdefault,
1073: $firstselectname,
1074: $secondselectname,
1075: $hashref,
1076: $menuorder,
1077: ) = @_;
1078: my $second = "document.$formname.$secondselectname";
1079: my $first = "document.$formname.$firstselectname";
1080: # output the javascript to do the changing
1081: my $result = '';
1082: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1083: $result.="// <![CDATA[\n";
1084: $result.="var select2data = new Object();\n";
1085: $" = '","';
1086: my $debug = '';
1087: foreach my $s1 (sort(keys(%$hashref))) {
1088: $result.="select2data.d_$s1 = new Object();\n";
1089: $result.="select2data.d_$s1.def = new String('".
1090: $hashref->{$s1}->{'default'}."');\n";
1091: $result.="select2data.d_$s1.values = new Array(";
1092: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1093: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1094: @s2values = @{$hashref->{$s1}->{'order'}};
1095: }
1096: $result.="\"@s2values\");\n";
1097: $result.="select2data.d_$s1.texts = new Array(";
1098: my @s2texts;
1099: foreach my $value (@s2values) {
1100: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1101: }
1102: $result.="\"@s2texts\");\n";
1103: }
1104: $"=' ';
1105: $result.= <<"END";
1106:
1107: function select1_changed() {
1108: // Determine new choice
1109: var newvalue = "d_" + $first.value;
1110: // update select2
1111: var values = select2data[newvalue].values;
1112: var texts = select2data[newvalue].texts;
1113: var select2def = select2data[newvalue].def;
1114: var i;
1115: // out with the old
1116: for (i = 0; i < $second.options.length; i++) {
1117: $second.options[i] = null;
1118: }
1119: // in with the nuclear
1120: for (i=0;i<values.length; i++) {
1121: $second.options[i] = new Option(values[i]);
1122: $second.options[i].value = values[i];
1123: $second.options[i].text = texts[i];
1124: if (values[i] == select2def) {
1125: $second.options[i].selected = true;
1126: }
1127: }
1128: }
1129: // ]]>
1130: </script>
1131: END
1132: # output the initial values for the selection lists
1133: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1134: my @order = sort(keys(%{$hashref}));
1135: if (ref($menuorder) eq 'ARRAY') {
1136: @order = @{$menuorder};
1137: }
1138: foreach my $value (@order) {
1139: $result.=" <option value=\"$value\" ";
1140: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1141: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1142: }
1143: $result .= "</select>\n";
1144: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1145: $result .= $middletext;
1146: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
1147: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1148:
1149: my @secondorder = sort(keys(%select2));
1150: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1151: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1152: }
1153: foreach my $value (@secondorder) {
1154: $result.=" <option value=\"$value\" ";
1155: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1156: $result.=">".&mt($select2{$value})."</option>\n";
1157: }
1158: $result .= "</select>\n";
1159: # return $debug;
1160: return $result;
1161: } # end of sub linked_select_forms {
1162:
1163: =pod
1164:
1165: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1166:
1167: Returns a string corresponding to an HTML link to the given help
1168: $topic, where $topic corresponds to the name of a .tex file in
1169: /home/httpd/html/adm/help/tex, with underscores replaced by
1170: spaces.
1171:
1172: $text will optionally be linked to the same topic, allowing you to
1173: link text in addition to the graphic. If you do not want to link
1174: text, but wish to specify one of the later parameters, pass an
1175: empty string.
1176:
1177: $stayOnPage is a value that will be interpreted as a boolean. If true,
1178: the link will not open a new window. If false, the link will open
1179: a new window using Javascript. (Default is false.)
1180:
1181: $width and $height are optional numerical parameters that will
1182: override the width and height of the popped up window, which may
1183: be useful for certain help topics with big pictures included.
1184:
1185: $imgid is the id of the img tag used for the help icon. This may be
1186: used in a javascript call to switch the image src. See
1187: lonhtmlcommon::htmlareaselectactive() for an example.
1188:
1189: =cut
1190:
1191: sub help_open_topic {
1192: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1193: $text = "" if (not defined $text);
1194: $stayOnPage = 0 if (not defined $stayOnPage);
1195: $width = 500 if (not defined $width);
1196: $height = 400 if (not defined $height);
1197: my $filename = $topic;
1198: $filename =~ s/ /_/g;
1199:
1200: my $template = "";
1201: my $link;
1202:
1203: $topic=~s/\W/\_/g;
1204:
1205: if (!$stayOnPage) {
1206: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1207: } elsif ($stayOnPage eq 'popup') {
1208: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1209: } else {
1210: $link = "/adm/help/${filename}.hlp";
1211: }
1212:
1213: # Add the text
1214: if ($text ne "") {
1215: $template.='<span class="LC_help_open_topic">'
1216: .'<a target="_top" href="'.$link.'">'
1217: .$text.'</a>';
1218: }
1219:
1220: # (Always) Add the graphic
1221: my $title = &mt('Online Help');
1222: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1223: if ($imgid ne '') {
1224: $imgid = ' id="'.$imgid.'"';
1225: }
1226: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1227: .'<img src="'.$helpicon.'" border="0"'
1228: .' alt="'.&mt('Help: [_1]',$topic).'"'
1229: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1230: .' /></a>';
1231: if ($text ne "") {
1232: $template.='</span>';
1233: }
1234: return $template;
1235:
1236: }
1237:
1238: # This is a quicky function for Latex cheatsheet editing, since it
1239: # appears in at least four places
1240: sub helpLatexCheatsheet {
1241: my ($topic,$text,$not_author,$stayOnPage) = @_;
1242: my $out;
1243: my $addOther = '';
1244: if ($topic) {
1245: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1246: }
1247: $out = '<span>' # Start cheatsheet
1248: .$addOther
1249: .'<span>'
1250: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1251: .'</span> <span>'
1252: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1253: .'</span>';
1254: unless ($not_author) {
1255: $out .= ' <span>'
1256: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1257: .'</span>';
1258: }
1259: $out .= '</span>'; # End cheatsheet
1260: return $out;
1261: }
1262:
1263: sub general_help {
1264: my $helptopic='Student_Intro';
1265: if ($env{'request.role'}=~/^(ca|au)/) {
1266: $helptopic='Authoring_Intro';
1267: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1268: $helptopic='Course_Coordination_Intro';
1269: } elsif ($env{'request.role'}=~/^dc/) {
1270: $helptopic='Domain_Coordination_Intro';
1271: }
1272: return $helptopic;
1273: }
1274:
1275: sub update_help_link {
1276: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1277: my $origurl = $ENV{'REQUEST_URI'};
1278: $origurl=~s|^/~|/priv/|;
1279: my $timestamp = time;
1280: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1281: $$datum = &escape($$datum);
1282: }
1283:
1284: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1285: my $output .= <<"ENDOUTPUT";
1286: <script type="text/javascript">
1287: // <![CDATA[
1288: banner_link = '$banner_link';
1289: // ]]>
1290: </script>
1291: ENDOUTPUT
1292: return $output;
1293: }
1294:
1295: # now just updates the help link and generates a blue icon
1296: sub help_open_menu {
1297: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1298: = @_;
1299: $stayOnPage = 1;
1300: my $output;
1301: if ($component_help) {
1302: if (!$text) {
1303: $output=&help_open_topic($component_help,undef,$stayOnPage,
1304: $width,$height);
1305: } else {
1306: my $help_text;
1307: $help_text=&unescape($topic);
1308: $output='<table><tr><td>'.
1309: &help_open_topic($component_help,$help_text,$stayOnPage,
1310: $width,$height).'</td></tr></table>';
1311: }
1312: }
1313: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1314: return $output.$banner_link;
1315: }
1316:
1317: sub top_nav_help {
1318: my ($text) = @_;
1319: $text = &mt($text);
1320: my $stay_on_page = 1;
1321:
1322: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1323: : "javascript:helpMenu('open')";
1324: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1325:
1326: my $title = &mt('Get help');
1327:
1328: return <<"END";
1329: $banner_link
1330: <a href="$link" title="$title">$text</a>
1331: END
1332: }
1333:
1334: sub help_menu_js {
1335: my ($text) = @_;
1336: my $stayOnPage = 1;
1337: my $width = 620;
1338: my $height = 600;
1339: my $helptopic=&general_help();
1340: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1341: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1342: my $start_page =
1343: &Apache::loncommon::start_page('Help Menu', undef,
1344: {'frameset' => 1,
1345: 'js_ready' => 1,
1346: 'add_entries' => {
1347: 'border' => '0',
1348: 'rows' => "110,*",},});
1349: my $end_page =
1350: &Apache::loncommon::end_page({'frameset' => 1,
1351: 'js_ready' => 1,});
1352:
1353: my $template .= <<"ENDTEMPLATE";
1354: <script type="text/javascript">
1355: // <![CDATA[
1356: // <!-- BEGIN LON-CAPA Internal
1357: var banner_link = '';
1358: function helpMenu(target) {
1359: var caller = this;
1360: if (target == 'open') {
1361: var newWindow = null;
1362: try {
1363: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1364: }
1365: catch(error) {
1366: writeHelp(caller);
1367: return;
1368: }
1369: if (newWindow) {
1370: caller = newWindow;
1371: }
1372: }
1373: writeHelp(caller);
1374: return;
1375: }
1376: function writeHelp(caller) {
1377: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1378: caller.document.close()
1379: caller.focus()
1380: }
1381: // END LON-CAPA Internal -->
1382: // ]]>
1383: </script>
1384: ENDTEMPLATE
1385: return $template;
1386: }
1387:
1388: sub help_open_bug {
1389: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1390: unless ($env{'user.adv'}) { return ''; }
1391: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1392: $text = "" if (not defined $text);
1393: $stayOnPage=1;
1394: $width = 600 if (not defined $width);
1395: $height = 600 if (not defined $height);
1396:
1397: $topic=~s/\W+/\+/g;
1398: my $link='';
1399: my $template='';
1400: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1401: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1402: if (!$stayOnPage)
1403: {
1404: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1405: }
1406: else
1407: {
1408: $link = $url;
1409: }
1410: # Add the text
1411: if ($text ne "")
1412: {
1413: $template .=
1414: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1415: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1416: }
1417:
1418: # Add the graphic
1419: my $title = &mt('Report a Bug');
1420: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1421: $template .= <<"ENDTEMPLATE";
1422: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1423: ENDTEMPLATE
1424: if ($text ne '') { $template.='</td></tr></table>' };
1425: return $template;
1426:
1427: }
1428:
1429: sub help_open_faq {
1430: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1431: unless ($env{'user.adv'}) { return ''; }
1432: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1433: $text = "" if (not defined $text);
1434: $stayOnPage=1;
1435: $width = 350 if (not defined $width);
1436: $height = 400 if (not defined $height);
1437:
1438: $topic=~s/\W+/\+/g;
1439: my $link='';
1440: my $template='';
1441: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1442: if (!$stayOnPage)
1443: {
1444: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1445: }
1446: else
1447: {
1448: $link = $url;
1449: }
1450:
1451: # Add the text
1452: if ($text ne "")
1453: {
1454: $template .=
1455: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1456: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1457: }
1458:
1459: # Add the graphic
1460: my $title = &mt('View the FAQ');
1461: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1462: $template .= <<"ENDTEMPLATE";
1463: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1464: ENDTEMPLATE
1465: if ($text ne '') { $template.='</td></tr></table>' };
1466: return $template;
1467:
1468: }
1469:
1470: ###############################################################
1471: ###############################################################
1472:
1473: =pod
1474:
1475: =item * &change_content_javascript():
1476:
1477: This and the next function allow you to create small sections of an
1478: otherwise static HTML page that you can update on the fly with
1479: Javascript, even in Netscape 4.
1480:
1481: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1482: must be written to the HTML page once. It will prove the Javascript
1483: function "change(name, content)". Calling the change function with the
1484: name of the section
1485: you want to update, matching the name passed to C<changable_area>, and
1486: the new content you want to put in there, will put the content into
1487: that area.
1488:
1489: B<Note>: Netscape 4 only reserves enough space for the changable area
1490: to contain room for the original contents. You need to "make space"
1491: for whatever changes you wish to make, and be B<sure> to check your
1492: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1493: it's adequate for updating a one-line status display, but little more.
1494: This script will set the space to 100% width, so you only need to
1495: worry about height in Netscape 4.
1496:
1497: Modern browsers are much less limiting, and if you can commit to the
1498: user not using Netscape 4, this feature may be used freely with
1499: pretty much any HTML.
1500:
1501: =cut
1502:
1503: sub change_content_javascript {
1504: # If we're on Netscape 4, we need to use Layer-based code
1505: if ($env{'browser.type'} eq 'netscape' &&
1506: $env{'browser.version'} =~ /^4\./) {
1507: return (<<NETSCAPE4);
1508: function change(name, content) {
1509: doc = document.layers[name+"___escape"].layers[0].document;
1510: doc.open();
1511: doc.write(content);
1512: doc.close();
1513: }
1514: NETSCAPE4
1515: } else {
1516: # Otherwise, we need to use semi-standards-compliant code
1517: # (technically, "innerHTML" isn't standard but the equivalent
1518: # is really scary, and every useful browser supports it
1519: return (<<DOMBASED);
1520: function change(name, content) {
1521: element = document.getElementById(name);
1522: element.innerHTML = content;
1523: }
1524: DOMBASED
1525: }
1526: }
1527:
1528: =pod
1529:
1530: =item * &changable_area($name,$origContent):
1531:
1532: This provides a "changable area" that can be modified on the fly via
1533: the Javascript code provided in C<change_content_javascript>. $name is
1534: the name you will use to reference the area later; do not repeat the
1535: same name on a given HTML page more then once. $origContent is what
1536: the area will originally contain, which can be left blank.
1537:
1538: =cut
1539:
1540: sub changable_area {
1541: my ($name, $origContent) = @_;
1542:
1543: if ($env{'browser.type'} eq 'netscape' &&
1544: $env{'browser.version'} =~ /^4\./) {
1545: # If this is netscape 4, we need to use the Layer tag
1546: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1547: } else {
1548: return "<span id='$name'>$origContent</span>";
1549: }
1550: }
1551:
1552: =pod
1553:
1554: =item * &viewport_geometry_js
1555:
1556: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1557:
1558: =cut
1559:
1560:
1561: sub viewport_geometry_js {
1562: return <<"GEOMETRY";
1563: var Geometry = {};
1564: function init_geometry() {
1565: if (Geometry.init) { return };
1566: Geometry.init=1;
1567: if (window.innerHeight) {
1568: Geometry.getViewportHeight = function() { return window.innerHeight; };
1569: Geometry.getViewportWidth = function() { return window.innerWidth; };
1570: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1571: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1572: }
1573: else if (document.documentElement && document.documentElement.clientHeight) {
1574: Geometry.getViewportHeight =
1575: function() { return document.documentElement.clientHeight; };
1576: Geometry.getViewportWidth =
1577: function() { return document.documentElement.clientWidth; };
1578:
1579: Geometry.getHorizontalScroll =
1580: function() { return document.documentElement.scrollLeft; };
1581: Geometry.getVerticalScroll =
1582: function() { return document.documentElement.scrollTop; };
1583: }
1584: else if (document.body.clientHeight) {
1585: Geometry.getViewportHeight =
1586: function() { return document.body.clientHeight; };
1587: Geometry.getViewportWidth =
1588: function() { return document.body.clientWidth; };
1589: Geometry.getHorizontalScroll =
1590: function() { return document.body.scrollLeft; };
1591: Geometry.getVerticalScroll =
1592: function() { return document.body.scrollTop; };
1593: }
1594: }
1595:
1596: GEOMETRY
1597: }
1598:
1599: =pod
1600:
1601: =item * &viewport_size_js()
1602:
1603: 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.
1604:
1605: =cut
1606:
1607: sub viewport_size_js {
1608: my $geometry = &viewport_geometry_js();
1609: return <<"DIMS";
1610:
1611: $geometry
1612:
1613: function getViewportDims(width,height) {
1614: init_geometry();
1615: width.value = Geometry.getViewportWidth();
1616: height.value = Geometry.getViewportHeight();
1617: return;
1618: }
1619:
1620: DIMS
1621: }
1622:
1623: =pod
1624:
1625: =item * &resize_textarea_js()
1626:
1627: emits the needed javascript to resize a textarea to be as big as possible
1628:
1629: creates a function resize_textrea that takes two IDs first should be
1630: the id of the element to resize, second should be the id of a div that
1631: surrounds everything that comes after the textarea, this routine needs
1632: to be attached to the <body> for the onload and onresize events.
1633:
1634: =back
1635:
1636: =cut
1637:
1638: sub resize_textarea_js {
1639: my $geometry = &viewport_geometry_js();
1640: return <<"RESIZE";
1641: <script type="text/javascript">
1642: // <![CDATA[
1643: $geometry
1644:
1645: function getX(element) {
1646: var x = 0;
1647: while (element) {
1648: x += element.offsetLeft;
1649: element = element.offsetParent;
1650: }
1651: return x;
1652: }
1653: function getY(element) {
1654: var y = 0;
1655: while (element) {
1656: y += element.offsetTop;
1657: element = element.offsetParent;
1658: }
1659: return y;
1660: }
1661:
1662:
1663: function resize_textarea(textarea_id,bottom_id) {
1664: init_geometry();
1665: var textarea = document.getElementById(textarea_id);
1666: //alert(textarea);
1667:
1668: var textarea_top = getY(textarea);
1669: var textarea_height = textarea.offsetHeight;
1670: var bottom = document.getElementById(bottom_id);
1671: var bottom_top = getY(bottom);
1672: var bottom_height = bottom.offsetHeight;
1673: var window_height = Geometry.getViewportHeight();
1674: var fudge = 23;
1675: var new_height = window_height-fudge-textarea_top-bottom_height;
1676: if (new_height < 300) {
1677: new_height = 300;
1678: }
1679: textarea.style.height=new_height+'px';
1680: }
1681: // ]]>
1682: </script>
1683: RESIZE
1684:
1685: }
1686:
1687: =pod
1688:
1689: =head1 Excel and CSV file utility routines
1690:
1691: =over 4
1692:
1693: =cut
1694:
1695: ###############################################################
1696: ###############################################################
1697:
1698: =pod
1699:
1700: =item * &csv_translate($text)
1701:
1702: Translate $text to allow it to be output as a 'comma separated values'
1703: format.
1704:
1705: =cut
1706:
1707: ###############################################################
1708: ###############################################################
1709: sub csv_translate {
1710: my $text = shift;
1711: $text =~ s/\"/\"\"/g;
1712: $text =~ s/\n/ /g;
1713: return $text;
1714: }
1715:
1716: ###############################################################
1717: ###############################################################
1718:
1719: =pod
1720:
1721: =item * &define_excel_formats()
1722:
1723: Define some commonly used Excel cell formats.
1724:
1725: Currently supported formats:
1726:
1727: =over 4
1728:
1729: =item header
1730:
1731: =item bold
1732:
1733: =item h1
1734:
1735: =item h2
1736:
1737: =item h3
1738:
1739: =item h4
1740:
1741: =item i
1742:
1743: =item date
1744:
1745: =back
1746:
1747: Inputs: $workbook
1748:
1749: Returns: $format, a hash reference.
1750:
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:
2861: =cut
2862:
2863: ###############################################################
2864: sub get_related_words {
2865: my $keyword = shift;
2866: my %thesaurus_db;
2867: if (! -e $thesaurus_db_file) {
2868: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2869: "failed because the file does not exist");
2870: return ();
2871: }
2872: if (! tie(%thesaurus_db,'GDBM_File',
2873: $thesaurus_db_file,&GDBM_READER(),0640)){
2874: return ();
2875: }
2876: my @Words=();
2877: my $count=0;
2878: if (exists($thesaurus_db{$keyword})) {
2879: # The first element is the number of times
2880: # the word appears. We do not need it now.
2881: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2882: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2883: my $threshold=$mostfrequentcount/10;
2884: foreach my $possibleword (@RelatedWords) {
2885: my ($word,$wordcount)=split(/\,/,$possibleword);
2886: if ($wordcount>$threshold) {
2887: push(@Words,$word);
2888: $count++;
2889: if ($count>10) { last; }
2890: }
2891: }
2892: }
2893: untie %thesaurus_db;
2894: return @Words;
2895: }
2896:
2897: =pod
2898:
2899: =back
2900:
2901: =cut
2902:
2903: # -------------------------------------------------------------- Plaintext name
2904: =pod
2905:
2906: =head1 User Name Functions
2907:
2908: =over 4
2909:
2910: =item * &plainname($uname,$udom,$first)
2911:
2912: Takes a users logon name and returns it as a string in
2913: "first middle last generation" form
2914: if $first is set to 'lastname' then it returns it as
2915: 'lastname generation, firstname middlename' if their is a lastname
2916:
2917: =cut
2918:
2919:
2920: ###############################################################
2921: sub plainname {
2922: my ($uname,$udom,$first)=@_;
2923: return if (!defined($uname) || !defined($udom));
2924: my %names=&getnames($uname,$udom);
2925: my $name=&Apache::lonnet::format_name($names{'firstname'},
2926: $names{'middlename'},
2927: $names{'lastname'},
2928: $names{'generation'},$first);
2929: $name=~s/^\s+//;
2930: $name=~s/\s+$//;
2931: $name=~s/\s+/ /g;
2932: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2933: return $name;
2934: }
2935:
2936: # -------------------------------------------------------------------- Nickname
2937: =pod
2938:
2939: =item * &nickname($uname,$udom)
2940:
2941: Gets a users name and returns it as a string as
2942:
2943: ""nickname""
2944:
2945: if the user has a nickname or
2946:
2947: "first middle last generation"
2948:
2949: if the user does not
2950:
2951: =cut
2952:
2953: sub nickname {
2954: my ($uname,$udom)=@_;
2955: return if (!defined($uname) || !defined($udom));
2956: my %names=&getnames($uname,$udom);
2957: my $name=$names{'nickname'};
2958: if ($name) {
2959: $name='"'.$name.'"';
2960: } else {
2961: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2962: $names{'lastname'}.' '.$names{'generation'};
2963: $name=~s/\s+$//;
2964: $name=~s/\s+/ /g;
2965: }
2966: return $name;
2967: }
2968:
2969: sub getnames {
2970: my ($uname,$udom)=@_;
2971: return if (!defined($uname) || !defined($udom));
2972: if ($udom eq 'public' && $uname eq 'public') {
2973: return ('lastname' => &mt('Public'));
2974: }
2975: my $id=$uname.':'.$udom;
2976: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2977: if ($cached) {
2978: return %{$names};
2979: } else {
2980: my %loadnames=&Apache::lonnet::get('environment',
2981: ['firstname','middlename','lastname','generation','nickname'],
2982: $udom,$uname);
2983: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2984: return %loadnames;
2985: }
2986: }
2987:
2988: # -------------------------------------------------------------------- getemails
2989:
2990: =pod
2991:
2992: =item * &getemails($uname,$udom)
2993:
2994: Gets a user's email information and returns it as a hash with keys:
2995: notification, critnotification, permanentemail
2996:
2997: For notification and critnotification, values are comma-separated lists
2998: of e-mail addresses; for permanentemail, value is a single e-mail address.
2999:
3000:
3001: =cut
3002:
3003:
3004: sub getemails {
3005: my ($uname,$udom)=@_;
3006: if ($udom eq 'public' && $uname eq 'public') {
3007: return;
3008: }
3009: if (!$udom) { $udom=$env{'user.domain'}; }
3010: if (!$uname) { $uname=$env{'user.name'}; }
3011: my $id=$uname.':'.$udom;
3012: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3013: if ($cached) {
3014: return %{$names};
3015: } else {
3016: my %loadnames=&Apache::lonnet::get('environment',
3017: ['notification','critnotification',
3018: 'permanentemail'],
3019: $udom,$uname);
3020: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3021: return %loadnames;
3022: }
3023: }
3024:
3025: sub flush_email_cache {
3026: my ($uname,$udom)=@_;
3027: if (!$udom) { $udom =$env{'user.domain'}; }
3028: if (!$uname) { $uname=$env{'user.name'}; }
3029: return if ($udom eq 'public' && $uname eq 'public');
3030: my $id=$uname.':'.$udom;
3031: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3032: }
3033:
3034: # -------------------------------------------------------------------- getlangs
3035:
3036: =pod
3037:
3038: =item * &getlangs($uname,$udom)
3039:
3040: Gets a user's language preference and returns it as a hash with key:
3041: language.
3042:
3043: =cut
3044:
3045:
3046: sub getlangs {
3047: my ($uname,$udom) = @_;
3048: if (!$udom) { $udom =$env{'user.domain'}; }
3049: if (!$uname) { $uname=$env{'user.name'}; }
3050: my $id=$uname.':'.$udom;
3051: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3052: if ($cached) {
3053: return %{$langs};
3054: } else {
3055: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3056: $udom,$uname);
3057: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3058: return %loadlangs;
3059: }
3060: }
3061:
3062: sub flush_langs_cache {
3063: my ($uname,$udom)=@_;
3064: if (!$udom) { $udom =$env{'user.domain'}; }
3065: if (!$uname) { $uname=$env{'user.name'}; }
3066: return if ($udom eq 'public' && $uname eq 'public');
3067: my $id=$uname.':'.$udom;
3068: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3069: }
3070:
3071: # ------------------------------------------------------------------ Screenname
3072:
3073: =pod
3074:
3075: =item * &screenname($uname,$udom)
3076:
3077: Gets a users screenname and returns it as a string
3078:
3079: =cut
3080:
3081: sub screenname {
3082: my ($uname,$udom)=@_;
3083: if ($uname eq $env{'user.name'} &&
3084: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3085: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3086: return $names{'screenname'};
3087: }
3088:
3089:
3090: # ------------------------------------------------------------- Confirm Wrapper
3091: =pod
3092:
3093: =item confirmwrapper
3094:
3095: Wrap messages about completion of operation in box
3096:
3097: =cut
3098:
3099: sub confirmwrapper {
3100: my ($message)=@_;
3101: if ($message) {
3102: return "\n".'<div class="LC_confirm_box">'."\n"
3103: .$message."\n"
3104: .'</div>'."\n";
3105: } else {
3106: return $message;
3107: }
3108: }
3109:
3110: # ------------------------------------------------------------- Message Wrapper
3111:
3112: sub messagewrapper {
3113: my ($link,$username,$domain,$subject,$text)=@_;
3114: return
3115: '<a href="/adm/email?compose=individual&'.
3116: 'recname='.$username.'&recdom='.$domain.
3117: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3118: 'title="'.&mt('Send message').'">'.$link.'</a>';
3119: }
3120:
3121: # --------------------------------------------------------------- Notes Wrapper
3122:
3123: sub noteswrapper {
3124: my ($link,$un,$do)=@_;
3125: return
3126: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3127: }
3128:
3129: # ------------------------------------------------------------- Aboutme Wrapper
3130:
3131: sub aboutmewrapper {
3132: my ($link,$username,$domain,$target)=@_;
3133: if (!defined($username) && !defined($domain)) {
3134: return;
3135: }
3136: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
3137: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3138: }
3139:
3140: # ------------------------------------------------------------ Syllabus Wrapper
3141:
3142: sub syllabuswrapper {
3143: my ($linktext,$coursedir,$domain)=@_;
3144: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3145: }
3146:
3147: # -----------------------------------------------------------------------------
3148:
3149: sub track_student_link {
3150: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3151: my $link ="/adm/trackstudent?";
3152: my $title = 'View recent activity';
3153: if (defined($sname) && $sname !~ /^\s*$/ &&
3154: defined($sdom) && $sdom !~ /^\s*$/) {
3155: $link .= "selected_student=$sname:$sdom";
3156: $title .= ' of this student';
3157: }
3158: if (defined($target) && $target !~ /^\s*$/) {
3159: $target = qq{target="$target"};
3160: } else {
3161: $target = '';
3162: }
3163: if ($start) { $link.='&start='.$start; }
3164: if ($only_body) { $link .= '&only_body=1'; }
3165: $title = &mt($title);
3166: $linktext = &mt($linktext);
3167: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3168: &help_open_topic('View_recent_activity');
3169: }
3170:
3171: sub slot_reservations_link {
3172: my ($linktext,$sname,$sdom,$target) = @_;
3173: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3174: my $title = 'View slot reservation history';
3175: if (defined($sname) && $sname !~ /^\s*$/ &&
3176: defined($sdom) && $sdom !~ /^\s*$/) {
3177: $link .= "&uname=$sname&udom=$sdom";
3178: $title .= ' of this student';
3179: }
3180: if (defined($target) && $target !~ /^\s*$/) {
3181: $target = qq{target="$target"};
3182: } else {
3183: $target = '';
3184: }
3185: $title = &mt($title);
3186: $linktext = &mt($linktext);
3187: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3188: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3189:
3190: }
3191:
3192: # ===================================================== Display a student photo
3193:
3194:
3195: sub student_image_tag {
3196: my ($domain,$user)=@_;
3197: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3198: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3199: return '<img src="'.$imgsrc.'" align="right" />';
3200: } else {
3201: return '';
3202: }
3203: }
3204:
3205: =pod
3206:
3207: =back
3208:
3209: =head1 Access .tab File Data
3210:
3211: =over 4
3212:
3213: =item * &languageids()
3214:
3215: returns list of all language ids
3216:
3217: =cut
3218:
3219: sub languageids {
3220: return sort(keys(%language));
3221: }
3222:
3223: =pod
3224:
3225: =item * &languagedescription()
3226:
3227: returns description of a specified language id
3228:
3229: =cut
3230:
3231: sub languagedescription {
3232: my $code=shift;
3233: return ($supported_language{$code}?'* ':'').
3234: $language{$code}.
3235: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3236: }
3237:
3238: =pod
3239:
3240: =item * &plainlanguagedescription
3241:
3242: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3243: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3244:
3245: =cut
3246:
3247: sub plainlanguagedescription {
3248: my $code=shift;
3249: return $language{$code};
3250: }
3251:
3252: =pod
3253:
3254: =item * &supportedlanguagecode
3255:
3256: Returns the supported language code (e.g. sptutf maps to pt) given a language
3257: code.
3258:
3259: =cut
3260:
3261: sub supportedlanguagecode {
3262: my $code=shift;
3263: return $supported_language{$code};
3264: }
3265:
3266: =pod
3267:
3268: =item * &latexlanguage()
3269:
3270: Given a language key code returns the correspondnig language to use
3271: to select the correct hyphenation on LaTeX printouts. This is undef if there
3272: is no supported hyphenation for the language code.
3273:
3274: =cut
3275:
3276: sub latexlanguage {
3277: my $code = shift;
3278: return $latex_language{$code};
3279: }
3280:
3281: =pod
3282:
3283: =item * &latexhyphenation()
3284:
3285: Same as above but what's supplied is the language as it might be stored
3286: in the metadata.
3287:
3288: =cut
3289:
3290: sub latexhyphenation {
3291: my $key = shift;
3292: return $latex_language_bykey{$key};
3293: }
3294:
3295: =pod
3296:
3297: =item * ©rightids()
3298:
3299: returns list of all copyrights
3300:
3301: =cut
3302:
3303: sub copyrightids {
3304: return sort(keys(%cprtag));
3305: }
3306:
3307: =pod
3308:
3309: =item * ©rightdescription()
3310:
3311: returns description of a specified copyright id
3312:
3313: =cut
3314:
3315: sub copyrightdescription {
3316: return &mt($cprtag{shift(@_)});
3317: }
3318:
3319: =pod
3320:
3321: =item * &source_copyrightids()
3322:
3323: returns list of all source copyrights
3324:
3325: =cut
3326:
3327: sub source_copyrightids {
3328: return sort(keys(%scprtag));
3329: }
3330:
3331: =pod
3332:
3333: =item * &source_copyrightdescription()
3334:
3335: returns description of a specified source copyright id
3336:
3337: =cut
3338:
3339: sub source_copyrightdescription {
3340: return &mt($scprtag{shift(@_)});
3341: }
3342:
3343: =pod
3344:
3345: =item * &filecategories()
3346:
3347: returns list of all file categories
3348:
3349: =cut
3350:
3351: sub filecategories {
3352: return sort(keys(%category_extensions));
3353: }
3354:
3355: =pod
3356:
3357: =item * &filecategorytypes()
3358:
3359: returns list of file types belonging to a given file
3360: category
3361:
3362: =cut
3363:
3364: sub filecategorytypes {
3365: my ($cat) = @_;
3366: return @{$category_extensions{lc($cat)}};
3367: }
3368:
3369: =pod
3370:
3371: =item * &fileembstyle()
3372:
3373: returns embedding style for a specified file type
3374:
3375: =cut
3376:
3377: sub fileembstyle {
3378: return $fe{lc(shift(@_))};
3379: }
3380:
3381: sub filemimetype {
3382: return $fm{lc(shift(@_))};
3383: }
3384:
3385:
3386: sub filecategoryselect {
3387: my ($name,$value)=@_;
3388: return &select_form($value,$name,
3389: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3390: }
3391:
3392: =pod
3393:
3394: =item * &filedescription()
3395:
3396: returns description for a specified file type
3397:
3398: =cut
3399:
3400: sub filedescription {
3401: my $file_description = $fd{lc(shift())};
3402: $file_description =~ s:([\[\]]):~$1:g;
3403: return &mt($file_description);
3404: }
3405:
3406: =pod
3407:
3408: =item * &filedescriptionex()
3409:
3410: returns description for a specified file type with
3411: extra formatting
3412:
3413: =cut
3414:
3415: sub filedescriptionex {
3416: my $ex=shift;
3417: my $file_description = $fd{lc($ex)};
3418: $file_description =~ s:([\[\]]):~$1:g;
3419: return '.'.$ex.' '.&mt($file_description);
3420: }
3421:
3422: # End of .tab access
3423: =pod
3424:
3425: =back
3426:
3427: =cut
3428:
3429: # ------------------------------------------------------------------ File Types
3430: sub fileextensions {
3431: return sort(keys(%fe));
3432: }
3433:
3434: # ----------------------------------------------------------- Display Languages
3435: # returns a hash with all desired display languages
3436: #
3437:
3438: sub display_languages {
3439: my %languages=();
3440: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3441: $languages{$lang}=1;
3442: }
3443: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3444: if ($env{'form.displaylanguage'}) {
3445: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3446: $languages{$lang}=1;
3447: }
3448: }
3449: return %languages;
3450: }
3451:
3452: sub languages {
3453: my ($possible_langs) = @_;
3454: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3455: if (!ref($possible_langs)) {
3456: if( wantarray ) {
3457: return @preferred_langs;
3458: } else {
3459: return $preferred_langs[0];
3460: }
3461: }
3462: my %possibilities = map { $_ => 1 } (@$possible_langs);
3463: my @preferred_possibilities;
3464: foreach my $preferred_lang (@preferred_langs) {
3465: if (exists($possibilities{$preferred_lang})) {
3466: push(@preferred_possibilities, $preferred_lang);
3467: }
3468: }
3469: if( wantarray ) {
3470: return @preferred_possibilities;
3471: }
3472: return $preferred_possibilities[0];
3473: }
3474:
3475: sub user_lang {
3476: my ($touname,$toudom,$fromcid) = @_;
3477: my @userlangs;
3478: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3479: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3480: $env{'course.'.$fromcid.'.languages'}));
3481: } else {
3482: my %langhash = &getlangs($touname,$toudom);
3483: if ($langhash{'languages'} ne '') {
3484: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3485: } else {
3486: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3487: if ($domdefs{'lang_def'} ne '') {
3488: @userlangs = ($domdefs{'lang_def'});
3489: }
3490: }
3491: }
3492: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3493: my $user_lh = Apache::localize->get_handle(@languages);
3494: return $user_lh;
3495: }
3496:
3497:
3498: ###############################################################
3499: ## Student Answer Attempts ##
3500: ###############################################################
3501:
3502: =pod
3503:
3504: =head1 Alternate Problem Views
3505:
3506: =over 4
3507:
3508: =item * &get_previous_attempt($symb, $username, $domain, $course,
3509: $getattempt, $regexp, $gradesub)
3510:
3511: Return string with previous attempt on problem. Arguments:
3512:
3513: =over 4
3514:
3515: =item * $symb: Problem, including path
3516:
3517: =item * $username: username of the desired student
3518:
3519: =item * $domain: domain of the desired student
3520:
3521: =item * $course: Course ID
3522:
3523: =item * $getattempt: Leave blank for all attempts, otherwise put
3524: something
3525:
3526: =item * $regexp: if string matches this regexp, the string will be
3527: sent to $gradesub
3528:
3529: =item * $gradesub: routine that processes the string if it matches $regexp
3530:
3531: =back
3532:
3533: The output string is a table containing all desired attempts, if any.
3534:
3535: =cut
3536:
3537: sub get_previous_attempt {
3538: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3539: my $prevattempts='';
3540: no strict 'refs';
3541: if ($symb) {
3542: my (%returnhash)=
3543: &Apache::lonnet::restore($symb,$course,$domain,$username);
3544: if ($returnhash{'version'}) {
3545: my %lasthash=();
3546: my $version;
3547: for ($version=1;$version<=$returnhash{'version'};$version++) {
3548: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3549: $lasthash{$key}=$returnhash{$version.':'.$key};
3550: }
3551: }
3552: $prevattempts=&start_data_table().&start_data_table_header_row();
3553: $prevattempts.='<th>'.&mt('History').'</th>';
3554: my (%typeparts,%lasthidden);
3555: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3556: foreach my $key (sort(keys(%lasthash))) {
3557: my ($ign,@parts) = split(/\./,$key);
3558: if ($#parts > 0) {
3559: my $data=$parts[-1];
3560: next if ($data eq 'foilorder');
3561: pop(@parts);
3562: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3563: if ($data eq 'type') {
3564: unless ($showsurv) {
3565: my $id = join(',',@parts);
3566: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3567: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3568: $lasthidden{$ign.'.'.$id} = 1;
3569: }
3570: }
3571: }
3572: } else {
3573: if ($#parts == 0) {
3574: $prevattempts.='<th>'.$parts[0].'</th>';
3575: } else {
3576: $prevattempts.='<th>'.$ign.'</th>';
3577: }
3578: }
3579: }
3580: $prevattempts.=&end_data_table_header_row();
3581: if ($getattempt eq '') {
3582: for ($version=1;$version<=$returnhash{'version'};$version++) {
3583: my @hidden;
3584: if (%typeparts) {
3585: foreach my $id (keys(%typeparts)) {
3586: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3587: push(@hidden,$id);
3588: }
3589: }
3590: }
3591: $prevattempts.=&start_data_table_row().
3592: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3593: if (@hidden) {
3594: foreach my $key (sort(keys(%lasthash))) {
3595: next if ($key =~ /\.foilorder$/);
3596: my $hide;
3597: foreach my $id (@hidden) {
3598: if ($key =~ /^\Q$id\E/) {
3599: $hide = 1;
3600: last;
3601: }
3602: }
3603: if ($hide) {
3604: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3605: if (($data eq 'award') || ($data eq 'awarddetail')) {
3606: my $value = &format_previous_attempt_value($key,
3607: $returnhash{$version.':'.$key});
3608: $prevattempts.='<td>'.$value.' </td>';
3609: } else {
3610: $prevattempts.='<td> </td>';
3611: }
3612: } else {
3613: if ($key =~ /\./) {
3614: my $value = &format_previous_attempt_value($key,
3615: $returnhash{$version.':'.$key});
3616: $prevattempts.='<td>'.$value.' </td>';
3617: } else {
3618: $prevattempts.='<td> </td>';
3619: }
3620: }
3621: }
3622: } else {
3623: foreach my $key (sort(keys(%lasthash))) {
3624: next if ($key =~ /\.foilorder$/);
3625: my $value = &format_previous_attempt_value($key,
3626: $returnhash{$version.':'.$key});
3627: $prevattempts.='<td>'.$value.' </td>';
3628: }
3629: }
3630: $prevattempts.=&end_data_table_row();
3631: }
3632: }
3633: my @currhidden = keys(%lasthidden);
3634: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3635: foreach my $key (sort(keys(%lasthash))) {
3636: next if ($key =~ /\.foilorder$/);
3637: if (%typeparts) {
3638: my $hidden;
3639: foreach my $id (@currhidden) {
3640: if ($key =~ /^\Q$id\E/) {
3641: $hidden = 1;
3642: last;
3643: }
3644: }
3645: if ($hidden) {
3646: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3647: if (($data eq 'award') || ($data eq 'awarddetail')) {
3648: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3649: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3650: $value = &$gradesub($value);
3651: }
3652: $prevattempts.='<td>'.$value.' </td>';
3653: } else {
3654: $prevattempts.='<td> </td>';
3655: }
3656: } else {
3657: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3658: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3659: $value = &$gradesub($value);
3660: }
3661: $prevattempts.='<td>'.$value.' </td>';
3662: }
3663: } else {
3664: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3665: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3666: $value = &$gradesub($value);
3667: }
3668: $prevattempts.='<td>'.$value.' </td>';
3669: }
3670: }
3671: $prevattempts.= &end_data_table_row().&end_data_table();
3672: } else {
3673: $prevattempts=
3674: &start_data_table().&start_data_table_row().
3675: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3676: &end_data_table_row().&end_data_table();
3677: }
3678: } else {
3679: $prevattempts=
3680: &start_data_table().&start_data_table_row().
3681: '<td>'.&mt('No data.').'</td>'.
3682: &end_data_table_row().&end_data_table();
3683: }
3684: }
3685:
3686: sub format_previous_attempt_value {
3687: my ($key,$value) = @_;
3688: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3689: $value = &Apache::lonlocal::locallocaltime($value);
3690: } elsif (ref($value) eq 'ARRAY') {
3691: $value = '('.join(', ', @{ $value }).')';
3692: } elsif ($key =~ /answerstring$/) {
3693: my %answers = &Apache::lonnet::str2hash($value);
3694: my @anskeys = sort(keys(%answers));
3695: if (@anskeys == 1) {
3696: my $answer = $answers{$anskeys[0]};
3697: if ($answer =~ m{\0}) {
3698: $answer =~ s{\0}{,}g;
3699: }
3700: my $tag_internal_answer_name = 'INTERNAL';
3701: if ($anskeys[0] eq $tag_internal_answer_name) {
3702: $value = $answer;
3703: } else {
3704: $value = $anskeys[0].'='.$answer;
3705: }
3706: } else {
3707: foreach my $ans (@anskeys) {
3708: my $answer = $answers{$ans};
3709: if ($answer =~ m{\0}) {
3710: $answer =~ s{\0}{,}g;
3711: }
3712: $value .= $ans.'='.$answer.'<br />';;
3713: }
3714: }
3715: } else {
3716: $value = &unescape($value);
3717: }
3718: return $value;
3719: }
3720:
3721:
3722: sub relative_to_absolute {
3723: my ($url,$output)=@_;
3724: my $parser=HTML::TokeParser->new(\$output);
3725: my $token;
3726: my $thisdir=$url;
3727: my @rlinks=();
3728: while ($token=$parser->get_token) {
3729: if ($token->[0] eq 'S') {
3730: if ($token->[1] eq 'a') {
3731: if ($token->[2]->{'href'}) {
3732: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3733: }
3734: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3735: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3736: } elsif ($token->[1] eq 'base') {
3737: $thisdir=$token->[2]->{'href'};
3738: }
3739: }
3740: }
3741: $thisdir=~s-/[^/]*$--;
3742: foreach my $link (@rlinks) {
3743: unless (($link=~/^https?\:\/\//i) ||
3744: ($link=~/^\//) ||
3745: ($link=~/^javascript:/i) ||
3746: ($link=~/^mailto:/i) ||
3747: ($link=~/^\#/)) {
3748: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3749: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3750: }
3751: }
3752: # -------------------------------------------------- Deal with Applet codebases
3753: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3754: return $output;
3755: }
3756:
3757: =pod
3758:
3759: =item * &get_student_view()
3760:
3761: show a snapshot of what student was looking at
3762:
3763: =cut
3764:
3765: sub get_student_view {
3766: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3767: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3768: my (%form);
3769: my @elements=('symb','courseid','domain','username');
3770: foreach my $element (@elements) {
3771: $form{'grade_'.$element}=eval '$'.$element #'
3772: }
3773: if (defined($moreenv)) {
3774: %form=(%form,%{$moreenv});
3775: }
3776: if (defined($target)) { $form{'grade_target'} = $target; }
3777: $feedurl=&Apache::lonnet::clutter($feedurl);
3778: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3779: $userview=~s/\<body[^\>]*\>//gi;
3780: $userview=~s/\<\/body\>//gi;
3781: $userview=~s/\<html\>//gi;
3782: $userview=~s/\<\/html\>//gi;
3783: $userview=~s/\<head\>//gi;
3784: $userview=~s/\<\/head\>//gi;
3785: $userview=~s/action\s*\=/would_be_action\=/gi;
3786: $userview=&relative_to_absolute($feedurl,$userview);
3787: if (wantarray) {
3788: return ($userview,$response);
3789: } else {
3790: return $userview;
3791: }
3792: }
3793:
3794: sub get_student_view_with_retries {
3795: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3796:
3797: my $ok = 0; # True if we got a good response.
3798: my $content;
3799: my $response;
3800:
3801: # Try to get the student_view done. within the retries count:
3802:
3803: do {
3804: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3805: $ok = $response->is_success;
3806: if (!$ok) {
3807: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3808: }
3809: $retries--;
3810: } while (!$ok && ($retries > 0));
3811:
3812: if (!$ok) {
3813: $content = ''; # On error return an empty content.
3814: }
3815: if (wantarray) {
3816: return ($content, $response);
3817: } else {
3818: return $content;
3819: }
3820: }
3821:
3822: =pod
3823:
3824: =item * &get_student_answers()
3825:
3826: show a snapshot of how student was answering problem
3827:
3828: =cut
3829:
3830: sub get_student_answers {
3831: my ($symb,$username,$domain,$courseid,%form) = @_;
3832: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3833: my (%moreenv);
3834: my @elements=('symb','courseid','domain','username');
3835: foreach my $element (@elements) {
3836: $moreenv{'grade_'.$element}=eval '$'.$element #'
3837: }
3838: $moreenv{'grade_target'}='answer';
3839: %moreenv=(%form,%moreenv);
3840: $feedurl = &Apache::lonnet::clutter($feedurl);
3841: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3842: return $userview;
3843: }
3844:
3845: =pod
3846:
3847: =item * &submlink()
3848:
3849: Inputs: $text $uname $udom $symb $target
3850:
3851: Returns: A link to grades.pm such as to see the SUBM view of a student
3852:
3853: =cut
3854:
3855: ###############################################
3856: sub submlink {
3857: my ($text,$uname,$udom,$symb,$target)=@_;
3858: if (!($uname && $udom)) {
3859: (my $cursymb, my $courseid,$udom,$uname)=
3860: &Apache::lonnet::whichuser($symb);
3861: if (!$symb) { $symb=$cursymb; }
3862: }
3863: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3864: $symb=&escape($symb);
3865: if ($target) { $target=" target=\"$target\""; }
3866: return
3867: '<a href="/adm/grades?command=submission'.
3868: '&symb='.$symb.
3869: '&student='.$uname.
3870: '&userdom='.$udom.'"'.
3871: $target.'>'.$text.'</a>';
3872: }
3873: ##############################################
3874:
3875: =pod
3876:
3877: =item * &pgrdlink()
3878:
3879: Inputs: $text $uname $udom $symb $target
3880:
3881: Returns: A link to grades.pm such as to see the PGRD view of a student
3882:
3883: =cut
3884:
3885: ###############################################
3886: sub pgrdlink {
3887: my $link=&submlink(@_);
3888: $link=~s/(&command=submission)/$1&showgrading=yes/;
3889: return $link;
3890: }
3891: ##############################################
3892:
3893: =pod
3894:
3895: =item * &pprmlink()
3896:
3897: Inputs: $text $uname $udom $symb $target
3898:
3899: Returns: A link to parmset.pm such as to see the PPRM view of a
3900: student and a specific resource
3901:
3902: =cut
3903:
3904: ###############################################
3905: sub pprmlink {
3906: my ($text,$uname,$udom,$symb,$target)=@_;
3907: if (!($uname && $udom)) {
3908: (my $cursymb, my $courseid,$udom,$uname)=
3909: &Apache::lonnet::whichuser($symb);
3910: if (!$symb) { $symb=$cursymb; }
3911: }
3912: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3913: $symb=&escape($symb);
3914: if ($target) { $target="target=\"$target\""; }
3915: return '<a href="/adm/parmset?command=set&'.
3916: 'symb='.$symb.'&uname='.$uname.
3917: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3918: }
3919: ##############################################
3920:
3921: =pod
3922:
3923: =back
3924:
3925: =cut
3926:
3927: ###############################################
3928:
3929:
3930: sub timehash {
3931: my ($thistime) = @_;
3932: my $timezone = &Apache::lonlocal::gettimezone();
3933: my $dt = DateTime->from_epoch(epoch => $thistime)
3934: ->set_time_zone($timezone);
3935: my $wday = $dt->day_of_week();
3936: if ($wday == 7) { $wday = 0; }
3937: return ( 'second' => $dt->second(),
3938: 'minute' => $dt->minute(),
3939: 'hour' => $dt->hour(),
3940: 'day' => $dt->day_of_month(),
3941: 'month' => $dt->month(),
3942: 'year' => $dt->year(),
3943: 'weekday' => $wday,
3944: 'dayyear' => $dt->day_of_year(),
3945: 'dlsav' => $dt->is_dst() );
3946: }
3947:
3948: sub utc_string {
3949: my ($date)=@_;
3950: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3951: }
3952:
3953: sub maketime {
3954: my %th=@_;
3955: my ($epoch_time,$timezone,$dt);
3956: $timezone = &Apache::lonlocal::gettimezone();
3957: eval {
3958: $dt = DateTime->new( year => $th{'year'},
3959: month => $th{'month'},
3960: day => $th{'day'},
3961: hour => $th{'hour'},
3962: minute => $th{'minute'},
3963: second => $th{'second'},
3964: time_zone => $timezone,
3965: );
3966: };
3967: if (!$@) {
3968: $epoch_time = $dt->epoch;
3969: if ($epoch_time) {
3970: return $epoch_time;
3971: }
3972: }
3973: return POSIX::mktime(
3974: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3975: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3976: }
3977:
3978: #########################################
3979:
3980: sub findallcourses {
3981: my ($roles,$uname,$udom) = @_;
3982: my %roles;
3983: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3984: my %courses;
3985: my $now=time;
3986: if (!defined($uname)) {
3987: $uname = $env{'user.name'};
3988: }
3989: if (!defined($udom)) {
3990: $udom = $env{'user.domain'};
3991: }
3992: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3993: my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
3994: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
3995: $extra);
3996: if (!%roles) {
3997: %roles = (
3998: cc => 1,
3999: co => 1,
4000: in => 1,
4001: ep => 1,
4002: ta => 1,
4003: cr => 1,
4004: st => 1,
4005: );
4006: }
4007: foreach my $entry (keys(%roleshash)) {
4008: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4009: if ($trole =~ /^cr/) {
4010: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4011: } else {
4012: next if (!exists($roles{$trole}));
4013: }
4014: if ($tend) {
4015: next if ($tend < $now);
4016: }
4017: if ($tstart) {
4018: next if ($tstart > $now);
4019: }
4020: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4021: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4022: my $value = $trole.'/'.$cdom.'/';
4023: if ($secpart eq '') {
4024: ($cnum,$role) = split(/_/,$cnumpart);
4025: $sec = 'none';
4026: $value .= $cnum.'/';
4027: } else {
4028: $cnum = $cnumpart;
4029: ($sec,$role) = split(/_/,$secpart);
4030: $value .= $cnum.'/'.$sec;
4031: }
4032: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4033: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4034: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4035: }
4036: } else {
4037: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4038: }
4039: }
4040: } else {
4041: foreach my $key (keys(%env)) {
4042: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4043: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4044: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4045: next if ($role eq 'ca' || $role eq 'aa');
4046: next if (%roles && !exists($roles{$role}));
4047: my ($starttime,$endtime)=split(/\./,$env{$key});
4048: my $active=1;
4049: if ($starttime) {
4050: if ($now<$starttime) { $active=0; }
4051: }
4052: if ($endtime) {
4053: if ($now>$endtime) { $active=0; }
4054: }
4055: if ($active) {
4056: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4057: if ($sec eq '') {
4058: $sec = 'none';
4059: } else {
4060: $value .= $sec;
4061: }
4062: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4063: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4064: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4065: }
4066: } else {
4067: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4068: }
4069: }
4070: }
4071: }
4072: }
4073: return %courses;
4074: }
4075:
4076: ###############################################
4077:
4078: sub blockcheck {
4079: my ($setters,$activity,$uname,$udom,$url) = @_;
4080:
4081: if (!defined($udom)) {
4082: $udom = $env{'user.domain'};
4083: }
4084: if (!defined($uname)) {
4085: $uname = $env{'user.name'};
4086: }
4087:
4088: # If uname and udom are for a course, check for blocks in the course.
4089:
4090: if (&Apache::lonnet::is_course($udom,$uname)) {
4091: my ($startblock,$endblock,$triggerblock) =
4092: &get_blocks($setters,$activity,$udom,$uname,$url);
4093: return ($startblock,$endblock,$triggerblock);
4094: }
4095:
4096: my $startblock = 0;
4097: my $endblock = 0;
4098: my $triggerblock = '';
4099: my %live_courses = &findallcourses(undef,$uname,$udom);
4100:
4101: # If uname is for a user, and activity is course-specific, i.e.,
4102: # boards, chat or groups, check for blocking in current course only.
4103:
4104: if (($activity eq 'boards' || $activity eq 'chat' ||
4105: $activity eq 'groups') && ($env{'request.course.id'})) {
4106: foreach my $key (keys(%live_courses)) {
4107: if ($key ne $env{'request.course.id'}) {
4108: delete($live_courses{$key});
4109: }
4110: }
4111: }
4112:
4113: my $otheruser = 0;
4114: my %own_courses;
4115: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4116: # Resource belongs to user other than current user.
4117: $otheruser = 1;
4118: # Gather courses for current user
4119: %own_courses =
4120: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4121: }
4122:
4123: # Gather active course roles - course coordinator, instructor,
4124: # exam proctor, ta, student, or custom role.
4125:
4126: foreach my $course (keys(%live_courses)) {
4127: my ($cdom,$cnum);
4128: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4129: $cdom = $env{'course.'.$course.'.domain'};
4130: $cnum = $env{'course.'.$course.'.num'};
4131: } else {
4132: ($cdom,$cnum) = split(/_/,$course);
4133: }
4134: my $no_ownblock = 0;
4135: my $no_userblock = 0;
4136: if ($otheruser && $activity ne 'com') {
4137: # Check if current user has 'evb' priv for this
4138: if (defined($own_courses{$course})) {
4139: foreach my $sec (keys(%{$own_courses{$course}})) {
4140: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4141: if ($sec ne 'none') {
4142: $checkrole .= '/'.$sec;
4143: }
4144: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4145: $no_ownblock = 1;
4146: last;
4147: }
4148: }
4149: }
4150: # if they have 'evb' priv and are currently not playing student
4151: next if (($no_ownblock) &&
4152: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4153: }
4154: foreach my $sec (keys(%{$live_courses{$course}})) {
4155: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4156: if ($sec ne 'none') {
4157: $checkrole .= '/'.$sec;
4158: }
4159: if ($otheruser) {
4160: # Resource belongs to user other than current user.
4161: # Assemble privs for that user, and check for 'evb' priv.
4162: my (%allroles,%userroles);
4163: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4164: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4165: my ($trole,$tdom,$tnum,$tsec);
4166: if ($entry =~ /^cr/) {
4167: ($trole,$tdom,$tnum,$tsec) =
4168: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4169: } else {
4170: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4171: }
4172: my ($spec,$area,$trest);
4173: $area = '/'.$tdom.'/'.$tnum;
4174: $trest = $tnum;
4175: if ($tsec ne '') {
4176: $area .= '/'.$tsec;
4177: $trest .= '/'.$tsec;
4178: }
4179: $spec = $trole.'.'.$area;
4180: if ($trole =~ /^cr/) {
4181: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4182: $tdom,$spec,$trest,$area);
4183: } else {
4184: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4185: $tdom,$spec,$trest,$area);
4186: }
4187: }
4188: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4189: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4190: if ($1) {
4191: $no_userblock = 1;
4192: last;
4193: }
4194: }
4195: }
4196: } else {
4197: # Resource belongs to current user
4198: # Check for 'evb' priv via lonnet::allowed().
4199: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4200: $no_ownblock = 1;
4201: last;
4202: }
4203: }
4204: }
4205: # if they have the evb priv and are currently not playing student
4206: next if (($no_ownblock) &&
4207: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4208: next if ($no_userblock);
4209:
4210: # Retrieve blocking times and identity of locker for course
4211: # of specified user, unless user has 'evb' privilege.
4212:
4213: my ($start,$end,$trigger) =
4214: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4215: if (($start != 0) &&
4216: (($startblock == 0) || ($startblock > $start))) {
4217: $startblock = $start;
4218: if ($trigger ne '') {
4219: $triggerblock = $trigger;
4220: }
4221: }
4222: if (($end != 0) &&
4223: (($endblock == 0) || ($endblock < $end))) {
4224: $endblock = $end;
4225: if ($trigger ne '') {
4226: $triggerblock = $trigger;
4227: }
4228: }
4229: }
4230: return ($startblock,$endblock,$triggerblock);
4231: }
4232:
4233: sub get_blocks {
4234: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4235: my $startblock = 0;
4236: my $endblock = 0;
4237: my $triggerblock = '';
4238: my $course = $cdom.'_'.$cnum;
4239: $setters->{$course} = {};
4240: $setters->{$course}{'staff'} = [];
4241: $setters->{$course}{'times'} = [];
4242: $setters->{$course}{'triggers'} = [];
4243: my (@blockers,%triggered);
4244: my $now = time;
4245: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4246: if ($activity eq 'docs') {
4247: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4248: foreach my $block (@blockers) {
4249: if ($block =~ /^firstaccess____(.+)$/) {
4250: my $item = $1;
4251: my $type = 'map';
4252: my $timersymb = $item;
4253: if ($item eq 'course') {
4254: $type = 'course';
4255: } elsif ($item =~ /___\d+___/) {
4256: $type = 'resource';
4257: } else {
4258: $timersymb = &Apache::lonnet::symbread($item);
4259: }
4260: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4261: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4262: $triggered{$block} = {
4263: start => $start,
4264: end => $end,
4265: type => $type,
4266: };
4267: }
4268: }
4269: } else {
4270: foreach my $block (keys(%commblocks)) {
4271: if ($block =~ m/^(\d+)____(\d+)$/) {
4272: my ($start,$end) = ($1,$2);
4273: if ($start <= time && $end >= time) {
4274: if (ref($commblocks{$block}) eq 'HASH') {
4275: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4276: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4277: unless(grep(/^\Q$block\E$/,@blockers)) {
4278: push(@blockers,$block);
4279: }
4280: }
4281: }
4282: }
4283: }
4284: } elsif ($block =~ /^firstaccess____(.+)$/) {
4285: my $item = $1;
4286: my $timersymb = $item;
4287: my $type = 'map';
4288: if ($item eq 'course') {
4289: $type = 'course';
4290: } elsif ($item =~ /___\d+___/) {
4291: $type = 'resource';
4292: } else {
4293: $timersymb = &Apache::lonnet::symbread($item);
4294: }
4295: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4296: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4297: if ($start && $end) {
4298: if (($start <= time) && ($end >= time)) {
4299: unless (grep(/^\Q$block\E$/,@blockers)) {
4300: push(@blockers,$block);
4301: $triggered{$block} = {
4302: start => $start,
4303: end => $end,
4304: type => $type,
4305: };
4306: }
4307: }
4308: }
4309: }
4310: }
4311: }
4312: foreach my $blocker (@blockers) {
4313: my ($staff_name,$staff_dom,$title,$blocks) =
4314: &parse_block_record($commblocks{$blocker});
4315: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4316: my ($start,$end,$triggertype);
4317: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4318: ($start,$end) = ($1,$2);
4319: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4320: $start = $triggered{$blocker}{'start'};
4321: $end = $triggered{$blocker}{'end'};
4322: $triggertype = $triggered{$blocker}{'type'};
4323: }
4324: if ($start) {
4325: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4326: if ($triggertype) {
4327: push(@{$$setters{$course}{'triggers'}},$triggertype);
4328: } else {
4329: push(@{$$setters{$course}{'triggers'}},0);
4330: }
4331: if ( ($startblock == 0) || ($startblock > $start) ) {
4332: $startblock = $start;
4333: if ($triggertype) {
4334: $triggerblock = $blocker;
4335: }
4336: }
4337: if ( ($endblock == 0) || ($endblock < $end) ) {
4338: $endblock = $end;
4339: if ($triggertype) {
4340: $triggerblock = $blocker;
4341: }
4342: }
4343: }
4344: }
4345: return ($startblock,$endblock,$triggerblock);
4346: }
4347:
4348: sub parse_block_record {
4349: my ($record) = @_;
4350: my ($setuname,$setudom,$title,$blocks);
4351: if (ref($record) eq 'HASH') {
4352: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4353: $title = &unescape($record->{'event'});
4354: $blocks = $record->{'blocks'};
4355: } else {
4356: my @data = split(/:/,$record,3);
4357: if (scalar(@data) eq 2) {
4358: $title = $data[1];
4359: ($setuname,$setudom) = split(/@/,$data[0]);
4360: } else {
4361: ($setuname,$setudom,$title) = @data;
4362: }
4363: $blocks = { 'com' => 'on' };
4364: }
4365: return ($setuname,$setudom,$title,$blocks);
4366: }
4367:
4368: sub blocking_status {
4369: my ($activity,$uname,$udom,$url) = @_;
4370: my %setters;
4371:
4372: # check for active blocking
4373: my ($startblock,$endblock,$triggerblock) =
4374: &blockcheck(\%setters,$activity,$uname,$udom,$url);
4375: my $blocked = 0;
4376: if ($startblock && $endblock) {
4377: $blocked = 1;
4378: }
4379:
4380: # caller just wants to know whether a block is active
4381: if (!wantarray) { return $blocked; }
4382:
4383: # build a link to a popup window containing the details
4384: my $querystring = "?activity=$activity";
4385: # $uname and $udom decide whose portfolio the user is trying to look at
4386: if ($activity eq 'port') {
4387: $querystring .= "&udom=$udom" if $udom;
4388: $querystring .= "&uname=$uname" if $uname;
4389: } elsif ($activity eq 'docs') {
4390: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4391: }
4392:
4393: my $output .= <<'END_MYBLOCK';
4394: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4395: var options = "width=" + w + ",height=" + h + ",";
4396: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4397: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4398: var newWin = window.open(url, wdwName, options);
4399: newWin.focus();
4400: }
4401: END_MYBLOCK
4402:
4403: $output = Apache::lonhtmlcommon::scripttag($output);
4404:
4405: my $popupUrl = "/adm/blockingstatus/$querystring";
4406: my $text = &mt('Communication Blocked');
4407: if ($activity eq 'docs') {
4408: $text = &mt('Content Access Blocked');
4409: } elsif ($activity eq 'printout') {
4410: $text = &mt('Printing Blocked');
4411: }
4412: $output .= <<"END_BLOCK";
4413: <div class='LC_comblock'>
4414: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4415: title='$text'>
4416: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4417: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4418: title='$text'>$text</a>
4419: </div>
4420:
4421: END_BLOCK
4422:
4423: return ($blocked, $output);
4424: }
4425:
4426: ###############################################
4427:
4428: sub check_ip_acc {
4429: my ($acc)=@_;
4430: &Apache::lonxml::debug("acc is $acc");
4431: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4432: return 1;
4433: }
4434: my $allowed=0;
4435: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4436:
4437: my $name;
4438: foreach my $pattern (split(',',$acc)) {
4439: $pattern =~ s/^\s*//;
4440: $pattern =~ s/\s*$//;
4441: if ($pattern =~ /\*$/) {
4442: #35.8.*
4443: $pattern=~s/\*//;
4444: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4445: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4446: #35.8.3.[34-56]
4447: my $low=$2;
4448: my $high=$3;
4449: $pattern=$1;
4450: if ($ip =~ /^\Q$pattern\E/) {
4451: my $last=(split(/\./,$ip))[3];
4452: if ($last <=$high && $last >=$low) { $allowed=1; }
4453: }
4454: } elsif ($pattern =~ /^\*/) {
4455: #*.msu.edu
4456: $pattern=~s/\*//;
4457: if (!defined($name)) {
4458: use Socket;
4459: my $netaddr=inet_aton($ip);
4460: ($name)=gethostbyaddr($netaddr,AF_INET);
4461: }
4462: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4463: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4464: #127.0.0.1
4465: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4466: } else {
4467: #some.name.com
4468: if (!defined($name)) {
4469: use Socket;
4470: my $netaddr=inet_aton($ip);
4471: ($name)=gethostbyaddr($netaddr,AF_INET);
4472: }
4473: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4474: }
4475: if ($allowed) { last; }
4476: }
4477: return $allowed;
4478: }
4479:
4480: ###############################################
4481:
4482: =pod
4483:
4484: =head1 Domain Template Functions
4485:
4486: =over 4
4487:
4488: =item * &determinedomain()
4489:
4490: Inputs: $domain (usually will be undef)
4491:
4492: Returns: Determines which domain should be used for designs
4493:
4494: =cut
4495:
4496: ###############################################
4497: sub determinedomain {
4498: my $domain=shift;
4499: if (! $domain) {
4500: # Determine domain if we have not been given one
4501: $domain = &Apache::lonnet::default_login_domain();
4502: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4503: if ($env{'request.role.domain'}) {
4504: $domain=$env{'request.role.domain'};
4505: }
4506: }
4507: return $domain;
4508: }
4509: ###############################################
4510:
4511: sub devalidate_domconfig_cache {
4512: my ($udom)=@_;
4513: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4514: }
4515:
4516: # ---------------------- Get domain configuration for a domain
4517: sub get_domainconf {
4518: my ($udom) = @_;
4519: my $cachetime=1800;
4520: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4521: if (defined($cached)) { return %{$result}; }
4522:
4523: my %domconfig = &Apache::lonnet::get_dom('configuration',
4524: ['login','rolecolors','autoenroll'],$udom);
4525: my (%designhash,%legacy);
4526: if (keys(%domconfig) > 0) {
4527: if (ref($domconfig{'login'}) eq 'HASH') {
4528: if (keys(%{$domconfig{'login'}})) {
4529: foreach my $key (keys(%{$domconfig{'login'}})) {
4530: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4531: if ($key eq 'loginvia') {
4532: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4533: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4534: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4535: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4536: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4537: $designhash{$udom.'.login.loginvia'} = $server;
4538: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4539:
4540: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4541: } else {
4542: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4543: }
4544: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4545: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4546: }
4547: }
4548: }
4549: }
4550: }
4551: } else {
4552: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4553: $designhash{$udom.'.login.'.$key.'_'.$img} =
4554: $domconfig{'login'}{$key}{$img};
4555: }
4556: }
4557: } else {
4558: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4559: }
4560: }
4561: } else {
4562: $legacy{'login'} = 1;
4563: }
4564: } else {
4565: $legacy{'login'} = 1;
4566: }
4567: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4568: if (keys(%{$domconfig{'rolecolors'}})) {
4569: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4570: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4571: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4572: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4573: }
4574: }
4575: }
4576: } else {
4577: $legacy{'rolecolors'} = 1;
4578: }
4579: } else {
4580: $legacy{'rolecolors'} = 1;
4581: }
4582: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4583: if ($domconfig{'autoenroll'}{'co-owners'}) {
4584: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4585: }
4586: }
4587: if (keys(%legacy) > 0) {
4588: my %legacyhash = &get_legacy_domconf($udom);
4589: foreach my $item (keys(%legacyhash)) {
4590: if ($item =~ /^\Q$udom\E\.login/) {
4591: if ($legacy{'login'}) {
4592: $designhash{$item} = $legacyhash{$item};
4593: }
4594: } else {
4595: if ($legacy{'rolecolors'}) {
4596: $designhash{$item} = $legacyhash{$item};
4597: }
4598: }
4599: }
4600: }
4601: } else {
4602: %designhash = &get_legacy_domconf($udom);
4603: }
4604: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4605: $cachetime);
4606: return %designhash;
4607: }
4608:
4609: sub get_legacy_domconf {
4610: my ($udom) = @_;
4611: my %legacyhash;
4612: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4613: my $designfile = $designdir.'/'.$udom.'.tab';
4614: if (-e $designfile) {
4615: if ( open (my $fh,"<$designfile") ) {
4616: while (my $line = <$fh>) {
4617: next if ($line =~ /^\#/);
4618: chomp($line);
4619: my ($key,$val)=(split(/\=/,$line));
4620: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4621: }
4622: close($fh);
4623: }
4624: }
4625: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4626: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4627: }
4628: return %legacyhash;
4629: }
4630:
4631: =pod
4632:
4633: =item * &domainlogo()
4634:
4635: Inputs: $domain (usually will be undef)
4636:
4637: Returns: A link to a domain logo, if the domain logo exists.
4638: If the domain logo does not exist, a description of the domain.
4639:
4640: =cut
4641:
4642: ###############################################
4643: sub domainlogo {
4644: my $domain = &determinedomain(shift);
4645: my %designhash = &get_domainconf($domain);
4646: # See if there is a logo
4647: if ($designhash{$domain.'.login.domlogo'} ne '') {
4648: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4649: if ($imgsrc =~ m{^/(adm|res)/}) {
4650: if ($imgsrc =~ m{^/res/}) {
4651: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4652: &Apache::lonnet::repcopy($local_name);
4653: }
4654: $imgsrc = &lonhttpdurl($imgsrc);
4655: }
4656: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4657: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4658: return &Apache::lonnet::domain($domain,'description');
4659: } else {
4660: return '';
4661: }
4662: }
4663: ##############################################
4664:
4665: =pod
4666:
4667: =item * &designparm()
4668:
4669: Inputs: $which parameter; $domain (usually will be undef)
4670:
4671: Returns: value of designparamter $which
4672:
4673: =cut
4674:
4675:
4676: ##############################################
4677: sub designparm {
4678: my ($which,$domain)=@_;
4679: if (exists($env{'environment.color.'.$which})) {
4680: return $env{'environment.color.'.$which};
4681: }
4682: $domain=&determinedomain($domain);
4683: my %domdesign;
4684: unless ($domain eq 'public') {
4685: %domdesign = &get_domainconf($domain);
4686: }
4687: my $output;
4688: if ($domdesign{$domain.'.'.$which} ne '') {
4689: $output = $domdesign{$domain.'.'.$which};
4690: } else {
4691: $output = $defaultdesign{$which};
4692: }
4693: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4694: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4695: if ($output =~ m{^/(adm|res)/}) {
4696: if ($output =~ m{^/res/}) {
4697: my $local_name = &Apache::lonnet::filelocation('',$output);
4698: &Apache::lonnet::repcopy($local_name);
4699: }
4700: $output = &lonhttpdurl($output);
4701: }
4702: }
4703: return $output;
4704: }
4705:
4706: ##############################################
4707: =pod
4708:
4709: =item * &authorspace()
4710:
4711: Inputs: $url (usually will be undef).
4712:
4713: Returns: Path to Construction Space containing the resource or
4714: directory being viewed (or for which action is being taken).
4715: If $url is provided, and begins /priv/<domain>/<uname>
4716: the path will be that portion of the $context argument.
4717: Otherwise the path will be for the author space of the current
4718: user when the current role is author, or for that of the
4719: co-author/assistant co-author space when the current role
4720: is co-author or assistant co-author.
4721:
4722: =cut
4723:
4724: sub authorspace {
4725: my ($url) = @_;
4726: if ($url ne '') {
4727: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4728: return $1;
4729: }
4730: }
4731: my $caname = '';
4732: my $cadom = '';
4733: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4734: ($cadom,$caname) =
4735: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4736: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4737: $caname = $env{'user.name'};
4738: $cadom = $env{'user.domain'};
4739: }
4740: if (($caname ne '') && ($cadom ne '')) {
4741: return "/priv/$cadom/$caname/";
4742: }
4743: return;
4744: }
4745:
4746: ##############################################
4747: =pod
4748:
4749: =item * &head_subbox()
4750:
4751: Inputs: $content (contains HTML code with page functions, etc.)
4752:
4753: Returns: HTML div with $content
4754: To be included in page header
4755:
4756: =cut
4757:
4758: sub head_subbox {
4759: my ($content)=@_;
4760: my $output =
4761: '<div class="LC_head_subbox">'
4762: .$content
4763: .'</div>'
4764: }
4765:
4766: ##############################################
4767: =pod
4768:
4769: =item * &CSTR_pageheader()
4770:
4771: Input: (optional) filename from which breadcrumb trail is built.
4772: In most cases no input as needed, as $env{'request.filename'}
4773: is appropriate for use in building the breadcrumb trail.
4774:
4775: Returns: HTML div with CSTR path and recent box
4776: To be included on Construction Space pages
4777:
4778: =cut
4779:
4780: sub CSTR_pageheader {
4781: my ($trailfile) = @_;
4782: if ($trailfile eq '') {
4783: $trailfile = $env{'request.filename'};
4784: }
4785:
4786: # this is for resources; directories have customtitle, and crumbs
4787: # and select recent are created in lonpubdir.pm
4788:
4789: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
4790: my ($udom,$uname,$thisdisfn)=
4791: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
4792: my $formaction = "/priv/$udom/$uname/$thisdisfn";
4793: $formaction =~ s{/+}{/}g;
4794:
4795: my $parentpath = '';
4796: my $lastitem = '';
4797: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4798: $parentpath = $1;
4799: $lastitem = $2;
4800: } else {
4801: $lastitem = $thisdisfn;
4802: }
4803:
4804: my $output =
4805: '<div>'
4806: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4807: .'<b>'.&mt('Construction Space:').'</b> '
4808: .'<form name="dirs" method="post" action="'.$formaction
4809: .'" target="_top">' #FIXME lonpubdir: target="_parent"
4810: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
4811:
4812: if ($lastitem) {
4813: $output .=
4814: '<span class="LC_filename">'
4815: .$lastitem
4816: .'</span>';
4817: }
4818: $output .=
4819: '<br />'
4820: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4821: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4822: .'</form>'
4823: .&Apache::lonmenu::constspaceform()
4824: .'</div>';
4825:
4826: return $output;
4827: }
4828:
4829: ###############################################
4830: ###############################################
4831:
4832: =pod
4833:
4834: =back
4835:
4836: =head1 HTML Helpers
4837:
4838: =over 4
4839:
4840: =item * &bodytag()
4841:
4842: Returns a uniform header for LON-CAPA web pages.
4843:
4844: Inputs:
4845:
4846: =over 4
4847:
4848: =item * $title, A title to be displayed on the page.
4849:
4850: =item * $function, the current role (can be undef).
4851:
4852: =item * $addentries, extra parameters for the <body> tag.
4853:
4854: =item * $bodyonly, if defined, only return the <body> tag.
4855:
4856: =item * $domain, if defined, force a given domain.
4857:
4858: =item * $forcereg, if page should register as content page (relevant for
4859: text interface only)
4860:
4861: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
4862: navigational links
4863:
4864: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4865:
4866: =item * $args, optional argument valid values are
4867: no_auto_mt_title -> prevents &mt()ing the title arg
4868: inherit_jsmath -> when creating popup window in a page,
4869: should it have jsmath forced on by the
4870: current page
4871:
4872: =back
4873:
4874: Returns: A uniform header for LON-CAPA web pages.
4875: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4876: If $bodyonly is undef or zero, an html string containing a <body> tag and
4877: other decorations will be returned.
4878:
4879: =cut
4880:
4881: sub bodytag {
4882: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
4883: $no_nav_bar,$bgcolor,$args)=@_;
4884:
4885: my $public;
4886: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
4887: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
4888: $public = 1;
4889: }
4890: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4891:
4892: $function = &get_users_function() if (!$function);
4893: my $img = &designparm($function.'.img',$domain);
4894: my $font = &designparm($function.'.font',$domain);
4895: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4896:
4897: my %design = ( 'style' => 'margin-top: 0',
4898: 'bgcolor' => $pgbg,
4899: 'text' => $font,
4900: 'alink' => &designparm($function.'.alink',$domain),
4901: 'vlink' => &designparm($function.'.vlink',$domain),
4902: 'link' => &designparm($function.'.link',$domain),);
4903: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4904:
4905: # role and realm
4906: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4907: if ($role eq 'ca') {
4908: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4909: $realm = &plainname($rname,$rdom);
4910: }
4911: # realm
4912: if ($env{'request.course.id'}) {
4913: if ($env{'request.role'} !~ /^cr/) {
4914: $role = &Apache::lonnet::plaintext($role,&course_type());
4915: }
4916: if ($env{'request.course.sec'}) {
4917: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
4918: }
4919: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4920: } else {
4921: $role = &Apache::lonnet::plaintext($role);
4922: }
4923:
4924: if (!$realm) { $realm=' '; }
4925:
4926: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4927:
4928: # construct main body tag
4929: my $bodytag = "<body $extra_body_attr>".
4930: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4931:
4932: if ($bodyonly) {
4933: return $bodytag;
4934: }
4935:
4936: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4937: if ($public) {
4938: undef($role);
4939: } else {
4940: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4941: }
4942:
4943: my $titleinfo = '<h1>'.$title.'</h1>';
4944: #
4945: # Extra info if you are the DC
4946: my $dc_info = '';
4947: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4948: $env{'course.'.$env{'request.course.id'}.
4949: '.domain'}.'/'})) {
4950: my $cid = $env{'request.course.id'};
4951: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4952: $dc_info =~ s/\s+$//;
4953: }
4954:
4955: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
4956: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
4957:
4958: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') {
4959: return $bodytag;
4960: }
4961:
4962: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
4963:
4964: # if ($env{'request.state'} eq 'construct') {
4965: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
4966: # }
4967:
4968:
4969:
4970: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
4971: if ($dc_info) {
4972: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
4973: }
4974: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
4975: <em>$realm</em> $dc_info</div>|;
4976: return $bodytag;
4977: }
4978:
4979: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
4980: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
4981: }
4982:
4983: $bodytag .= Apache::lonhtmlcommon::scripttag(
4984: Apache::lonmenu::utilityfunctions(), 'start');
4985:
4986: $bodytag .= Apache::lonmenu::primary_menu();
4987:
4988: if ($dc_info) {
4989: $dc_info = &dc_courseid_toggle($dc_info);
4990: }
4991: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
4992:
4993: #don't show menus for public users
4994: if (!$public){
4995: $bodytag .= Apache::lonmenu::secondary_menu();
4996: $bodytag .= Apache::lonmenu::serverform();
4997: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4998: if ($env{'request.state'} eq 'construct') {
4999: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5000: $args->{'bread_crumbs'});
5001: } elsif ($forcereg) {
5002: $bodytag .= &Apache::lonmenu::innerregister($forcereg);
5003: }
5004: }else{
5005: # this is to seperate menu from content when there's no secondary
5006: # menu. Especially needed for public accessible ressources.
5007: $bodytag .= '<hr style="clear:both" />';
5008: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5009: }
5010:
5011: return $bodytag;
5012: }
5013:
5014: sub dc_courseid_toggle {
5015: my ($dc_info) = @_;
5016: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5017: '<a href="javascript:showCourseID();">'.
5018: &mt('(More ...)').'</a></span>'.
5019: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5020: }
5021:
5022: sub make_attr_string {
5023: my ($register,$attr_ref) = @_;
5024:
5025: if ($attr_ref && !ref($attr_ref)) {
5026: die("addentries Must be a hash ref ".
5027: join(':',caller(1))." ".
5028: join(':',caller(0))." ");
5029: }
5030:
5031: if ($register) {
5032: my ($on_load,$on_unload);
5033: foreach my $key (keys(%{$attr_ref})) {
5034: if (lc($key) eq 'onload') {
5035: $on_load.=$attr_ref->{$key}.';';
5036: delete($attr_ref->{$key});
5037:
5038: } elsif (lc($key) eq 'onunload') {
5039: $on_unload.=$attr_ref->{$key}.';';
5040: delete($attr_ref->{$key});
5041: }
5042: }
5043: $attr_ref->{'onload'} = $on_load;
5044: $attr_ref->{'onunload'}= $on_unload;
5045: }
5046:
5047: my $attr_string;
5048: foreach my $attr (keys(%$attr_ref)) {
5049: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5050: }
5051: return $attr_string;
5052: }
5053:
5054:
5055: ###############################################
5056: ###############################################
5057:
5058: =pod
5059:
5060: =item * &endbodytag()
5061:
5062: Returns a uniform footer for LON-CAPA web pages.
5063:
5064: Inputs: 1 - optional reference to an args hash
5065: If in the hash, key for noredirectlink has a value which evaluates to true,
5066: a 'Continue' link is not displayed if the page contains an
5067: internal redirect in the <head></head> section,
5068: i.e., $env{'internal.head.redirect'} exists
5069:
5070: =cut
5071:
5072: sub endbodytag {
5073: my ($args) = @_;
5074: my $endbodytag='</body>';
5075: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5076: if ( exists( $env{'internal.head.redirect'} ) ) {
5077: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5078: $endbodytag=
5079: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5080: &mt('Continue').'</a>'.
5081: $endbodytag;
5082: }
5083: }
5084: return $endbodytag;
5085: }
5086:
5087: =pod
5088:
5089: =item * &standard_css()
5090:
5091: Returns a style sheet
5092:
5093: Inputs: (all optional)
5094: domain -> force to color decorate a page for a specific
5095: domain
5096: function -> force usage of a specific rolish color scheme
5097: bgcolor -> override the default page bgcolor
5098:
5099: =cut
5100:
5101: sub standard_css {
5102: my ($function,$domain,$bgcolor) = @_;
5103: $function = &get_users_function() if (!$function);
5104: my $img = &designparm($function.'.img', $domain);
5105: my $tabbg = &designparm($function.'.tabbg', $domain);
5106: my $font = &designparm($function.'.font', $domain);
5107: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5108: #second colour for later usage
5109: my $sidebg = &designparm($function.'.sidebg',$domain);
5110: my $pgbg_or_bgcolor =
5111: $bgcolor ||
5112: &designparm($function.'.pgbg', $domain);
5113: my $pgbg = &designparm($function.'.pgbg', $domain);
5114: my $alink = &designparm($function.'.alink', $domain);
5115: my $vlink = &designparm($function.'.vlink', $domain);
5116: my $link = &designparm($function.'.link', $domain);
5117:
5118: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5119: my $mono = 'monospace';
5120: my $data_table_head = $sidebg;
5121: my $data_table_light = '#FAFAFA';
5122: my $data_table_dark = '#E0E0E0';
5123: my $data_table_darker = '#CCCCCC';
5124: my $data_table_highlight = '#FFFF00';
5125: my $mail_new = '#FFBB77';
5126: my $mail_new_hover = '#DD9955';
5127: my $mail_read = '#BBBB77';
5128: my $mail_read_hover = '#999944';
5129: my $mail_replied = '#AAAA88';
5130: my $mail_replied_hover = '#888855';
5131: my $mail_other = '#99BBBB';
5132: my $mail_other_hover = '#669999';
5133: my $table_header = '#DDDDDD';
5134: my $feedback_link_bg = '#BBBBBB';
5135: my $lg_border_color = '#C8C8C8';
5136: my $button_hover = '#BF2317';
5137:
5138: my $border = ($env{'browser.type'} eq 'explorer' ||
5139: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5140: : '0 3px 0 4px';
5141:
5142:
5143: return <<END;
5144:
5145: /* needed for iframe to allow 100% height in FF */
5146: body, html {
5147: margin: 0;
5148: padding: 0 0.5%;
5149: height: 99%; /* to avoid scrollbars */
5150: }
5151:
5152: body {
5153: font-family: $sans;
5154: line-height:130%;
5155: font-size:0.83em;
5156: color:$font;
5157: }
5158:
5159: a:focus,
5160: a:focus img {
5161: color: red;
5162: }
5163:
5164: form, .inline {
5165: display: inline;
5166: }
5167:
5168: .LC_right {
5169: text-align:right;
5170: }
5171:
5172: .LC_middle {
5173: vertical-align:middle;
5174: }
5175:
5176: .LC_400Box {
5177: width:400px;
5178: }
5179:
5180: .LC_iframecontainer {
5181: width: 98%;
5182: margin: 0;
5183: position: fixed;
5184: top: 8.5em;
5185: bottom: 0;
5186: }
5187:
5188: .LC_iframecontainer iframe{
5189: border: none;
5190: width: 100%;
5191: height: 100%;
5192: }
5193:
5194: .LC_filename {
5195: font-family: $mono;
5196: white-space:pre;
5197: font-size: 120%;
5198: }
5199:
5200: .LC_fileicon {
5201: border: none;
5202: height: 1.3em;
5203: vertical-align: text-bottom;
5204: margin-right: 0.3em;
5205: text-decoration:none;
5206: }
5207:
5208: .LC_setting {
5209: text-decoration:underline;
5210: }
5211:
5212: .LC_error {
5213: color: red;
5214: font-size: larger;
5215: }
5216:
5217: .LC_warning,
5218: .LC_diff_removed {
5219: color: red;
5220: }
5221:
5222: .LC_info,
5223: .LC_success,
5224: .LC_diff_added {
5225: color: green;
5226: }
5227:
5228: div.LC_confirm_box {
5229: background-color: #FAFAFA;
5230: border: 1px solid $lg_border_color;
5231: margin-right: 0;
5232: padding: 5px;
5233: }
5234:
5235: div.LC_confirm_box .LC_error img,
5236: div.LC_confirm_box .LC_success img {
5237: vertical-align: middle;
5238: }
5239:
5240: .LC_icon {
5241: border: none;
5242: vertical-align: middle;
5243: }
5244:
5245: .LC_docs_spacer {
5246: width: 25px;
5247: height: 1px;
5248: border: none;
5249: }
5250:
5251: .LC_internal_info {
5252: color: #999999;
5253: }
5254:
5255: .LC_discussion {
5256: background: $data_table_dark;
5257: border: 1px solid black;
5258: margin: 2px;
5259: }
5260:
5261: .LC_disc_action_left {
5262: background: $sidebg;
5263: text-align: left;
5264: padding: 4px;
5265: margin: 2px;
5266: }
5267:
5268: .LC_disc_action_right {
5269: background: $sidebg;
5270: text-align: right;
5271: padding: 4px;
5272: margin: 2px;
5273: }
5274:
5275: .LC_disc_new_item {
5276: background: white;
5277: border: 2px solid red;
5278: margin: 4px;
5279: padding: 4px;
5280: }
5281:
5282: .LC_disc_old_item {
5283: background: white;
5284: margin: 4px;
5285: padding: 4px;
5286: }
5287:
5288: table.LC_pastsubmission {
5289: border: 1px solid black;
5290: margin: 2px;
5291: }
5292:
5293: table#LC_menubuttons {
5294: width: 100%;
5295: background: $pgbg;
5296: border: 2px;
5297: border-collapse: separate;
5298: padding: 0;
5299: }
5300:
5301: table#LC_title_bar a {
5302: color: $fontmenu;
5303: }
5304:
5305: table#LC_title_bar {
5306: clear: both;
5307: display: none;
5308: }
5309:
5310: table#LC_title_bar,
5311: table.LC_breadcrumbs, /* obsolete? */
5312: table#LC_title_bar.LC_with_remote {
5313: width: 100%;
5314: border-color: $pgbg;
5315: border-style: solid;
5316: border-width: $border;
5317: background: $pgbg;
5318: color: $fontmenu;
5319: border-collapse: collapse;
5320: padding: 0;
5321: margin: 0;
5322: }
5323:
5324: ul.LC_breadcrumb_tools_outerlist {
5325: margin: 0;
5326: padding: 0;
5327: position: relative;
5328: list-style: none;
5329: }
5330: ul.LC_breadcrumb_tools_outerlist li {
5331: display: inline;
5332: }
5333:
5334: .LC_breadcrumb_tools_navigation {
5335: padding: 0;
5336: margin: 0;
5337: float: left;
5338: }
5339: .LC_breadcrumb_tools_tools {
5340: padding: 0;
5341: margin: 0;
5342: float: right;
5343: }
5344:
5345: table#LC_title_bar td {
5346: background: $tabbg;
5347: }
5348:
5349: table#LC_menubuttons img {
5350: border: none;
5351: }
5352:
5353: .LC_breadcrumbs_component {
5354: float: right;
5355: margin: 0 1em;
5356: }
5357: .LC_breadcrumbs_component img {
5358: vertical-align: middle;
5359: }
5360:
5361: td.LC_table_cell_checkbox {
5362: text-align: center;
5363: }
5364:
5365: .LC_fontsize_small {
5366: font-size: 70%;
5367: }
5368:
5369: #LC_breadcrumbs {
5370: clear:both;
5371: background: $sidebg;
5372: border-bottom: 1px solid $lg_border_color;
5373: line-height: 2.5em;
5374: overflow: hidden;
5375: margin: 0;
5376: padding: 0;
5377: text-align: left;
5378: }
5379:
5380: .LC_head_subbox {
5381: clear:both;
5382: background: #F8F8F8; /* $sidebg; */
5383: border: 1px solid $sidebg;
5384: margin: 0 0 10px 0;
5385: padding: 3px;
5386: text-align: left;
5387: }
5388:
5389: .LC_fontsize_medium {
5390: font-size: 85%;
5391: }
5392:
5393: .LC_fontsize_large {
5394: font-size: 120%;
5395: }
5396:
5397: .LC_menubuttons_inline_text {
5398: color: $font;
5399: font-size: 90%;
5400: padding-left:3px;
5401: }
5402:
5403: .LC_menubuttons_inline_text img{
5404: vertical-align: middle;
5405: }
5406:
5407: li.LC_menubuttons_inline_text img {
5408: cursor:pointer;
5409: text-decoration: none;
5410: }
5411:
5412: .LC_menubuttons_link {
5413: text-decoration: none;
5414: }
5415:
5416: .LC_menubuttons_category {
5417: color: $font;
5418: background: $pgbg;
5419: font-size: larger;
5420: font-weight: bold;
5421: }
5422:
5423: td.LC_menubuttons_text {
5424: color: $font;
5425: }
5426:
5427: .LC_current_location {
5428: background: $tabbg;
5429: }
5430:
5431: table.LC_data_table {
5432: border: 1px solid #000000;
5433: border-collapse: separate;
5434: border-spacing: 1px;
5435: background: $pgbg;
5436: }
5437:
5438: .LC_data_table_dense {
5439: font-size: small;
5440: }
5441:
5442: table.LC_nested_outer {
5443: border: 1px solid #000000;
5444: border-collapse: collapse;
5445: border-spacing: 0;
5446: width: 100%;
5447: }
5448:
5449: table.LC_innerpickbox,
5450: table.LC_nested {
5451: border: none;
5452: border-collapse: collapse;
5453: border-spacing: 0;
5454: width: 100%;
5455: }
5456:
5457: table.LC_data_table tr th,
5458: table.LC_calendar tr th,
5459: table.LC_prior_tries tr th,
5460: table.LC_innerpickbox tr th {
5461: font-weight: bold;
5462: background-color: $data_table_head;
5463: color:$fontmenu;
5464: font-size:90%;
5465: }
5466:
5467: table.LC_innerpickbox tr th,
5468: table.LC_innerpickbox tr td {
5469: vertical-align: top;
5470: }
5471:
5472: table.LC_data_table tr.LC_info_row > td {
5473: background-color: #CCCCCC;
5474: font-weight: bold;
5475: text-align: left;
5476: }
5477:
5478: table.LC_data_table tr.LC_odd_row > td {
5479: background-color: $data_table_light;
5480: padding: 2px;
5481: vertical-align: top;
5482: }
5483:
5484: table.LC_pick_box tr > td.LC_odd_row {
5485: background-color: $data_table_light;
5486: vertical-align: top;
5487: }
5488:
5489: table.LC_data_table tr.LC_even_row > td {
5490: background-color: $data_table_dark;
5491: padding: 2px;
5492: vertical-align: top;
5493: }
5494:
5495: table.LC_pick_box tr > td.LC_even_row {
5496: background-color: $data_table_dark;
5497: vertical-align: top;
5498: }
5499:
5500: table.LC_data_table tr.LC_data_table_highlight td {
5501: background-color: $data_table_darker;
5502: }
5503:
5504: table.LC_data_table tr td.LC_leftcol_header {
5505: background-color: $data_table_head;
5506: font-weight: bold;
5507: }
5508:
5509: table.LC_data_table tr.LC_empty_row td,
5510: table.LC_nested tr.LC_empty_row td {
5511: font-weight: bold;
5512: font-style: italic;
5513: text-align: center;
5514: padding: 8px;
5515: }
5516:
5517: table.LC_data_table tr.LC_empty_row td {
5518: background-color: $sidebg;
5519: }
5520:
5521: table.LC_nested tr.LC_empty_row td {
5522: background-color: #FFFFFF;
5523: }
5524:
5525: table.LC_caption {
5526: }
5527:
5528: table.LC_nested tr.LC_empty_row td {
5529: padding: 4ex
5530: }
5531:
5532: table.LC_nested_outer tr th {
5533: font-weight: bold;
5534: color:$fontmenu;
5535: background-color: $data_table_head;
5536: font-size: small;
5537: border-bottom: 1px solid #000000;
5538: }
5539:
5540: table.LC_nested_outer tr td.LC_subheader {
5541: background-color: $data_table_head;
5542: font-weight: bold;
5543: font-size: small;
5544: border-bottom: 1px solid #000000;
5545: text-align: right;
5546: }
5547:
5548: table.LC_nested tr.LC_info_row td {
5549: background-color: #CCCCCC;
5550: font-weight: bold;
5551: font-size: small;
5552: text-align: center;
5553: }
5554:
5555: table.LC_nested tr.LC_info_row td.LC_left_item,
5556: table.LC_nested_outer tr th.LC_left_item {
5557: text-align: left;
5558: }
5559:
5560: table.LC_nested td {
5561: background-color: #FFFFFF;
5562: font-size: small;
5563: }
5564:
5565: table.LC_nested_outer tr th.LC_right_item,
5566: table.LC_nested tr.LC_info_row td.LC_right_item,
5567: table.LC_nested tr.LC_odd_row td.LC_right_item,
5568: table.LC_nested tr td.LC_right_item {
5569: text-align: right;
5570: }
5571:
5572: table.LC_nested tr.LC_odd_row td {
5573: background-color: #EEEEEE;
5574: }
5575:
5576: table.LC_createuser {
5577: }
5578:
5579: table.LC_createuser tr.LC_section_row td {
5580: font-size: small;
5581: }
5582:
5583: table.LC_createuser tr.LC_info_row td {
5584: background-color: #CCCCCC;
5585: font-weight: bold;
5586: text-align: center;
5587: }
5588:
5589: table.LC_calendar {
5590: border: 1px solid #000000;
5591: border-collapse: collapse;
5592: width: 98%;
5593: }
5594:
5595: table.LC_calendar_pickdate {
5596: font-size: xx-small;
5597: }
5598:
5599: table.LC_calendar tr td {
5600: border: 1px solid #000000;
5601: vertical-align: top;
5602: width: 14%;
5603: }
5604:
5605: table.LC_calendar tr td.LC_calendar_day_empty {
5606: background-color: $data_table_dark;
5607: }
5608:
5609: table.LC_calendar tr td.LC_calendar_day_current {
5610: background-color: $data_table_highlight;
5611: }
5612:
5613: table.LC_data_table tr td.LC_mail_new {
5614: background-color: $mail_new;
5615: }
5616:
5617: table.LC_data_table tr.LC_mail_new:hover {
5618: background-color: $mail_new_hover;
5619: }
5620:
5621: table.LC_data_table tr td.LC_mail_read {
5622: background-color: $mail_read;
5623: }
5624:
5625: /*
5626: table.LC_data_table tr.LC_mail_read:hover {
5627: background-color: $mail_read_hover;
5628: }
5629: */
5630:
5631: table.LC_data_table tr td.LC_mail_replied {
5632: background-color: $mail_replied;
5633: }
5634:
5635: /*
5636: table.LC_data_table tr.LC_mail_replied:hover {
5637: background-color: $mail_replied_hover;
5638: }
5639: */
5640:
5641: table.LC_data_table tr td.LC_mail_other {
5642: background-color: $mail_other;
5643: }
5644:
5645: /*
5646: table.LC_data_table tr.LC_mail_other:hover {
5647: background-color: $mail_other_hover;
5648: }
5649: */
5650:
5651: table.LC_data_table tr > td.LC_browser_file,
5652: table.LC_data_table tr > td.LC_browser_file_published {
5653: background: #AAEE77;
5654: }
5655:
5656: table.LC_data_table tr > td.LC_browser_file_locked,
5657: table.LC_data_table tr > td.LC_browser_file_unpublished {
5658: background: #FFAA99;
5659: }
5660:
5661: table.LC_data_table tr > td.LC_browser_file_obsolete {
5662: background: #888888;
5663: }
5664:
5665: table.LC_data_table tr > td.LC_browser_file_modified,
5666: table.LC_data_table tr > td.LC_browser_file_metamodified {
5667: background: #F8F866;
5668: }
5669:
5670: table.LC_data_table tr.LC_browser_folder > td {
5671: background: #E0E8FF;
5672: }
5673:
5674: table.LC_data_table tr > td.LC_roles_is {
5675: /* background: #77FF77; */
5676: }
5677:
5678: table.LC_data_table tr > td.LC_roles_future {
5679: border-right: 8px solid #FFFF77;
5680: }
5681:
5682: table.LC_data_table tr > td.LC_roles_will {
5683: border-right: 8px solid #FFAA77;
5684: }
5685:
5686: table.LC_data_table tr > td.LC_roles_expired {
5687: border-right: 8px solid #FF7777;
5688: }
5689:
5690: table.LC_data_table tr > td.LC_roles_will_not {
5691: border-right: 8px solid #AAFF77;
5692: }
5693:
5694: table.LC_data_table tr > td.LC_roles_selected {
5695: border-right: 8px solid #11CC55;
5696: }
5697:
5698: span.LC_current_location {
5699: font-size:larger;
5700: background: $pgbg;
5701: }
5702:
5703: span.LC_current_nav_location {
5704: font-weight:bold;
5705: background: $sidebg;
5706: }
5707:
5708: span.LC_parm_menu_item {
5709: font-size: larger;
5710: }
5711:
5712: span.LC_parm_scope_all {
5713: color: red;
5714: }
5715:
5716: span.LC_parm_scope_folder {
5717: color: green;
5718: }
5719:
5720: span.LC_parm_scope_resource {
5721: color: orange;
5722: }
5723:
5724: span.LC_parm_part {
5725: color: blue;
5726: }
5727:
5728: span.LC_parm_folder,
5729: span.LC_parm_symb {
5730: font-size: x-small;
5731: font-family: $mono;
5732: color: #AAAAAA;
5733: }
5734:
5735: ul.LC_parm_parmlist li {
5736: display: inline-block;
5737: padding: 0.3em 0.8em;
5738: vertical-align: top;
5739: width: 150px;
5740: border-top:1px solid $lg_border_color;
5741: }
5742:
5743: td.LC_parm_overview_level_menu,
5744: td.LC_parm_overview_map_menu,
5745: td.LC_parm_overview_parm_selectors,
5746: td.LC_parm_overview_restrictions {
5747: border: 1px solid black;
5748: border-collapse: collapse;
5749: }
5750:
5751: table.LC_parm_overview_restrictions td {
5752: border-width: 1px 4px 1px 4px;
5753: border-style: solid;
5754: border-color: $pgbg;
5755: text-align: center;
5756: }
5757:
5758: table.LC_parm_overview_restrictions th {
5759: background: $tabbg;
5760: border-width: 1px 4px 1px 4px;
5761: border-style: solid;
5762: border-color: $pgbg;
5763: }
5764:
5765: table#LC_helpmenu {
5766: border: none;
5767: height: 55px;
5768: border-spacing: 0;
5769: }
5770:
5771: table#LC_helpmenu fieldset legend {
5772: font-size: larger;
5773: }
5774:
5775: table#LC_helpmenu_links {
5776: width: 100%;
5777: border: 1px solid black;
5778: background: $pgbg;
5779: padding: 0;
5780: border-spacing: 1px;
5781: }
5782:
5783: table#LC_helpmenu_links tr td {
5784: padding: 1px;
5785: background: $tabbg;
5786: text-align: center;
5787: font-weight: bold;
5788: }
5789:
5790: table#LC_helpmenu_links a:link,
5791: table#LC_helpmenu_links a:visited,
5792: table#LC_helpmenu_links a:active {
5793: text-decoration: none;
5794: color: $font;
5795: }
5796:
5797: table#LC_helpmenu_links a:hover {
5798: text-decoration: underline;
5799: color: $vlink;
5800: }
5801:
5802: .LC_chrt_popup_exists {
5803: border: 1px solid #339933;
5804: margin: -1px;
5805: }
5806:
5807: .LC_chrt_popup_up {
5808: border: 1px solid yellow;
5809: margin: -1px;
5810: }
5811:
5812: .LC_chrt_popup {
5813: border: 1px solid #8888FF;
5814: background: #CCCCFF;
5815: }
5816:
5817: table.LC_pick_box {
5818: border-collapse: separate;
5819: background: white;
5820: border: 1px solid black;
5821: border-spacing: 1px;
5822: }
5823:
5824: table.LC_pick_box td.LC_pick_box_title {
5825: background: $sidebg;
5826: font-weight: bold;
5827: text-align: left;
5828: vertical-align: top;
5829: width: 184px;
5830: padding: 8px;
5831: }
5832:
5833: table.LC_pick_box td.LC_pick_box_value {
5834: text-align: left;
5835: padding: 8px;
5836: }
5837:
5838: table.LC_pick_box td.LC_pick_box_select {
5839: text-align: left;
5840: padding: 8px;
5841: }
5842:
5843: table.LC_pick_box td.LC_pick_box_separator {
5844: padding: 0;
5845: height: 1px;
5846: background: black;
5847: }
5848:
5849: table.LC_pick_box td.LC_pick_box_submit {
5850: text-align: right;
5851: }
5852:
5853: table.LC_pick_box td.LC_evenrow_value {
5854: text-align: left;
5855: padding: 8px;
5856: background-color: $data_table_light;
5857: }
5858:
5859: table.LC_pick_box td.LC_oddrow_value {
5860: text-align: left;
5861: padding: 8px;
5862: background-color: $data_table_light;
5863: }
5864:
5865: span.LC_helpform_receipt_cat {
5866: font-weight: bold;
5867: }
5868:
5869: table.LC_group_priv_box {
5870: background: white;
5871: border: 1px solid black;
5872: border-spacing: 1px;
5873: }
5874:
5875: table.LC_group_priv_box td.LC_pick_box_title {
5876: background: $tabbg;
5877: font-weight: bold;
5878: text-align: right;
5879: width: 184px;
5880: }
5881:
5882: table.LC_group_priv_box td.LC_groups_fixed {
5883: background: $data_table_light;
5884: text-align: center;
5885: }
5886:
5887: table.LC_group_priv_box td.LC_groups_optional {
5888: background: $data_table_dark;
5889: text-align: center;
5890: }
5891:
5892: table.LC_group_priv_box td.LC_groups_functionality {
5893: background: $data_table_darker;
5894: text-align: center;
5895: font-weight: bold;
5896: }
5897:
5898: table.LC_group_priv td {
5899: text-align: left;
5900: padding: 0;
5901: }
5902:
5903: .LC_navbuttons {
5904: margin: 2ex 0ex 2ex 0ex;
5905: }
5906:
5907: .LC_topic_bar {
5908: font-weight: bold;
5909: background: $tabbg;
5910: margin: 1em 0em 1em 2em;
5911: padding: 3px;
5912: font-size: 1.2em;
5913: }
5914:
5915: .LC_topic_bar span {
5916: left: 0.5em;
5917: position: absolute;
5918: vertical-align: middle;
5919: font-size: 1.2em;
5920: }
5921:
5922: table.LC_course_group_status {
5923: margin: 20px;
5924: }
5925:
5926: table.LC_status_selector td {
5927: vertical-align: top;
5928: text-align: center;
5929: padding: 4px;
5930: }
5931:
5932: div.LC_feedback_link {
5933: clear: both;
5934: background: $sidebg;
5935: width: 100%;
5936: padding-bottom: 10px;
5937: border: 1px $tabbg solid;
5938: height: 22px;
5939: line-height: 22px;
5940: padding-top: 5px;
5941: }
5942:
5943: div.LC_feedback_link img {
5944: height: 22px;
5945: vertical-align:middle;
5946: }
5947:
5948: div.LC_feedback_link a {
5949: text-decoration: none;
5950: }
5951:
5952: div.LC_comblock {
5953: display:inline;
5954: color:$font;
5955: font-size:90%;
5956: }
5957:
5958: div.LC_feedback_link div.LC_comblock {
5959: padding-left:5px;
5960: }
5961:
5962: div.LC_feedback_link div.LC_comblock a {
5963: color:$font;
5964: }
5965:
5966: span.LC_feedback_link {
5967: /* background: $feedback_link_bg; */
5968: font-size: larger;
5969: }
5970:
5971: span.LC_message_link {
5972: /* background: $feedback_link_bg; */
5973: font-size: larger;
5974: position: absolute;
5975: right: 1em;
5976: }
5977:
5978: table.LC_prior_tries {
5979: border: 1px solid #000000;
5980: border-collapse: separate;
5981: border-spacing: 1px;
5982: }
5983:
5984: table.LC_prior_tries td {
5985: padding: 2px;
5986: }
5987:
5988: .LC_answer_correct {
5989: background: lightgreen;
5990: color: darkgreen;
5991: padding: 6px;
5992: }
5993:
5994: .LC_answer_charged_try {
5995: background: #FFAAAA;
5996: color: darkred;
5997: padding: 6px;
5998: }
5999:
6000: .LC_answer_not_charged_try,
6001: .LC_answer_no_grade,
6002: .LC_answer_late {
6003: background: lightyellow;
6004: color: black;
6005: padding: 6px;
6006: }
6007:
6008: .LC_answer_previous {
6009: background: lightblue;
6010: color: darkblue;
6011: padding: 6px;
6012: }
6013:
6014: .LC_answer_no_message {
6015: background: #FFFFFF;
6016: color: black;
6017: padding: 6px;
6018: }
6019:
6020: .LC_answer_unknown {
6021: background: orange;
6022: color: black;
6023: padding: 6px;
6024: }
6025:
6026: span.LC_prior_numerical,
6027: span.LC_prior_string,
6028: span.LC_prior_custom,
6029: span.LC_prior_reaction,
6030: span.LC_prior_math {
6031: font-family: $mono;
6032: white-space: pre;
6033: }
6034:
6035: span.LC_prior_string {
6036: font-family: $mono;
6037: white-space: pre;
6038: }
6039:
6040: table.LC_prior_option {
6041: width: 100%;
6042: border-collapse: collapse;
6043: }
6044:
6045: table.LC_prior_rank,
6046: table.LC_prior_match {
6047: border-collapse: collapse;
6048: }
6049:
6050: table.LC_prior_option tr td,
6051: table.LC_prior_rank tr td,
6052: table.LC_prior_match tr td {
6053: border: 1px solid #000000;
6054: }
6055:
6056: .LC_nobreak {
6057: white-space: nowrap;
6058: }
6059:
6060: span.LC_cusr_emph {
6061: font-style: italic;
6062: }
6063:
6064: span.LC_cusr_subheading {
6065: font-weight: normal;
6066: font-size: 85%;
6067: }
6068:
6069: div.LC_docs_entry_move {
6070: border: 1px solid #BBBBBB;
6071: background: #DDDDDD;
6072: width: 22px;
6073: padding: 1px;
6074: margin: 0;
6075: }
6076:
6077: table.LC_data_table tr > td.LC_docs_entry_commands,
6078: table.LC_data_table tr > td.LC_docs_entry_parameter {
6079: background: #DDDDDD;
6080: font-size: x-small;
6081: }
6082:
6083: .LC_docs_entry_parameter {
6084: white-space: nowrap;
6085: }
6086:
6087: .LC_docs_copy {
6088: color: #000099;
6089: }
6090:
6091: .LC_docs_cut {
6092: color: #550044;
6093: }
6094:
6095: .LC_docs_rename {
6096: color: #009900;
6097: }
6098:
6099: .LC_docs_remove {
6100: color: #990000;
6101: }
6102:
6103: .LC_docs_reinit_warn,
6104: .LC_docs_ext_edit {
6105: font-size: x-small;
6106: }
6107:
6108: table.LC_docs_adddocs td,
6109: table.LC_docs_adddocs th {
6110: border: 1px solid #BBBBBB;
6111: padding: 4px;
6112: background: #DDDDDD;
6113: }
6114:
6115: table.LC_sty_begin {
6116: background: #BBFFBB;
6117: }
6118:
6119: table.LC_sty_end {
6120: background: #FFBBBB;
6121: }
6122:
6123: table.LC_double_column {
6124: border-width: 0;
6125: border-collapse: collapse;
6126: width: 100%;
6127: padding: 2px;
6128: }
6129:
6130: table.LC_double_column tr td.LC_left_col {
6131: top: 2px;
6132: left: 2px;
6133: width: 47%;
6134: vertical-align: top;
6135: }
6136:
6137: table.LC_double_column tr td.LC_right_col {
6138: top: 2px;
6139: right: 2px;
6140: width: 47%;
6141: vertical-align: top;
6142: }
6143:
6144: div.LC_left_float {
6145: float: left;
6146: padding-right: 5%;
6147: padding-bottom: 4px;
6148: }
6149:
6150: div.LC_clear_float_header {
6151: padding-bottom: 2px;
6152: }
6153:
6154: div.LC_clear_float_footer {
6155: padding-top: 10px;
6156: clear: both;
6157: }
6158:
6159: div.LC_grade_show_user {
6160: /* border-left: 5px solid $sidebg; */
6161: border-top: 5px solid #000000;
6162: margin: 50px 0 0 0;
6163: padding: 15px 0 5px 10px;
6164: }
6165:
6166: div.LC_grade_show_user_odd_row {
6167: /* border-left: 5px solid #000000; */
6168: }
6169:
6170: div.LC_grade_show_user div.LC_Box {
6171: margin-right: 50px;
6172: }
6173:
6174: div.LC_grade_submissions,
6175: div.LC_grade_message_center,
6176: div.LC_grade_info_links {
6177: margin: 5px;
6178: width: 99%;
6179: background: #FFFFFF;
6180: }
6181:
6182: div.LC_grade_submissions_header,
6183: div.LC_grade_message_center_header {
6184: font-weight: bold;
6185: font-size: large;
6186: }
6187:
6188: div.LC_grade_submissions_body,
6189: div.LC_grade_message_center_body {
6190: border: 1px solid black;
6191: width: 99%;
6192: background: #FFFFFF;
6193: }
6194:
6195: table.LC_scantron_action {
6196: width: 100%;
6197: }
6198:
6199: table.LC_scantron_action tr th {
6200: font-weight:bold;
6201: font-style:normal;
6202: }
6203:
6204: .LC_edit_problem_header,
6205: div.LC_edit_problem_footer {
6206: font-weight: normal;
6207: font-size: medium;
6208: margin: 2px;
6209: background-color: $sidebg;
6210: }
6211:
6212: div.LC_edit_problem_header,
6213: div.LC_edit_problem_header div,
6214: div.LC_edit_problem_footer,
6215: div.LC_edit_problem_footer div,
6216: div.LC_edit_problem_editxml_header,
6217: div.LC_edit_problem_editxml_header div {
6218: margin-top: 5px;
6219: }
6220:
6221: div.LC_edit_problem_header_title {
6222: font-weight: bold;
6223: font-size: larger;
6224: background: $tabbg;
6225: padding: 3px;
6226: margin: 0 0 5px 0;
6227: }
6228:
6229: table.LC_edit_problem_header_title {
6230: width: 100%;
6231: background: $tabbg;
6232: }
6233:
6234: div.LC_edit_problem_discards {
6235: float: left;
6236: padding-bottom: 5px;
6237: }
6238:
6239: div.LC_edit_problem_saves {
6240: float: right;
6241: padding-bottom: 5px;
6242: }
6243:
6244: img.stift {
6245: border-width: 0;
6246: vertical-align: middle;
6247: }
6248:
6249: table td.LC_mainmenu_col_fieldset {
6250: vertical-align: top;
6251: }
6252:
6253: div.LC_createcourse {
6254: margin: 10px 10px 10px 10px;
6255: }
6256:
6257: .LC_dccid {
6258: margin: 0.2em 0 0 0;
6259: padding: 0;
6260: font-size: 90%;
6261: display:none;
6262: }
6263:
6264: ol.LC_primary_menu a:hover,
6265: ol#LC_MenuBreadcrumbs a:hover,
6266: ol#LC_PathBreadcrumbs a:hover,
6267: ul#LC_secondary_menu a:hover,
6268: .LC_FormSectionClearButton input:hover
6269: ul.LC_TabContent li:hover a {
6270: color:$button_hover;
6271: text-decoration:none;
6272: }
6273:
6274: h1 {
6275: padding: 0;
6276: line-height:130%;
6277: }
6278:
6279: h2,
6280: h3,
6281: h4,
6282: h5,
6283: h6 {
6284: margin: 5px 0 5px 0;
6285: padding: 0;
6286: line-height:130%;
6287: }
6288:
6289: .LC_hcell {
6290: padding:3px 15px 3px 15px;
6291: margin: 0;
6292: background-color:$tabbg;
6293: color:$fontmenu;
6294: border-bottom:solid 1px $lg_border_color;
6295: }
6296:
6297: .LC_Box > .LC_hcell {
6298: margin: 0 -10px 10px -10px;
6299: }
6300:
6301: .LC_noBorder {
6302: border: 0;
6303: }
6304:
6305: .LC_FormSectionClearButton input {
6306: background-color:transparent;
6307: border: none;
6308: cursor:pointer;
6309: text-decoration:underline;
6310: }
6311:
6312: .LC_help_open_topic {
6313: color: #FFFFFF;
6314: background-color: #EEEEFF;
6315: margin: 1px;
6316: padding: 4px;
6317: border: 1px solid #000033;
6318: white-space: nowrap;
6319: /* vertical-align: middle; */
6320: }
6321:
6322: dl,
6323: ul,
6324: div,
6325: fieldset {
6326: margin: 10px 10px 10px 0;
6327: /* overflow: hidden; */
6328: }
6329:
6330: fieldset > legend {
6331: font-weight: bold;
6332: padding: 0 5px 0 5px;
6333: }
6334:
6335: #LC_nav_bar {
6336: float: left;
6337: background-color: $pgbg_or_bgcolor;
6338: margin: 0 0 2px 0;
6339: }
6340:
6341: #LC_realm {
6342: margin: 0.2em 0 0 0;
6343: padding: 0;
6344: font-weight: bold;
6345: text-align: center;
6346: background-color: $pgbg_or_bgcolor;
6347: }
6348:
6349: #LC_nav_bar em {
6350: font-weight: bold;
6351: font-style: normal;
6352: }
6353:
6354: ol.LC_primary_menu {
6355: float: right;
6356: margin: 0;
6357: background-color: $pgbg_or_bgcolor;
6358: }
6359:
6360: ol#LC_PathBreadcrumbs {
6361: margin: 0;
6362: }
6363:
6364: ol.LC_primary_menu li {
6365: display: inline;
6366: padding: 5px 5px 0 10px;
6367: vertical-align: top;
6368: }
6369:
6370: ol.LC_primary_menu li img {
6371: vertical-align: bottom;
6372: height: 1.1em;
6373: }
6374:
6375: ol.LC_primary_menu a {
6376: color: RGB(80, 80, 80);
6377: text-decoration: none;
6378: }
6379:
6380: ol.LC_primary_menu a.LC_new_message {
6381: font-weight:bold;
6382: color: darkred;
6383: }
6384:
6385: ol.LC_docs_parameters {
6386: margin-left: 0;
6387: padding: 0;
6388: list-style: none;
6389: }
6390:
6391: ol.LC_docs_parameters li {
6392: margin: 0;
6393: padding-right: 20px;
6394: display: inline;
6395: }
6396:
6397: ol.LC_docs_parameters li:before {
6398: content: "\\002022 \\0020";
6399: }
6400:
6401: li.LC_docs_parameters_title {
6402: font-weight: bold;
6403: }
6404:
6405: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6406: content: "";
6407: }
6408:
6409: ul#LC_secondary_menu {
6410: clear: both;
6411: color: $fontmenu;
6412: background: $tabbg;
6413: list-style: none;
6414: padding: 0;
6415: margin: 0;
6416: width: 100%;
6417: text-align: left;
6418: }
6419:
6420: ul#LC_secondary_menu li {
6421: font-weight: bold;
6422: line-height: 1.8em;
6423: padding: 0 0.8em;
6424: border-right: 1px solid black;
6425: display: inline;
6426: vertical-align: middle;
6427: }
6428:
6429: ul.LC_TabContent {
6430: display:block;
6431: background: $sidebg;
6432: border-bottom: solid 1px $lg_border_color;
6433: list-style:none;
6434: margin: -1px -10px 0 -10px;
6435: padding: 0;
6436: }
6437:
6438: ul.LC_TabContent li,
6439: ul.LC_TabContentBigger li {
6440: float:left;
6441: }
6442:
6443: ul#LC_secondary_menu li a {
6444: color: $fontmenu;
6445: text-decoration: none;
6446: }
6447:
6448: ul.LC_TabContent {
6449: min-height:20px;
6450: }
6451:
6452: ul.LC_TabContent li {
6453: vertical-align:middle;
6454: padding: 0 16px 0 10px;
6455: background-color:$tabbg;
6456: border-bottom:solid 1px $lg_border_color;
6457: border-left: solid 1px $font;
6458: }
6459:
6460: ul.LC_TabContent .right {
6461: float:right;
6462: }
6463:
6464: ul.LC_TabContent li a,
6465: ul.LC_TabContent li {
6466: color:rgb(47,47,47);
6467: text-decoration:none;
6468: font-size:95%;
6469: font-weight:bold;
6470: min-height:20px;
6471: }
6472:
6473: ul.LC_TabContent li a:hover,
6474: ul.LC_TabContent li a:focus {
6475: color: $button_hover;
6476: background:none;
6477: outline:none;
6478: }
6479:
6480: ul.LC_TabContent li:hover {
6481: color: $button_hover;
6482: cursor:pointer;
6483: }
6484:
6485: ul.LC_TabContent li.active {
6486: color: $font;
6487: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6488: border-bottom:solid 1px #FFFFFF;
6489: cursor: default;
6490: }
6491:
6492: ul.LC_TabContent li.active a {
6493: color:$font;
6494: background:#FFFFFF;
6495: outline: none;
6496: }
6497:
6498: ul.LC_TabContent li.goback {
6499: float: left;
6500: border-left: none;
6501: }
6502:
6503: #maincoursedoc {
6504: clear:both;
6505: }
6506:
6507: ul.LC_TabContentBigger {
6508: display:block;
6509: list-style:none;
6510: padding: 0;
6511: }
6512:
6513: ul.LC_TabContentBigger li {
6514: vertical-align:bottom;
6515: height: 30px;
6516: font-size:110%;
6517: font-weight:bold;
6518: color: #737373;
6519: }
6520:
6521: ul.LC_TabContentBigger li.active {
6522: position: relative;
6523: top: 1px;
6524: }
6525:
6526: ul.LC_TabContentBigger li a {
6527: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6528: height: 30px;
6529: line-height: 30px;
6530: text-align: center;
6531: display: block;
6532: text-decoration: none;
6533: outline: none;
6534: }
6535:
6536: ul.LC_TabContentBigger li.active a {
6537: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6538: color:$font;
6539: }
6540:
6541: ul.LC_TabContentBigger li b {
6542: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6543: display: block;
6544: float: left;
6545: padding: 0 30px;
6546: border-bottom: 1px solid $lg_border_color;
6547: }
6548:
6549: ul.LC_TabContentBigger li:hover b {
6550: color:$button_hover;
6551: }
6552:
6553: ul.LC_TabContentBigger li.active b {
6554: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6555: color:$font;
6556: border: 0;
6557: }
6558:
6559:
6560: ul.LC_CourseBreadcrumbs {
6561: background: $sidebg;
6562: height: 2em;
6563: padding-left: 10px;
6564: margin: 0;
6565: list-style-position: inside;
6566: }
6567:
6568: ol#LC_MenuBreadcrumbs,
6569: ol#LC_PathBreadcrumbs {
6570: padding-left: 10px;
6571: margin: 0;
6572: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6573: }
6574:
6575: ol#LC_MenuBreadcrumbs li,
6576: ol#LC_PathBreadcrumbs li,
6577: ul.LC_CourseBreadcrumbs li {
6578: display: inline;
6579: white-space: normal;
6580: }
6581:
6582: ol#LC_MenuBreadcrumbs li a,
6583: ul.LC_CourseBreadcrumbs li a {
6584: text-decoration: none;
6585: font-size:90%;
6586: }
6587:
6588: ol#LC_MenuBreadcrumbs h1 {
6589: display: inline;
6590: font-size: 90%;
6591: line-height: 2.5em;
6592: margin: 0;
6593: padding: 0;
6594: }
6595:
6596: ol#LC_PathBreadcrumbs li a {
6597: text-decoration:none;
6598: font-size:100%;
6599: font-weight:bold;
6600: }
6601:
6602: .LC_Box {
6603: border: solid 1px $lg_border_color;
6604: padding: 0 10px 10px 10px;
6605: }
6606:
6607: .LC_DocsBox {
6608: border: solid 1px $lg_border_color;
6609: padding: 0 0 10px 10px;
6610: }
6611:
6612: .LC_AboutMe_Image {
6613: float:left;
6614: margin-right:10px;
6615: }
6616:
6617: .LC_Clear_AboutMe_Image {
6618: clear:left;
6619: }
6620:
6621: dl.LC_ListStyleClean dt {
6622: padding-right: 5px;
6623: display: table-header-group;
6624: }
6625:
6626: dl.LC_ListStyleClean dd {
6627: display: table-row;
6628: }
6629:
6630: .LC_ListStyleClean,
6631: .LC_ListStyleSimple,
6632: .LC_ListStyleNormal,
6633: .LC_ListStyleSpecial {
6634: /* display:block; */
6635: list-style-position: inside;
6636: list-style-type: none;
6637: overflow: hidden;
6638: padding: 0;
6639: }
6640:
6641: .LC_ListStyleSimple li,
6642: .LC_ListStyleSimple dd,
6643: .LC_ListStyleNormal li,
6644: .LC_ListStyleNormal dd,
6645: .LC_ListStyleSpecial li,
6646: .LC_ListStyleSpecial dd {
6647: margin: 0;
6648: padding: 5px 5px 5px 10px;
6649: clear: both;
6650: }
6651:
6652: .LC_ListStyleClean li,
6653: .LC_ListStyleClean dd {
6654: padding-top: 0;
6655: padding-bottom: 0;
6656: }
6657:
6658: .LC_ListStyleSimple dd,
6659: .LC_ListStyleSimple li {
6660: border-bottom: solid 1px $lg_border_color;
6661: }
6662:
6663: .LC_ListStyleSpecial li,
6664: .LC_ListStyleSpecial dd {
6665: list-style-type: none;
6666: background-color: RGB(220, 220, 220);
6667: margin-bottom: 4px;
6668: }
6669:
6670: table.LC_SimpleTable {
6671: margin:5px;
6672: border:solid 1px $lg_border_color;
6673: }
6674:
6675: table.LC_SimpleTable tr {
6676: padding: 0;
6677: border:solid 1px $lg_border_color;
6678: }
6679:
6680: table.LC_SimpleTable thead {
6681: background:rgb(220,220,220);
6682: }
6683:
6684: div.LC_columnSection {
6685: display: block;
6686: clear: both;
6687: overflow: hidden;
6688: margin: 0;
6689: }
6690:
6691: div.LC_columnSection>* {
6692: float: left;
6693: margin: 10px 20px 10px 0;
6694: overflow:hidden;
6695: }
6696:
6697: table em {
6698: font-weight: bold;
6699: font-style: normal;
6700: }
6701:
6702: table.LC_tableBrowseRes,
6703: table.LC_tableOfContent {
6704: border:none;
6705: border-spacing: 1px;
6706: padding: 3px;
6707: background-color: #FFFFFF;
6708: font-size: 90%;
6709: }
6710:
6711: table.LC_tableOfContent {
6712: border-collapse: collapse;
6713: }
6714:
6715: table.LC_tableBrowseRes a,
6716: table.LC_tableOfContent a {
6717: background-color: transparent;
6718: text-decoration: none;
6719: }
6720:
6721: table.LC_tableOfContent img {
6722: border: none;
6723: height: 1.3em;
6724: vertical-align: text-bottom;
6725: margin-right: 0.3em;
6726: }
6727:
6728: a#LC_content_toolbar_firsthomework {
6729: background-image:url(/res/adm/pages/open-first-problem.gif);
6730: }
6731:
6732: a#LC_content_toolbar_everything {
6733: background-image:url(/res/adm/pages/show-all.gif);
6734: }
6735:
6736: a#LC_content_toolbar_uncompleted {
6737: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
6738: }
6739:
6740: #LC_content_toolbar_clearbubbles {
6741: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
6742: }
6743:
6744: a#LC_content_toolbar_changefolder {
6745: background : url(/res/adm/pages/close-all-folders.gif) top center ;
6746: }
6747:
6748: a#LC_content_toolbar_changefolder_toggled {
6749: background-image:url(/res/adm/pages/open-all-folders.gif);
6750: }
6751:
6752: a#LC_content_toolbar_edittoplevel {
6753: background-image:url(/res/adm/pages/edittoplevel.gif);
6754: }
6755:
6756: ul#LC_toolbar li a:hover {
6757: background-position: bottom center;
6758: }
6759:
6760: ul#LC_toolbar {
6761: padding: 0;
6762: margin: 2px;
6763: list-style:none;
6764: position:relative;
6765: background-color:white;
6766: }
6767:
6768: ul#LC_toolbar li {
6769: border:1px solid white;
6770: padding: 0;
6771: margin: 0;
6772: float: left;
6773: display:inline;
6774: vertical-align:middle;
6775: }
6776:
6777:
6778: a.LC_toolbarItem {
6779: display:block;
6780: padding: 0;
6781: margin: 0;
6782: height: 32px;
6783: width: 32px;
6784: color:white;
6785: border: none;
6786: background-repeat:no-repeat;
6787: background-color:transparent;
6788: }
6789:
6790: ul.LC_funclist {
6791: margin: 0;
6792: padding: 0.5em 1em 0.5em 0;
6793: }
6794:
6795: ul.LC_funclist > li:first-child {
6796: font-weight:bold;
6797: margin-left:0.8em;
6798: }
6799:
6800: ul.LC_funclist + ul.LC_funclist {
6801: /*
6802: left border as a seperator if we have more than
6803: one list
6804: */
6805: border-left: 1px solid $sidebg;
6806: /*
6807: this hides the left border behind the border of the
6808: outer box if element is wrapped to the next 'line'
6809: */
6810: margin-left: -1px;
6811: }
6812:
6813: ul.LC_funclist li {
6814: display: inline;
6815: white-space: nowrap;
6816: margin: 0 0 0 25px;
6817: line-height: 150%;
6818: }
6819:
6820: .LC_hidden {
6821: display: none;
6822: }
6823:
6824: .LCmodal-overlay {
6825: position:fixed;
6826: top:0;
6827: right:0;
6828: bottom:0;
6829: left:0;
6830: height:100%;
6831: width:100%;
6832: margin:0;
6833: padding:0;
6834: background:#999;
6835: opacity:.75;
6836: filter: alpha(opacity=75);
6837: -moz-opacity: 0.75;
6838: z-index:101;
6839: }
6840:
6841: * html .LCmodal-overlay {
6842: position: absolute;
6843: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
6844: }
6845:
6846: .LCmodal-window {
6847: position:fixed;
6848: top:50%;
6849: left:50%;
6850: margin:0;
6851: padding:0;
6852: z-index:102;
6853: }
6854:
6855: * html .LCmodal-window {
6856: position:absolute;
6857: }
6858:
6859: .LCclose-window {
6860: position:absolute;
6861: width:32px;
6862: height:32px;
6863: right:8px;
6864: top:8px;
6865: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
6866: text-indent:-99999px;
6867: overflow:hidden;
6868: cursor:pointer;
6869: }
6870:
6871: END
6872: }
6873:
6874: =pod
6875:
6876: =item * &headtag()
6877:
6878: Returns a uniform footer for LON-CAPA web pages.
6879:
6880: Inputs: $title - optional title for the head
6881: $head_extra - optional extra HTML to put inside the <head>
6882: $args - optional arguments
6883: force_register - if is true call registerurl so the remote is
6884: informed
6885: redirect -> array ref of
6886: 1- seconds before redirect occurs
6887: 2- url to redirect to
6888: 3- whether the side effect should occur
6889: (side effect of setting
6890: $env{'internal.head.redirect'} to the url
6891: redirected too)
6892: domain -> force to color decorate a page for a specific
6893: domain
6894: function -> force usage of a specific rolish color scheme
6895: bgcolor -> override the default page bgcolor
6896: no_auto_mt_title
6897: -> prevent &mt()ing the title arg
6898:
6899: =cut
6900:
6901: sub headtag {
6902: my ($title,$head_extra,$args) = @_;
6903:
6904: my $function = $args->{'function'} || &get_users_function();
6905: my $domain = $args->{'domain'} || &determinedomain();
6906: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
6907: my $url = join(':',$env{'user.name'},$env{'user.domain'},
6908: $Apache::lonnet::perlvar{'lonVersion'},
6909: #time(),
6910: $env{'environment.color.timestamp'},
6911: $function,$domain,$bgcolor);
6912:
6913: $url = '/adm/css/'.&escape($url).'.css';
6914:
6915: my $result =
6916: '<head>'.
6917: &font_settings();
6918:
6919: my $inhibitprint = &print_suppression();
6920:
6921: if (!$args->{'frameset'}) {
6922: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
6923: }
6924: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
6925: $result .= Apache::lonxml::display_title();
6926: }
6927: if (!$args->{'no_nav_bar'}
6928: && !$args->{'only_body'}
6929: && !$args->{'frameset'}) {
6930: $result .= &help_menu_js();
6931: $result.=&modal_window();
6932: $result.=&togglebox_script();
6933: $result.=&wishlist_window();
6934: $result.=&LCprogressbarUpdate_script();
6935: } else {
6936: if ($args->{'add_modal'}) {
6937: $result.=&modal_window();
6938: }
6939: if ($args->{'add_wishlist'}) {
6940: $result.=&wishlist_window();
6941: }
6942: if ($args->{'add_togglebox'}) {
6943: $result.=&togglebox_script();
6944: }
6945: if ($args->{'add_progressbar'}) {
6946: $result.=&LCprogressbarUpdate_script();
6947: }
6948: }
6949: if (ref($args->{'redirect'})) {
6950: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
6951: $url = &Apache::lonenc::check_encrypt($url);
6952: if (!$inhibit_continue) {
6953: $env{'internal.head.redirect'} = $url;
6954: }
6955: $result.=<<ADDMETA
6956: <meta http-equiv="pragma" content="no-cache" />
6957: <meta http-equiv="Refresh" content="$time; url=$url" />
6958: ADDMETA
6959: }
6960: if (!defined($title)) {
6961: $title = 'The LearningOnline Network with CAPA';
6962: }
6963: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6964: $result .= '<title> LON-CAPA '.$title.'</title>'
6965: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
6966: .$inhibitprint
6967: .$head_extra;
6968: return $result.'</head>';
6969: }
6970:
6971: =pod
6972:
6973: =item * &font_settings()
6974:
6975: Returns neccessary <meta> to set the proper encoding
6976:
6977: Inputs: none
6978:
6979: =cut
6980:
6981: sub font_settings {
6982: my $headerstring='';
6983: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
6984: $headerstring.=
6985: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
6986: }
6987: return $headerstring;
6988: }
6989:
6990: =pod
6991:
6992: =item * &print_suppression()
6993:
6994: In course context returns css which causes the body to be blank when media="print",
6995: if printout generation is unavailable for the current resource.
6996:
6997: This could be because:
6998:
6999: (a) printstartdate is in the future
7000:
7001: (b) printenddate is in the past
7002:
7003: (c) there is an active exam block with "printout"
7004: functionality blocked
7005:
7006: Users with pav, pfo or evb privileges are exempt.
7007:
7008: Inputs: none
7009:
7010: =cut
7011:
7012:
7013: sub print_suppression {
7014: my $noprint;
7015: if ($env{'request.course.id'}) {
7016: my $scope = $env{'request.course.id'};
7017: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7018: (&Apache::lonnet::allowed('pfo',$scope))) {
7019: return;
7020: }
7021: if ($env{'request.course.sec'} ne '') {
7022: $scope .= "/$env{'request.course.sec'}";
7023: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7024: (&Apache::lonnet::allowed('pfo',$scope))) {
7025: return;
7026: }
7027: }
7028: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7029: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7030: my $blocked = &blocking_status('printout',$cnum,$cdom);
7031: if ($blocked) {
7032: my $checkrole = "cm./$cdom/$cnum";
7033: if ($env{'request.course.sec'} ne '') {
7034: $checkrole .= "/$env{'request.course.sec'}";
7035: }
7036: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7037: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7038: $noprint = 1;
7039: }
7040: }
7041: unless ($noprint) {
7042: my $symb = &Apache::lonnet::symbread();
7043: if ($symb ne '') {
7044: my $navmap = Apache::lonnavmaps::navmap->new();
7045: if (ref($navmap)) {
7046: my $res = $navmap->getBySymb($symb);
7047: if (ref($res)) {
7048: if (!$res->resprintable()) {
7049: $noprint = 1;
7050: }
7051: }
7052: }
7053: }
7054: }
7055: if ($noprint) {
7056: return <<"ENDSTYLE";
7057: <style type="text/css" media="print">
7058: body { display:none }
7059: </style>
7060: ENDSTYLE
7061: }
7062: }
7063: return;
7064: }
7065:
7066: =pod
7067:
7068: =item * &xml_begin()
7069:
7070: Returns the needed doctype and <html>
7071:
7072: Inputs: none
7073:
7074: =cut
7075:
7076: sub xml_begin {
7077: my $output='';
7078:
7079: if ($env{'browser.mathml'}) {
7080: $output='<?xml version="1.0"?>'
7081: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7082: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7083:
7084: # .'<!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">] >'
7085: .'<!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">'
7086: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7087: .'xmlns="http://www.w3.org/1999/xhtml">';
7088: } else {
7089: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
7090: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
7091: }
7092: return $output;
7093: }
7094:
7095: =pod
7096:
7097: =item * &start_page()
7098:
7099: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7100:
7101: Inputs:
7102:
7103: =over 4
7104:
7105: $title - optional title for the page
7106:
7107: $head_extra - optional extra HTML to incude inside the <head>
7108:
7109: $args - additional optional args supported are:
7110:
7111: =over 8
7112:
7113: only_body -> is true will set &bodytag() onlybodytag
7114: arg on
7115: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7116: add_entries -> additional attributes to add to the <body>
7117: domain -> force to color decorate a page for a
7118: specific domain
7119: function -> force usage of a specific rolish color
7120: scheme
7121: redirect -> see &headtag()
7122: bgcolor -> override the default page bg color
7123: js_ready -> return a string ready for being used in
7124: a javascript writeln
7125: html_encode -> return a string ready for being used in
7126: a html attribute
7127: force_register -> if is true will turn on the &bodytag()
7128: $forcereg arg
7129: frameset -> if true will start with a <frameset>
7130: rather than <body>
7131: skip_phases -> hash ref of
7132: head -> skip the <html><head> generation
7133: body -> skip all <body> generation
7134: no_auto_mt_title -> prevent &mt()ing the title arg
7135: inherit_jsmath -> when creating popup window in a page,
7136: should it have jsmath forced on by the
7137: current page
7138: bread_crumbs -> Array containing breadcrumbs
7139: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7140:
7141: =back
7142:
7143: =back
7144:
7145: =cut
7146:
7147: sub start_page {
7148: my ($title,$head_extra,$args) = @_;
7149: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7150:
7151: $env{'internal.start_page'}++;
7152: my $result;
7153:
7154: if (! exists($args->{'skip_phases'}{'head'}) ) {
7155: $result .= &xml_begin() . &headtag($title, $head_extra, $args);
7156: }
7157:
7158: if (! exists($args->{'skip_phases'}{'body'}) ) {
7159: if ($args->{'frameset'}) {
7160: my $attr_string = &make_attr_string($args->{'force_register'},
7161: $args->{'add_entries'});
7162: $result .= "\n<frameset $attr_string>\n";
7163: } else {
7164: $result .=
7165: &bodytag($title,
7166: $args->{'function'}, $args->{'add_entries'},
7167: $args->{'only_body'}, $args->{'domain'},
7168: $args->{'force_register'}, $args->{'no_nav_bar'},
7169: $args->{'bgcolor'}, $args);
7170: }
7171: }
7172:
7173: if ($args->{'js_ready'}) {
7174: $result = &js_ready($result);
7175: }
7176: if ($args->{'html_encode'}) {
7177: $result = &html_encode($result);
7178: }
7179:
7180: # Preparation for new and consistent functionlist at top of screen
7181: # if ($args->{'functionlist'}) {
7182: # $result .= &build_functionlist();
7183: #}
7184:
7185: # Don't add anything more if only_body wanted or in const space
7186: return $result if $args->{'only_body'}
7187: || $env{'request.state'} eq 'construct';
7188:
7189: #Breadcrumbs
7190: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7191: &Apache::lonhtmlcommon::clear_breadcrumbs();
7192: #if any br links exists, add them to the breadcrumbs
7193: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7194: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7195: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7196: }
7197: }
7198:
7199: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7200: if(exists($args->{'bread_crumbs_component'})){
7201: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7202: }else{
7203: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7204: }
7205: }
7206: return $result;
7207: }
7208:
7209: sub end_page {
7210: my ($args) = @_;
7211: $env{'internal.end_page'}++;
7212: my $result;
7213: if ($args->{'discussion'}) {
7214: my ($target,$parser);
7215: if (ref($args->{'discussion'})) {
7216: ($target,$parser) =($args->{'discussion'}{'target'},
7217: $args->{'discussion'}{'parser'});
7218: }
7219: $result .= &Apache::lonxml::xmlend($target,$parser);
7220: }
7221: if ($args->{'frameset'}) {
7222: $result .= '</frameset>';
7223: } else {
7224: $result .= &endbodytag($args);
7225: }
7226: $result .= "\n</html>";
7227:
7228: if ($args->{'js_ready'}) {
7229: $result = &js_ready($result);
7230: }
7231:
7232: if ($args->{'html_encode'}) {
7233: $result = &html_encode($result);
7234: }
7235:
7236: return $result;
7237: }
7238:
7239: sub wishlist_window {
7240: return(<<'ENDWISHLIST');
7241: <script type="text/javascript">
7242: // <![CDATA[
7243: // <!-- BEGIN LON-CAPA Internal
7244: function set_wishlistlink(title, path) {
7245: if (!title) {
7246: title = document.title;
7247: title = title.replace(/^LON-CAPA /,'');
7248: }
7249: if (!path) {
7250: path = location.pathname;
7251: }
7252: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7253: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7254: }
7255: // END LON-CAPA Internal -->
7256: // ]]>
7257: </script>
7258: ENDWISHLIST
7259: }
7260:
7261: sub modal_window {
7262: return(<<'ENDMODAL');
7263: <script type="text/javascript">
7264: // <![CDATA[
7265: // <!-- BEGIN LON-CAPA Internal
7266: var modalWindow = {
7267: parent:"body",
7268: windowId:null,
7269: content:null,
7270: width:null,
7271: height:null,
7272: close:function()
7273: {
7274: $(".LCmodal-window").remove();
7275: $(".LCmodal-overlay").remove();
7276: },
7277: open:function()
7278: {
7279: var modal = "";
7280: modal += "<div class=\"LCmodal-overlay\"></div>";
7281: modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
7282: modal += this.content;
7283: modal += "</div>";
7284:
7285: $(this.parent).append(modal);
7286:
7287: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7288: $(".LCclose-window").click(function(){modalWindow.close();});
7289: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7290: }
7291: };
7292: var openMyModal = function(source,width,height,scrolling)
7293: {
7294: modalWindow.windowId = "myModal";
7295: modalWindow.width = width;
7296: modalWindow.height = height;
7297: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'></iframe>";
7298: modalWindow.open();
7299: };
7300: // END LON-CAPA Internal -->
7301: // ]]>
7302: </script>
7303: ENDMODAL
7304: }
7305:
7306: sub modal_link {
7307: my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
7308: unless ($width) { $width=480; }
7309: unless ($height) { $height=400; }
7310: unless ($scrolling) { $scrolling='yes'; }
7311: return '<a href="'.$link.'" target="'.$target.'" title="'.$title.'" onclick="openMyModal(\''.$link.'\','.$width.','.$height.',\''.$scrolling.'\'); return false;">'.
7312: $linktext.'</a>';
7313: }
7314:
7315: sub modal_adhoc_script {
7316: my ($funcname,$width,$height,$content)=@_;
7317: return (<<ENDADHOC);
7318: <script type="text/javascript">
7319: // <![CDATA[
7320: var $funcname = function()
7321: {
7322: modalWindow.windowId = "myModal";
7323: modalWindow.width = $width;
7324: modalWindow.height = $height;
7325: modalWindow.content = '$content';
7326: modalWindow.open();
7327: };
7328: // ]]>
7329: </script>
7330: ENDADHOC
7331: }
7332:
7333: sub modal_adhoc_inner {
7334: my ($funcname,$width,$height,$content)=@_;
7335: my $innerwidth=$width-20;
7336: $content=&js_ready(
7337: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7338: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
7339: $content.
7340: &end_scrollbox().
7341: &end_page()
7342: );
7343: return &modal_adhoc_script($funcname,$width,$height,$content);
7344: }
7345:
7346: sub modal_adhoc_window {
7347: my ($funcname,$width,$height,$content,$linktext)=@_;
7348: return &modal_adhoc_inner($funcname,$width,$height,$content).
7349: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7350: }
7351:
7352: sub modal_adhoc_launch {
7353: my ($funcname,$width,$height,$content)=@_;
7354: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7355: <script type="text/javascript">
7356: // <![CDATA[
7357: $funcname();
7358: // ]]>
7359: </script>
7360: ENDLAUNCH
7361: }
7362:
7363: sub modal_adhoc_close {
7364: return (<<ENDCLOSE);
7365: <script type="text/javascript">
7366: // <![CDATA[
7367: modalWindow.close();
7368: // ]]>
7369: </script>
7370: ENDCLOSE
7371: }
7372:
7373: sub togglebox_script {
7374: return(<<ENDTOGGLE);
7375: <script type="text/javascript">
7376: // <![CDATA[
7377: function LCtoggleDisplay(id,hidetext,showtext) {
7378: link = document.getElementById(id + "link").childNodes[0];
7379: with (document.getElementById(id).style) {
7380: if (display == "none" ) {
7381: display = "inline";
7382: link.nodeValue = hidetext;
7383: } else {
7384: display = "none";
7385: link.nodeValue = showtext;
7386: }
7387: }
7388: }
7389: // ]]>
7390: </script>
7391: ENDTOGGLE
7392: }
7393:
7394: sub start_togglebox {
7395: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7396: unless ($heading) { $heading=''; } else { $heading.=' '; }
7397: unless ($showtext) { $showtext=&mt('show'); }
7398: unless ($hidetext) { $hidetext=&mt('hide'); }
7399: unless ($headerbg) { $headerbg='#FFFFFF'; }
7400: return &start_data_table().
7401: &start_data_table_header_row().
7402: '<td bgcolor="'.$headerbg.'">'.$heading.
7403: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7404: $showtext.'\')">'.$showtext.'</a>]</td>'.
7405: &end_data_table_header_row().
7406: '<tr id="'.$id.'" style="display:none""><td>';
7407: }
7408:
7409: sub end_togglebox {
7410: return '</td></tr>'.&end_data_table();
7411: }
7412:
7413: sub LCprogressbar_script {
7414: my ($id)=@_;
7415: return(<<ENDPROGRESS);
7416: <script type="text/javascript">
7417: // <![CDATA[
7418: \$('#progressbar$id').progressbar({
7419: value: 0,
7420: change: function(event, ui) {
7421: var newVal = \$(this).progressbar('option', 'value');
7422: \$('.pblabel', this).text(LCprogressTxt);
7423: }
7424: });
7425: // ]]>
7426: </script>
7427: ENDPROGRESS
7428: }
7429:
7430: sub LCprogressbarUpdate_script {
7431: return(<<ENDPROGRESSUPDATE);
7432: <style type="text/css">
7433: .ui-progressbar { position:relative; }
7434: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7435: </style>
7436: <script type="text/javascript">
7437: // <![CDATA[
7438: var LCprogressTxt='---';
7439:
7440: function LCupdateProgress(percent,progresstext,id) {
7441: LCprogressTxt=progresstext;
7442: \$('#progressbar'+id).progressbar('value',percent);
7443: }
7444: // ]]>
7445: </script>
7446: ENDPROGRESSUPDATE
7447: }
7448:
7449: my $LClastpercent;
7450: my $LCidcnt;
7451: my $LCcurrentid;
7452:
7453: sub LCprogressbar {
7454: my ($r)=(@_);
7455: $LClastpercent=0;
7456: $LCidcnt++;
7457: $LCcurrentid=$$.'_'.$LCidcnt;
7458: my $starting=&mt('Starting');
7459: my $content=(<<ENDPROGBAR);
7460: <p>
7461: <div id="progressbar$LCcurrentid">
7462: <span class="pblabel">$starting</span>
7463: </div>
7464: </p>
7465: ENDPROGBAR
7466: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7467: }
7468:
7469: sub LCprogressbarUpdate {
7470: my ($r,$val,$text)=@_;
7471: unless ($val) {
7472: if ($LClastpercent) {
7473: $val=$LClastpercent;
7474: } else {
7475: $val=0;
7476: }
7477: }
7478: if ($val<0) { $val=0; }
7479: if ($val>100) { $val=0; }
7480: $LClastpercent=$val;
7481: unless ($text) { $text=$val.'%'; }
7482: $text=&js_ready($text);
7483: &r_print($r,<<ENDUPDATE);
7484: <script type="text/javascript">
7485: // <![CDATA[
7486: LCupdateProgress($val,'$text','$LCcurrentid');
7487: // ]]>
7488: </script>
7489: ENDUPDATE
7490: }
7491:
7492: sub LCprogressbarClose {
7493: my ($r)=@_;
7494: $LClastpercent=0;
7495: &r_print($r,<<ENDCLOSE);
7496: <script type="text/javascript">
7497: // <![CDATA[
7498: \$("#progressbar$LCcurrentid").hide('slow');
7499: // ]]>
7500: </script>
7501: ENDCLOSE
7502: }
7503:
7504: sub r_print {
7505: my ($r,$to_print)=@_;
7506: if ($r) {
7507: $r->print($to_print);
7508: $r->rflush();
7509: } else {
7510: print($to_print);
7511: }
7512: }
7513:
7514: sub html_encode {
7515: my ($result) = @_;
7516:
7517: $result = &HTML::Entities::encode($result,'<>&"');
7518:
7519: return $result;
7520: }
7521:
7522: sub js_ready {
7523: my ($result) = @_;
7524:
7525: $result =~ s/[\n\r]/ /xmsg;
7526: $result =~ s/\\/\\\\/xmsg;
7527: $result =~ s/'/\\'/xmsg;
7528: $result =~ s{</}{<\\/}xmsg;
7529:
7530: return $result;
7531: }
7532:
7533: sub validate_page {
7534: if ( exists($env{'internal.start_page'})
7535: && $env{'internal.start_page'} > 1) {
7536: &Apache::lonnet::logthis('start_page called multiple times '.
7537: $env{'internal.start_page'}.' '.
7538: $ENV{'request.filename'});
7539: }
7540: if ( exists($env{'internal.end_page'})
7541: && $env{'internal.end_page'} > 1) {
7542: &Apache::lonnet::logthis('end_page called multiple times '.
7543: $env{'internal.end_page'}.' '.
7544: $env{'request.filename'});
7545: }
7546: if ( exists($env{'internal.start_page'})
7547: && ! exists($env{'internal.end_page'})) {
7548: &Apache::lonnet::logthis('start_page called without end_page '.
7549: $env{'request.filename'});
7550: }
7551: if ( ! exists($env{'internal.start_page'})
7552: && exists($env{'internal.end_page'})) {
7553: &Apache::lonnet::logthis('end_page called without start_page'.
7554: $env{'request.filename'});
7555: }
7556: }
7557:
7558:
7559: sub start_scrollbox {
7560: my ($outerwidth,$width,$height,$id)=@_;
7561: unless ($outerwidth) { $outerwidth='520px'; }
7562: unless ($width) { $width='500px'; }
7563: unless ($height) { $height='200px'; }
7564: my ($table_id,$div_id);
7565: if ($id ne '') {
7566: $table_id = " id='table_$id'";
7567: $div_id = " id='div_$id'";
7568: }
7569: 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>";
7570: }
7571:
7572: sub end_scrollbox {
7573: return '</div></td></tr></table>';
7574: }
7575:
7576: sub simple_error_page {
7577: my ($r,$title,$msg) = @_;
7578: my $page =
7579: &Apache::loncommon::start_page($title).
7580: &mt($msg).
7581: &Apache::loncommon::end_page();
7582: if (ref($r)) {
7583: $r->print($page);
7584: return;
7585: }
7586: return $page;
7587: }
7588:
7589: {
7590: my @row_count;
7591:
7592: sub start_data_table_count {
7593: unshift(@row_count, 0);
7594: return;
7595: }
7596:
7597: sub end_data_table_count {
7598: shift(@row_count);
7599: return;
7600: }
7601:
7602: sub start_data_table {
7603: my ($add_class,$id) = @_;
7604: my $css_class = (join(' ','LC_data_table',$add_class));
7605: my $table_id;
7606: if (defined($id)) {
7607: $table_id = ' id="'.$id.'"';
7608: }
7609: &start_data_table_count();
7610: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
7611: }
7612:
7613: sub end_data_table {
7614: &end_data_table_count();
7615: return '</table>'."\n";;
7616: }
7617:
7618: sub start_data_table_row {
7619: my ($add_class, $id) = @_;
7620: $row_count[0]++;
7621: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7622: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7623: $id = (' id="'.$id.'"') unless ($id eq '');
7624: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7625: }
7626:
7627: sub continue_data_table_row {
7628: my ($add_class, $id) = @_;
7629: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7630: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7631: $id = (' id="'.$id.'"') unless ($id eq '');
7632: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7633: }
7634:
7635: sub end_data_table_row {
7636: return '</tr>'."\n";;
7637: }
7638:
7639: sub start_data_table_empty_row {
7640: # $row_count[0]++;
7641: return '<tr class="LC_empty_row" >'."\n";;
7642: }
7643:
7644: sub end_data_table_empty_row {
7645: return '</tr>'."\n";;
7646: }
7647:
7648: sub start_data_table_header_row {
7649: return '<tr class="LC_header_row">'."\n";;
7650: }
7651:
7652: sub end_data_table_header_row {
7653: return '</tr>'."\n";;
7654: }
7655:
7656: sub data_table_caption {
7657: my $caption = shift;
7658: return "<caption class=\"LC_caption\">$caption</caption>";
7659: }
7660: }
7661:
7662: =pod
7663:
7664: =item * &inhibit_menu_check($arg)
7665:
7666: Checks for a inhibitmenu state and generates output to preserve it
7667:
7668: Inputs: $arg - can be any of
7669: - undef - in which case the return value is a string
7670: to add into arguments list of a uri
7671: - 'input' - in which case the return value is a HTML
7672: <form> <input> field of type hidden to
7673: preserve the value
7674: - a url - in which case the return value is the url with
7675: the neccesary cgi args added to preserve the
7676: inhibitmenu state
7677: - a ref to a url - no return value, but the string is
7678: updated to include the neccessary cgi
7679: args to preserve the inhibitmenu state
7680:
7681: =cut
7682:
7683: sub inhibit_menu_check {
7684: my ($arg) = @_;
7685: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
7686: if ($arg eq 'input') {
7687: if ($env{'form.inhibitmenu'}) {
7688: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
7689: } else {
7690: return
7691: }
7692: }
7693: if ($env{'form.inhibitmenu'}) {
7694: if (ref($arg)) {
7695: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7696: } elsif ($arg eq '') {
7697: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
7698: } else {
7699: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7700: }
7701: }
7702: if (!ref($arg)) {
7703: return $arg;
7704: }
7705: }
7706:
7707: ###############################################
7708:
7709: =pod
7710:
7711: =back
7712:
7713: =head1 User Information Routines
7714:
7715: =over 4
7716:
7717: =item * &get_users_function()
7718:
7719: Used by &bodytag to determine the current users primary role.
7720: Returns either 'student','coordinator','admin', or 'author'.
7721:
7722: =cut
7723:
7724: ###############################################
7725: sub get_users_function {
7726: my $function = 'norole';
7727: if ($env{'request.role'}=~/^(st)/) {
7728: $function='student';
7729: }
7730: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
7731: $function='coordinator';
7732: }
7733: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
7734: $function='admin';
7735: }
7736: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
7737: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
7738: $function='author';
7739: }
7740: return $function;
7741: }
7742:
7743: ###############################################
7744:
7745: =pod
7746:
7747: =item * &show_course()
7748:
7749: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
7750: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
7751:
7752: Inputs:
7753: None
7754:
7755: Outputs:
7756: Scalar: 1 if 'Course' to be used, 0 otherwise.
7757:
7758: =cut
7759:
7760: ###############################################
7761: sub show_course {
7762: my $course = !$env{'user.adv'};
7763: if (!$env{'user.adv'}) {
7764: foreach my $env (keys(%env)) {
7765: next if ($env !~ m/^user\.priv\./);
7766: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
7767: $course = 0;
7768: last;
7769: }
7770: }
7771: }
7772: return $course;
7773: }
7774:
7775: ###############################################
7776:
7777: =pod
7778:
7779: =item * &check_user_status()
7780:
7781: Determines current status of supplied role for a
7782: specific user. Roles can be active, previous or future.
7783:
7784: Inputs:
7785: user's domain, user's username, course's domain,
7786: course's number, optional section ID.
7787:
7788: Outputs:
7789: role status: active, previous or future.
7790:
7791: =cut
7792:
7793: sub check_user_status {
7794: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
7795: my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
7796: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
7797: my @uroles = keys %userinfo;
7798: my $srchstr;
7799: my $active_chk = 'none';
7800: my $now = time;
7801: if (@uroles > 0) {
7802: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
7803: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
7804: } else {
7805: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
7806: }
7807: if (grep/^\Q$srchstr\E$/,@uroles) {
7808: my $role_end = 0;
7809: my $role_start = 0;
7810: $active_chk = 'active';
7811: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
7812: $role_end = $1;
7813: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
7814: $role_start = $1;
7815: }
7816: }
7817: if ($role_start > 0) {
7818: if ($now < $role_start) {
7819: $active_chk = 'future';
7820: }
7821: }
7822: if ($role_end > 0) {
7823: if ($now > $role_end) {
7824: $active_chk = 'previous';
7825: }
7826: }
7827: }
7828: }
7829: return $active_chk;
7830: }
7831:
7832: ###############################################
7833:
7834: =pod
7835:
7836: =item * &get_sections()
7837:
7838: Determines all the sections for a course including
7839: sections with students and sections containing other roles.
7840: Incoming parameters:
7841:
7842: 1. domain
7843: 2. course number
7844: 3. reference to array containing roles for which sections should
7845: be gathered (optional).
7846: 4. reference to array containing status types for which sections
7847: should be gathered (optional).
7848:
7849: If the third argument is undefined, sections are gathered for any role.
7850: If the fourth argument is undefined, sections are gathered for any status.
7851: Permissible values are 'active' or 'future' or 'previous'.
7852:
7853: Returns section hash (keys are section IDs, values are
7854: number of users in each section), subject to the
7855: optional roles filter, optional status filter
7856:
7857: =cut
7858:
7859: ###############################################
7860: sub get_sections {
7861: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
7862: if (!defined($cdom) || !defined($cnum)) {
7863: my $cid = $env{'request.course.id'};
7864:
7865: return if (!defined($cid));
7866:
7867: $cdom = $env{'course.'.$cid.'.domain'};
7868: $cnum = $env{'course.'.$cid.'.num'};
7869: }
7870:
7871: my %sectioncount;
7872: my $now = time;
7873:
7874: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
7875: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
7876: my $sec_index = &Apache::loncoursedata::CL_SECTION();
7877: my $status_index = &Apache::loncoursedata::CL_STATUS();
7878: my $start_index = &Apache::loncoursedata::CL_START();
7879: my $end_index = &Apache::loncoursedata::CL_END();
7880: my $status;
7881: while (my ($student,$data) = each(%$classlist)) {
7882: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
7883: $data->[$status_index],
7884: $data->[$start_index],
7885: $data->[$end_index]);
7886: if ($stu_status eq 'Active') {
7887: $status = 'active';
7888: } elsif ($end < $now) {
7889: $status = 'previous';
7890: } elsif ($start > $now) {
7891: $status = 'future';
7892: }
7893: if ($section ne '-1' && $section !~ /^\s*$/) {
7894: if ((!defined($possible_status)) || (($status ne '') &&
7895: (grep/^\Q$status\E$/,@{$possible_status}))) {
7896: $sectioncount{$section}++;
7897: }
7898: }
7899: }
7900: }
7901: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7902: foreach my $user (sort(keys(%courseroles))) {
7903: if ($user !~ /^(\w{2})/) { next; }
7904: my ($role) = ($user =~ /^(\w{2})/);
7905: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
7906: my ($section,$status);
7907: if ($role eq 'cr' &&
7908: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
7909: $section=$1;
7910: }
7911: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
7912: if (!defined($section) || $section eq '-1') { next; }
7913: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
7914: if ($end == -1 && $start == -1) {
7915: next; #deleted role
7916: }
7917: if (!defined($possible_status)) {
7918: $sectioncount{$section}++;
7919: } else {
7920: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
7921: $status = 'active';
7922: } elsif ($end < $now) {
7923: $status = 'future';
7924: } elsif ($start > $now) {
7925: $status = 'previous';
7926: }
7927: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
7928: $sectioncount{$section}++;
7929: }
7930: }
7931: }
7932: return %sectioncount;
7933: }
7934:
7935: ###############################################
7936:
7937: =pod
7938:
7939: =item * &get_course_users()
7940:
7941: Retrieves usernames:domains for users in the specified course
7942: with specific role(s), and access status.
7943:
7944: Incoming parameters:
7945: 1. course domain
7946: 2. course number
7947: 3. access status: users must have - either active,
7948: previous, future, or all.
7949: 4. reference to array of permissible roles
7950: 5. reference to array of section restrictions (optional)
7951: 6. reference to results object (hash of hashes).
7952: 7. reference to optional userdata hash
7953: 8. reference to optional statushash
7954: 9. flag if privileged users (except those set to unhide in
7955: course settings) should be excluded
7956: Keys of top level results hash are roles.
7957: Keys of inner hashes are username:domain, with
7958: values set to access type.
7959: Optional userdata hash returns an array with arguments in the
7960: same order as loncoursedata::get_classlist() for student data.
7961:
7962: Optional statushash returns
7963:
7964: Entries for end, start, section and status are blank because
7965: of the possibility of multiple values for non-student roles.
7966:
7967: =cut
7968:
7969: ###############################################
7970:
7971: sub get_course_users {
7972: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
7973: my %idx = ();
7974: my %seclists;
7975:
7976: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
7977: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
7978: $idx{end} = &Apache::loncoursedata::CL_END();
7979: $idx{start} = &Apache::loncoursedata::CL_START();
7980: $idx{id} = &Apache::loncoursedata::CL_ID();
7981: $idx{section} = &Apache::loncoursedata::CL_SECTION();
7982: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
7983: $idx{status} = &Apache::loncoursedata::CL_STATUS();
7984:
7985: if (grep(/^st$/,@{$roles})) {
7986: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
7987: my $now = time;
7988: foreach my $student (keys(%{$classlist})) {
7989: my $match = 0;
7990: my $secmatch = 0;
7991: my $section = $$classlist{$student}[$idx{section}];
7992: my $status = $$classlist{$student}[$idx{status}];
7993: if ($section eq '') {
7994: $section = 'none';
7995: }
7996: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7997: if (grep(/^all$/,@{$sections})) {
7998: $secmatch = 1;
7999: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8000: if (grep(/^none$/,@{$sections})) {
8001: $secmatch = 1;
8002: }
8003: } else {
8004: if (grep(/^\Q$section\E$/,@{$sections})) {
8005: $secmatch = 1;
8006: }
8007: }
8008: if (!$secmatch) {
8009: next;
8010: }
8011: }
8012: if (defined($$types{'active'})) {
8013: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8014: push(@{$$users{st}{$student}},'active');
8015: $match = 1;
8016: }
8017: }
8018: if (defined($$types{'previous'})) {
8019: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8020: push(@{$$users{st}{$student}},'previous');
8021: $match = 1;
8022: }
8023: }
8024: if (defined($$types{'future'})) {
8025: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8026: push(@{$$users{st}{$student}},'future');
8027: $match = 1;
8028: }
8029: }
8030: if ($match) {
8031: push(@{$seclists{$student}},$section);
8032: if (ref($userdata) eq 'HASH') {
8033: $$userdata{$student} = $$classlist{$student};
8034: }
8035: if (ref($statushash) eq 'HASH') {
8036: $statushash->{$student}{'st'}{$section} = $status;
8037: }
8038: }
8039: }
8040: }
8041: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8042: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8043: my $now = time;
8044: my %displaystatus = ( previous => 'Expired',
8045: active => 'Active',
8046: future => 'Future',
8047: );
8048: my %nothide;
8049: if ($hidepriv) {
8050: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8051: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8052: if ($user !~ /:/) {
8053: $nothide{join(':',split(/[\@]/,$user))}=1;
8054: } else {
8055: $nothide{$user} = 1;
8056: }
8057: }
8058: }
8059: foreach my $person (sort(keys(%coursepersonnel))) {
8060: my $match = 0;
8061: my $secmatch = 0;
8062: my $status;
8063: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8064: $user =~ s/:$//;
8065: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8066: if ($end == -1 || $start == -1) {
8067: next;
8068: }
8069: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8070: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8071: my ($uname,$udom) = split(/:/,$user);
8072: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8073: if (grep(/^all$/,@{$sections})) {
8074: $secmatch = 1;
8075: } elsif ($usec eq '') {
8076: if (grep(/^none$/,@{$sections})) {
8077: $secmatch = 1;
8078: }
8079: } else {
8080: if (grep(/^\Q$usec\E$/,@{$sections})) {
8081: $secmatch = 1;
8082: }
8083: }
8084: if (!$secmatch) {
8085: next;
8086: }
8087: }
8088: if ($usec eq '') {
8089: $usec = 'none';
8090: }
8091: if ($uname ne '' && $udom ne '') {
8092: if ($hidepriv) {
8093: if ((&Apache::lonnet::privileged($uname,$udom)) &&
8094: (!$nothide{$uname.':'.$udom})) {
8095: next;
8096: }
8097: }
8098: if ($end > 0 && $end < $now) {
8099: $status = 'previous';
8100: } elsif ($start > $now) {
8101: $status = 'future';
8102: } else {
8103: $status = 'active';
8104: }
8105: foreach my $type (keys(%{$types})) {
8106: if ($status eq $type) {
8107: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8108: push(@{$$users{$role}{$user}},$type);
8109: }
8110: $match = 1;
8111: }
8112: }
8113: if (($match) && (ref($userdata) eq 'HASH')) {
8114: if (!exists($$userdata{$uname.':'.$udom})) {
8115: &get_user_info($udom,$uname,\%idx,$userdata);
8116: }
8117: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8118: push(@{$seclists{$uname.':'.$udom}},$usec);
8119: }
8120: if (ref($statushash) eq 'HASH') {
8121: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8122: }
8123: }
8124: }
8125: }
8126: }
8127: if (grep(/^ow$/,@{$roles})) {
8128: if ((defined($cdom)) && (defined($cnum))) {
8129: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8130: if ( defined($csettings{'internal.courseowner'}) ) {
8131: my $owner = $csettings{'internal.courseowner'};
8132: next if ($owner eq '');
8133: my ($ownername,$ownerdom);
8134: if ($owner =~ /^([^:]+):([^:]+)$/) {
8135: $ownername = $1;
8136: $ownerdom = $2;
8137: } else {
8138: $ownername = $owner;
8139: $ownerdom = $cdom;
8140: $owner = $ownername.':'.$ownerdom;
8141: }
8142: @{$$users{'ow'}{$owner}} = 'any';
8143: if (defined($userdata) &&
8144: !exists($$userdata{$owner})) {
8145: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8146: if (!grep(/^none$/,@{$seclists{$owner}})) {
8147: push(@{$seclists{$owner}},'none');
8148: }
8149: if (ref($statushash) eq 'HASH') {
8150: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8151: }
8152: }
8153: }
8154: }
8155: }
8156: foreach my $user (keys(%seclists)) {
8157: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8158: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8159: }
8160: }
8161: return;
8162: }
8163:
8164: sub get_user_info {
8165: my ($udom,$uname,$idx,$userdata) = @_;
8166: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8167: &plainname($uname,$udom,'lastname');
8168: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8169: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8170: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8171: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8172: return;
8173: }
8174:
8175: ###############################################
8176:
8177: =pod
8178:
8179: =item * &get_user_quota()
8180:
8181: Retrieves quota assigned for storage of portfolio files for a user
8182:
8183: Incoming parameters:
8184: 1. user's username
8185: 2. user's domain
8186:
8187: Returns:
8188: 1. Disk quota (in Mb) assigned to student.
8189: 2. (Optional) Type of setting: custom or default
8190: (individually assigned or default for user's
8191: institutional status).
8192: 3. (Optional) - User's institutional status (e.g., faculty, staff
8193: or student - types as defined in localenroll::inst_usertypes
8194: for user's domain, which determines default quota for user.
8195: 4. (Optional) - Default quota which would apply to the user.
8196:
8197: If a value has been stored in the user's environment,
8198: it will return that, otherwise it returns the maximal default
8199: defined for the user's instituional status(es) in the domain.
8200:
8201: =cut
8202:
8203: ###############################################
8204:
8205:
8206: sub get_user_quota {
8207: my ($uname,$udom) = @_;
8208: my ($quota,$quotatype,$settingstatus,$defquota);
8209: if (!defined($udom)) {
8210: $udom = $env{'user.domain'};
8211: }
8212: if (!defined($uname)) {
8213: $uname = $env{'user.name'};
8214: }
8215: if (($udom eq '' || $uname eq '') ||
8216: ($udom eq 'public') && ($uname eq 'public')) {
8217: $quota = 0;
8218: $quotatype = 'default';
8219: $defquota = 0;
8220: } else {
8221: my $inststatus;
8222: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8223: $quota = $env{'environment.portfolioquota'};
8224: $inststatus = $env{'environment.inststatus'};
8225: } else {
8226: my %userenv =
8227: &Apache::lonnet::get('environment',['portfolioquota',
8228: 'inststatus'],$udom,$uname);
8229: my ($tmp) = keys(%userenv);
8230: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8231: $quota = $userenv{'portfolioquota'};
8232: $inststatus = $userenv{'inststatus'};
8233: } else {
8234: undef(%userenv);
8235: }
8236: }
8237: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
8238: if ($quota eq '') {
8239: $quota = $defquota;
8240: $quotatype = 'default';
8241: } else {
8242: $quotatype = 'custom';
8243: }
8244: }
8245: if (wantarray) {
8246: return ($quota,$quotatype,$settingstatus,$defquota);
8247: } else {
8248: return $quota;
8249: }
8250: }
8251:
8252: ###############################################
8253:
8254: =pod
8255:
8256: =item * &default_quota()
8257:
8258: Retrieves default quota assigned for storage of user portfolio files,
8259: given an (optional) user's institutional status.
8260:
8261: Incoming parameters:
8262: 1. domain
8263: 2. (Optional) institutional status(es). This is a : separated list of
8264: status types (e.g., faculty, staff, student etc.)
8265: which apply to the user for whom the default is being retrieved.
8266: If the institutional status string in undefined, the domain
8267: default quota will be returned.
8268:
8269: Returns:
8270: 1. Default disk quota (in Mb) for user portfolios in the domain.
8271: 2. (Optional) institutional type which determined the value of the
8272: default quota.
8273:
8274: If a value has been stored in the domain's configuration db,
8275: it will return that, otherwise it returns 20 (for backwards
8276: compatibility with domains which have not set up a configuration
8277: db file; the original statically defined portfolio quota was 20 Mb).
8278:
8279: If the user's status includes multiple types (e.g., staff and student),
8280: the largest default quota which applies to the user determines the
8281: default quota returned.
8282:
8283: =back
8284:
8285: =cut
8286:
8287: ###############################################
8288:
8289:
8290: sub default_quota {
8291: my ($udom,$inststatus) = @_;
8292: my ($defquota,$settingstatus);
8293: my %quotahash = &Apache::lonnet::get_dom('configuration',
8294: ['quotas'],$udom);
8295: if (ref($quotahash{'quotas'}) eq 'HASH') {
8296: if ($inststatus ne '') {
8297: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8298: foreach my $item (@statuses) {
8299: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8300: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
8301: if ($defquota eq '') {
8302: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8303: $settingstatus = $item;
8304: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
8305: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8306: $settingstatus = $item;
8307: }
8308: }
8309: } else {
8310: if ($quotahash{'quotas'}{$item} ne '') {
8311: if ($defquota eq '') {
8312: $defquota = $quotahash{'quotas'}{$item};
8313: $settingstatus = $item;
8314: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8315: $defquota = $quotahash{'quotas'}{$item};
8316: $settingstatus = $item;
8317: }
8318: }
8319: }
8320: }
8321: }
8322: if ($defquota eq '') {
8323: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8324: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
8325: } else {
8326: $defquota = $quotahash{'quotas'}{'default'};
8327: }
8328: $settingstatus = 'default';
8329: }
8330: } else {
8331: $settingstatus = 'default';
8332: $defquota = 20;
8333: }
8334: if (wantarray) {
8335: return ($defquota,$settingstatus);
8336: } else {
8337: return $defquota;
8338: }
8339: }
8340:
8341: sub get_secgrprole_info {
8342: my ($cdom,$cnum,$needroles,$type) = @_;
8343: my %sections_count = &get_sections($cdom,$cnum);
8344: my @sections = (sort {$a <=> $b} keys(%sections_count));
8345: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8346: my @groups = sort(keys(%curr_groups));
8347: my $allroles = [];
8348: my $rolehash;
8349: my $accesshash = {
8350: active => 'Currently has access',
8351: future => 'Will have future access',
8352: previous => 'Previously had access',
8353: };
8354: if ($needroles) {
8355: $rolehash = {'all' => 'all'};
8356: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8357: if (&Apache::lonnet::error(%user_roles)) {
8358: undef(%user_roles);
8359: }
8360: foreach my $item (keys(%user_roles)) {
8361: my ($role)=split(/\:/,$item,2);
8362: if ($role eq 'cr') { next; }
8363: if ($role =~ /^cr/) {
8364: $$rolehash{$role} = (split('/',$role))[3];
8365: } else {
8366: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
8367: }
8368: }
8369: foreach my $key (sort(keys(%{$rolehash}))) {
8370: push(@{$allroles},$key);
8371: }
8372: push (@{$allroles},'st');
8373: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
8374: }
8375: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
8376: }
8377:
8378: sub user_picker {
8379: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
8380: my $currdom = $dom;
8381: my %curr_selected = (
8382: srchin => 'dom',
8383: srchby => 'lastname',
8384: );
8385: my $srchterm;
8386: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
8387: if ($srch->{'srchby'} ne '') {
8388: $curr_selected{'srchby'} = $srch->{'srchby'};
8389: }
8390: if ($srch->{'srchin'} ne '') {
8391: $curr_selected{'srchin'} = $srch->{'srchin'};
8392: }
8393: if ($srch->{'srchtype'} ne '') {
8394: $curr_selected{'srchtype'} = $srch->{'srchtype'};
8395: }
8396: if ($srch->{'srchdomain'} ne '') {
8397: $currdom = $srch->{'srchdomain'};
8398: }
8399: $srchterm = $srch->{'srchterm'};
8400: }
8401: my %lt=&Apache::lonlocal::texthash(
8402: 'usr' => 'Search criteria',
8403: 'doma' => 'Domain/institution to search',
8404: 'uname' => 'username',
8405: 'lastname' => 'last name',
8406: 'lastfirst' => 'last name, first name',
8407: 'crs' => 'in this course',
8408: 'dom' => 'in selected LON-CAPA domain',
8409: 'alc' => 'all LON-CAPA',
8410: 'instd' => 'in institutional directory for selected domain',
8411: 'exact' => 'is',
8412: 'contains' => 'contains',
8413: 'begins' => 'begins with',
8414: 'youm' => "You must include some text to search for.",
8415: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
8416: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
8417: 'yomc' => "You must choose a domain when using an institutional directory search.",
8418: 'ymcd' => "You must choose a domain when using a domain search.",
8419: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
8420: 'whse' => "When searching by last,first you must include at least one character in the first name.",
8421: 'thfo' => "The following need to be corrected before the search can be run:",
8422: );
8423: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
8424: my $srchinsel = ' <select name="srchin">';
8425:
8426: my @srchins = ('crs','dom','alc','instd');
8427:
8428: foreach my $option (@srchins) {
8429: # FIXME 'alc' option unavailable until
8430: # loncreateuser::print_user_query_page()
8431: # has been completed.
8432: next if ($option eq 'alc');
8433: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
8434: next if ($option eq 'crs' && !$env{'request.course.id'});
8435: if ($curr_selected{'srchin'} eq $option) {
8436: $srchinsel .= '
8437: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8438: } else {
8439: $srchinsel .= '
8440: <option value="'.$option.'">'.$lt{$option}.'</option>';
8441: }
8442: }
8443: $srchinsel .= "\n </select>\n";
8444:
8445: my $srchbysel = ' <select name="srchby">';
8446: foreach my $option ('lastname','lastfirst','uname') {
8447: if ($curr_selected{'srchby'} eq $option) {
8448: $srchbysel .= '
8449: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8450: } else {
8451: $srchbysel .= '
8452: <option value="'.$option.'">'.$lt{$option}.'</option>';
8453: }
8454: }
8455: $srchbysel .= "\n </select>\n";
8456:
8457: my $srchtypesel = ' <select name="srchtype">';
8458: foreach my $option ('begins','contains','exact') {
8459: if ($curr_selected{'srchtype'} eq $option) {
8460: $srchtypesel .= '
8461: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8462: } else {
8463: $srchtypesel .= '
8464: <option value="'.$option.'">'.$lt{$option}.'</option>';
8465: }
8466: }
8467: $srchtypesel .= "\n </select>\n";
8468:
8469: my ($newuserscript,$new_user_create);
8470: my $context_dom = $env{'request.role.domain'};
8471: if ($context eq 'requestcrs') {
8472: if ($env{'form.coursedom'} ne '') {
8473: $context_dom = $env{'form.coursedom'};
8474: }
8475: }
8476: if ($forcenewuser) {
8477: if (ref($srch) eq 'HASH') {
8478: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
8479: if ($cancreate) {
8480: $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>';
8481: } else {
8482: my $helplink = 'javascript:helpMenu('."'display'".')';
8483: my %usertypetext = (
8484: official => 'institutional',
8485: unofficial => 'non-institutional',
8486: );
8487: $new_user_create = '<p class="LC_warning">'
8488: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
8489: .' '
8490: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
8491: ,'<a href="'.$helplink.'">','</a>')
8492: .'</p><br />';
8493: }
8494: }
8495: }
8496:
8497: $newuserscript = <<"ENDSCRIPT";
8498:
8499: function setSearch(createnew,callingForm) {
8500: if (createnew == 1) {
8501: for (var i=0; i<callingForm.srchby.length; i++) {
8502: if (callingForm.srchby.options[i].value == 'uname') {
8503: callingForm.srchby.selectedIndex = i;
8504: }
8505: }
8506: for (var i=0; i<callingForm.srchin.length; i++) {
8507: if ( callingForm.srchin.options[i].value == 'dom') {
8508: callingForm.srchin.selectedIndex = i;
8509: }
8510: }
8511: for (var i=0; i<callingForm.srchtype.length; i++) {
8512: if (callingForm.srchtype.options[i].value == 'exact') {
8513: callingForm.srchtype.selectedIndex = i;
8514: }
8515: }
8516: for (var i=0; i<callingForm.srchdomain.length; i++) {
8517: if (callingForm.srchdomain.options[i].value == '$context_dom') {
8518: callingForm.srchdomain.selectedIndex = i;
8519: }
8520: }
8521: }
8522: }
8523: ENDSCRIPT
8524:
8525: }
8526:
8527: my $output = <<"END_BLOCK";
8528: <script type="text/javascript">
8529: // <![CDATA[
8530: function validateEntry(callingForm) {
8531:
8532: var checkok = 1;
8533: var srchin;
8534: for (var i=0; i<callingForm.srchin.length; i++) {
8535: if ( callingForm.srchin[i].checked ) {
8536: srchin = callingForm.srchin[i].value;
8537: }
8538: }
8539:
8540: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
8541: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
8542: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
8543: var srchterm = callingForm.srchterm.value;
8544: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
8545: var msg = "";
8546:
8547: if (srchterm == "") {
8548: checkok = 0;
8549: msg += "$lt{'youm'}\\n";
8550: }
8551:
8552: if (srchtype== 'begins') {
8553: if (srchterm.length < 2) {
8554: checkok = 0;
8555: msg += "$lt{'thte'}\\n";
8556: }
8557: }
8558:
8559: if (srchtype== 'contains') {
8560: if (srchterm.length < 3) {
8561: checkok = 0;
8562: msg += "$lt{'thet'}\\n";
8563: }
8564: }
8565: if (srchin == 'instd') {
8566: if (srchdomain == '') {
8567: checkok = 0;
8568: msg += "$lt{'yomc'}\\n";
8569: }
8570: }
8571: if (srchin == 'dom') {
8572: if (srchdomain == '') {
8573: checkok = 0;
8574: msg += "$lt{'ymcd'}\\n";
8575: }
8576: }
8577: if (srchby == 'lastfirst') {
8578: if (srchterm.indexOf(",") == -1) {
8579: checkok = 0;
8580: msg += "$lt{'whus'}\\n";
8581: }
8582: if (srchterm.indexOf(",") == srchterm.length -1) {
8583: checkok = 0;
8584: msg += "$lt{'whse'}\\n";
8585: }
8586: }
8587: if (checkok == 0) {
8588: alert("$lt{'thfo'}\\n"+msg);
8589: return;
8590: }
8591: if (checkok == 1) {
8592: callingForm.submit();
8593: }
8594: }
8595:
8596: $newuserscript
8597:
8598: // ]]>
8599: </script>
8600:
8601: $new_user_create
8602:
8603: END_BLOCK
8604:
8605: $output .= &Apache::lonhtmlcommon::start_pick_box().
8606: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8607: $domform.
8608: &Apache::lonhtmlcommon::row_closure().
8609: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8610: $srchbysel.
8611: $srchtypesel.
8612: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8613: $srchinsel.
8614: &Apache::lonhtmlcommon::row_closure(1).
8615: &Apache::lonhtmlcommon::end_pick_box().
8616: '<br />';
8617: return $output;
8618: }
8619:
8620: sub user_rule_check {
8621: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
8622: my $response;
8623: if (ref($usershash) eq 'HASH') {
8624: foreach my $user (keys(%{$usershash})) {
8625: my ($uname,$udom) = split(/:/,$user);
8626: next if ($udom eq '' || $uname eq '');
8627: my ($id,$newuser);
8628: if (ref($usershash->{$user}) eq 'HASH') {
8629: $newuser = $usershash->{$user}->{'newuser'};
8630: $id = $usershash->{$user}->{'id'};
8631: }
8632: my $inst_response;
8633: if (ref($checks) eq 'HASH') {
8634: if (defined($checks->{'username'})) {
8635: ($inst_response,%{$inst_results->{$user}}) =
8636: &Apache::lonnet::get_instuser($udom,$uname);
8637: } elsif (defined($checks->{'id'})) {
8638: ($inst_response,%{$inst_results->{$user}}) =
8639: &Apache::lonnet::get_instuser($udom,undef,$id);
8640: }
8641: } else {
8642: ($inst_response,%{$inst_results->{$user}}) =
8643: &Apache::lonnet::get_instuser($udom,$uname);
8644: return;
8645: }
8646: if (!$got_rules->{$udom}) {
8647: my %domconfig = &Apache::lonnet::get_dom('configuration',
8648: ['usercreation'],$udom);
8649: if (ref($domconfig{'usercreation'}) eq 'HASH') {
8650: foreach my $item ('username','id') {
8651: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
8652: $$curr_rules{$udom}{$item} =
8653: $domconfig{'usercreation'}{$item.'_rule'};
8654: }
8655: }
8656: }
8657: $got_rules->{$udom} = 1;
8658: }
8659: foreach my $item (keys(%{$checks})) {
8660: if (ref($$curr_rules{$udom}) eq 'HASH') {
8661: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
8662: if (@{$$curr_rules{$udom}{$item}} > 0) {
8663: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
8664: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
8665: if ($rule_check{$rule}) {
8666: $$rulematch{$user}{$item} = $rule;
8667: if ($inst_response eq 'ok') {
8668: if (ref($inst_results) eq 'HASH') {
8669: if (ref($inst_results->{$user}) eq 'HASH') {
8670: if (keys(%{$inst_results->{$user}}) == 0) {
8671: $$alerts{$item}{$udom}{$uname} = 1;
8672: }
8673: }
8674: }
8675: }
8676: last;
8677: }
8678: }
8679: }
8680: }
8681: }
8682: }
8683: }
8684: }
8685: return;
8686: }
8687:
8688: sub user_rule_formats {
8689: my ($domain,$domdesc,$curr_rules,$check) = @_;
8690: my %text = (
8691: 'username' => 'Usernames',
8692: 'id' => 'IDs',
8693: );
8694: my $output;
8695: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
8696: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
8697: if (@{$ruleorder} > 0) {
8698: $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>';
8699: foreach my $rule (@{$ruleorder}) {
8700: if (ref($curr_rules) eq 'ARRAY') {
8701: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
8702: if (ref($rules->{$rule}) eq 'HASH') {
8703: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
8704: $rules->{$rule}{'desc'}.'</li>';
8705: }
8706: }
8707: }
8708: }
8709: $output .= '</ul>';
8710: }
8711: }
8712: return $output;
8713: }
8714:
8715: sub instrule_disallow_msg {
8716: my ($checkitem,$domdesc,$count,$mode) = @_;
8717: my $response;
8718: my %text = (
8719: item => 'username',
8720: items => 'usernames',
8721: match => 'matches',
8722: do => 'does',
8723: action => 'a username',
8724: one => 'one',
8725: );
8726: if ($count > 1) {
8727: $text{'item'} = 'usernames';
8728: $text{'match'} ='match';
8729: $text{'do'} = 'do';
8730: $text{'action'} = 'usernames',
8731: $text{'one'} = 'ones';
8732: }
8733: if ($checkitem eq 'id') {
8734: $text{'items'} = 'IDs';
8735: $text{'item'} = 'ID';
8736: $text{'action'} = 'an ID';
8737: if ($count > 1) {
8738: $text{'item'} = 'IDs';
8739: $text{'action'} = 'IDs';
8740: }
8741: }
8742: $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 />';
8743: if ($mode eq 'upload') {
8744: if ($checkitem eq 'username') {
8745: $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'}.");
8746: } elsif ($checkitem eq 'id') {
8747: $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.");
8748: }
8749: } elsif ($mode eq 'selfcreate') {
8750: if ($checkitem eq 'id') {
8751: $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.");
8752: }
8753: } else {
8754: if ($checkitem eq 'username') {
8755: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
8756: } elsif ($checkitem eq 'id') {
8757: $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.");
8758: }
8759: }
8760: return $response;
8761: }
8762:
8763: sub personal_data_fieldtitles {
8764: my %fieldtitles = &Apache::lonlocal::texthash (
8765: id => 'Student/Employee ID',
8766: permanentemail => 'E-mail address',
8767: lastname => 'Last Name',
8768: firstname => 'First Name',
8769: middlename => 'Middle Name',
8770: generation => 'Generation',
8771: gen => 'Generation',
8772: inststatus => 'Affiliation',
8773: );
8774: return %fieldtitles;
8775: }
8776:
8777: sub sorted_inst_types {
8778: my ($dom) = @_;
8779: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
8780: my $othertitle = &mt('All users');
8781: if ($env{'request.course.id'}) {
8782: $othertitle = &mt('Any users');
8783: }
8784: my @types;
8785: if (ref($order) eq 'ARRAY') {
8786: @types = @{$order};
8787: }
8788: if (@types == 0) {
8789: if (ref($usertypes) eq 'HASH') {
8790: @types = sort(keys(%{$usertypes}));
8791: }
8792: }
8793: if (keys(%{$usertypes}) > 0) {
8794: $othertitle = &mt('Other users');
8795: }
8796: return ($othertitle,$usertypes,\@types);
8797: }
8798:
8799: sub get_institutional_codes {
8800: my ($settings,$allcourses,$LC_code) = @_;
8801: # Get complete list of course sections to update
8802: my @currsections = ();
8803: my @currxlists = ();
8804: my $coursecode = $$settings{'internal.coursecode'};
8805:
8806: if ($$settings{'internal.sectionnums'} ne '') {
8807: @currsections = split(/,/,$$settings{'internal.sectionnums'});
8808: }
8809:
8810: if ($$settings{'internal.crosslistings'} ne '') {
8811: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
8812: }
8813:
8814: if (@currxlists > 0) {
8815: foreach (@currxlists) {
8816: if (m/^([^:]+):(\w*)$/) {
8817: unless (grep/^$1$/,@{$allcourses}) {
8818: push @{$allcourses},$1;
8819: $$LC_code{$1} = $2;
8820: }
8821: }
8822: }
8823: }
8824:
8825: if (@currsections > 0) {
8826: foreach (@currsections) {
8827: if (m/^(\w+):(\w*)$/) {
8828: my $sec = $coursecode.$1;
8829: my $lc_sec = $2;
8830: unless (grep/^$sec$/,@{$allcourses}) {
8831: push @{$allcourses},$sec;
8832: $$LC_code{$sec} = $lc_sec;
8833: }
8834: }
8835: }
8836: }
8837: return;
8838: }
8839:
8840: sub get_standard_codeitems {
8841: return ('Year','Semester','Department','Number','Section');
8842: }
8843:
8844: =pod
8845:
8846: =head1 Slot Helpers
8847:
8848: =over 4
8849:
8850: =item * sorted_slots()
8851:
8852: Sorts an array of slot names in order of an optional sort key,
8853: default sort is by slot start time (earliest first).
8854:
8855: Inputs:
8856:
8857: =over 4
8858:
8859: slotsarr - Reference to array of unsorted slot names.
8860:
8861: slots - Reference to hash of hash, where outer hash keys are slot names.
8862:
8863: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
8864:
8865: =back
8866:
8867: Returns:
8868:
8869: =over 4
8870:
8871: sorted - An array of slot names sorted by a specified sort key
8872: (default sort key is start time of the slot).
8873:
8874: =back
8875:
8876: =cut
8877:
8878:
8879: sub sorted_slots {
8880: my ($slotsarr,$slots,$sortkey) = @_;
8881: if ($sortkey eq '') {
8882: $sortkey = 'starttime';
8883: }
8884: my @sorted;
8885: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
8886: @sorted =
8887: sort {
8888: if (ref($slots->{$a}) && ref($slots->{$b})) {
8889: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
8890: }
8891: if (ref($slots->{$a})) { return -1;}
8892: if (ref($slots->{$b})) { return 1;}
8893: return 0;
8894: } @{$slotsarr};
8895: }
8896: return @sorted;
8897: }
8898:
8899: =pod
8900:
8901: =item * get_future_slots()
8902:
8903: Inputs:
8904:
8905: =over 4
8906:
8907: cnum - course number
8908:
8909: cdom - course domain
8910:
8911: now - current UNIX time
8912:
8913: symb - optional symb
8914:
8915: =back
8916:
8917: Returns:
8918:
8919: =over 4
8920:
8921: sorted_reservable - ref to array of student_schedulable slots currently
8922: reservable, ordered by end date of reservation period.
8923:
8924: reservable_now - ref to hash of student_schedulable slots currently
8925: reservable.
8926:
8927: Keys in inner hash are:
8928: (a) symb: either blank or symb to which slot use is restricted.
8929: (b) endreserve: end date of reservation period.
8930:
8931: sorted_future - ref to array of student_schedulable slots reservable in
8932: the future, ordered by start date of reservation period.
8933:
8934: future_reservable - ref to hash of student_schedulable slots reservable
8935: in the future.
8936:
8937: Keys in inner hash are:
8938: (a) symb: either blank or symb to which slot use is restricted.
8939: (b) startreserve: start date of reservation period.
8940:
8941: =back
8942:
8943: =cut
8944:
8945: sub get_future_slots {
8946: my ($cnum,$cdom,$now,$symb) = @_;
8947: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
8948: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
8949: foreach my $slot (keys(%slots)) {
8950: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
8951: if ($symb) {
8952: next if (($slots{$slot}->{'symb'} ne '') &&
8953: ($slots{$slot}->{'symb'} ne $symb));
8954: }
8955: if (($slots{$slot}->{'starttime'} > $now) &&
8956: ($slots{$slot}->{'endtime'} > $now)) {
8957: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
8958: my $userallowed = 0;
8959: if ($slots{$slot}->{'allowedsections'}) {
8960: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
8961: if (!defined($env{'request.role.sec'})
8962: && grep(/^No section assigned$/,@allowed_sec)) {
8963: $userallowed=1;
8964: } else {
8965: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
8966: $userallowed=1;
8967: }
8968: }
8969: unless ($userallowed) {
8970: if (defined($env{'request.course.groups'})) {
8971: my @groups = split(/:/,$env{'request.course.groups'});
8972: foreach my $group (@groups) {
8973: if (grep(/^\Q$group\E$/,@allowed_sec)) {
8974: $userallowed=1;
8975: last;
8976: }
8977: }
8978: }
8979: }
8980: }
8981: if ($slots{$slot}->{'allowedusers'}) {
8982: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
8983: my $user = $env{'user.name'}.':'.$env{'user.domain'};
8984: if (grep(/^\Q$user\E$/,@allowed_users)) {
8985: $userallowed = 1;
8986: }
8987: }
8988: next unless($userallowed);
8989: }
8990: my $startreserve = $slots{$slot}->{'startreserve'};
8991: my $endreserve = $slots{$slot}->{'endreserve'};
8992: my $symb = $slots{$slot}->{'symb'};
8993: if (($startreserve < $now) &&
8994: (!$endreserve || $endreserve > $now)) {
8995: my $lastres = $endreserve;
8996: if (!$lastres) {
8997: $lastres = $slots{$slot}->{'starttime'};
8998: }
8999: $reservable_now{$slot} = {
9000: symb => $symb,
9001: endreserve => $lastres
9002: };
9003: } elsif (($startreserve > $now) &&
9004: (!$endreserve || $endreserve > $startreserve)) {
9005: $future_reservable{$slot} = {
9006: symb => $symb,
9007: startreserve => $startreserve
9008: };
9009: }
9010: }
9011: }
9012: my @unsorted_reservable = keys(%reservable_now);
9013: if (@unsorted_reservable > 0) {
9014: @sorted_reservable =
9015: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9016: }
9017: my @unsorted_future = keys(%future_reservable);
9018: if (@unsorted_future > 0) {
9019: @sorted_future =
9020: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9021: }
9022: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9023: }
9024:
9025: =pod
9026:
9027: =back
9028:
9029: =head1 HTTP Helpers
9030:
9031: =over 4
9032:
9033: =item * &get_unprocessed_cgi($query,$possible_names)
9034:
9035: Modify the %env hash to contain unprocessed CGI form parameters held in
9036: $query. The parameters listed in $possible_names (an array reference),
9037: will be set in $env{'form.name'} if they do not already exist.
9038:
9039: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9040: $possible_names is an ref to an array of form element names. As an example:
9041: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9042: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9043:
9044: =cut
9045:
9046: sub get_unprocessed_cgi {
9047: my ($query,$possible_names)= @_;
9048: # $Apache::lonxml::debug=1;
9049: foreach my $pair (split(/&/,$query)) {
9050: my ($name, $value) = split(/=/,$pair);
9051: $name = &unescape($name);
9052: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9053: $value =~ tr/+/ /;
9054: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9055: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9056: }
9057: }
9058: }
9059:
9060: =pod
9061:
9062: =item * &cacheheader()
9063:
9064: returns cache-controlling header code
9065:
9066: =cut
9067:
9068: sub cacheheader {
9069: unless ($env{'request.method'} eq 'GET') { return ''; }
9070: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9071: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9072: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9073: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9074: return $output;
9075: }
9076:
9077: =pod
9078:
9079: =item * &no_cache($r)
9080:
9081: specifies header code to not have cache
9082:
9083: =cut
9084:
9085: sub no_cache {
9086: my ($r) = @_;
9087: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9088: $env{'request.method'} ne 'GET') { return ''; }
9089: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9090: $r->no_cache(1);
9091: $r->header_out("Expires" => $date);
9092: $r->header_out("Pragma" => "no-cache");
9093: }
9094:
9095: sub content_type {
9096: my ($r,$type,$charset) = @_;
9097: if ($r) {
9098: # Note that printout.pl calls this with undef for $r.
9099: &no_cache($r);
9100: }
9101: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9102: unless ($charset) {
9103: $charset=&Apache::lonlocal::current_encoding;
9104: }
9105: if ($charset) { $type.='; charset='.$charset; }
9106: if ($r) {
9107: $r->content_type($type);
9108: } else {
9109: print("Content-type: $type\n\n");
9110: }
9111: }
9112:
9113: =pod
9114:
9115: =item * &add_to_env($name,$value)
9116:
9117: adds $name to the %env hash with value
9118: $value, if $name already exists, the entry is converted to an array
9119: reference and $value is added to the array.
9120:
9121: =cut
9122:
9123: sub add_to_env {
9124: my ($name,$value)=@_;
9125: if (defined($env{$name})) {
9126: if (ref($env{$name})) {
9127: #already have multiple values
9128: push(@{ $env{$name} },$value);
9129: } else {
9130: #first time seeing multiple values, convert hash entry to an arrayref
9131: my $first=$env{$name};
9132: undef($env{$name});
9133: push(@{ $env{$name} },$first,$value);
9134: }
9135: } else {
9136: $env{$name}=$value;
9137: }
9138: }
9139:
9140: =pod
9141:
9142: =item * &get_env_multiple($name)
9143:
9144: gets $name from the %env hash, it seemlessly handles the cases where multiple
9145: values may be defined and end up as an array ref.
9146:
9147: returns an array of values
9148:
9149: =cut
9150:
9151: sub get_env_multiple {
9152: my ($name) = @_;
9153: my @values;
9154: if (defined($env{$name})) {
9155: # exists is it an array
9156: if (ref($env{$name})) {
9157: @values=@{ $env{$name} };
9158: } else {
9159: $values[0]=$env{$name};
9160: }
9161: }
9162: return(@values);
9163: }
9164:
9165: sub ask_for_embedded_content {
9166: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9167: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
9168: my $num = 0;
9169: my $numremref = 0;
9170: my $numinvalid = 0;
9171: my $numpathchg = 0;
9172: my $numexisting = 0;
9173: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
9174: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9175: my $current_path='/';
9176: if ($env{'form.currentpath'}) {
9177: $current_path = $env{'form.currentpath'};
9178: }
9179: if ($actionurl eq '/adm/coursegrp_portfolio') {
9180: $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9181: $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
9182: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9183: } else {
9184: $udom = $env{'user.domain'};
9185: $uname = $env{'user.name'};
9186: $url = '/userfiles/portfolio';
9187: }
9188: $toplevel = $url.'/';
9189: $url .= $current_path;
9190: $getpropath = 1;
9191: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9192: ($actionurl eq '/adm/imsimport')) {
9193: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9194: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9195: $toplevel = $url;
9196: if ($rest ne '') {
9197: $url .= $rest;
9198: }
9199: } elsif ($actionurl eq '/adm/coursedocs') {
9200: if (ref($args) eq 'HASH') {
9201: $url = $args->{'docs_url'};
9202: $toplevel = $url;
9203: }
9204: }
9205: my $now = time();
9206: foreach my $embed_file (keys(%{$allfiles})) {
9207: my $absolutepath;
9208: if ($embed_file =~ m{^\w+://}) {
9209: $newfiles{$embed_file} = 1;
9210: $mapping{$embed_file} = $embed_file;
9211: } else {
9212: if ($embed_file =~ m{^/}) {
9213: $absolutepath = $embed_file;
9214: $embed_file =~ s{^(/+)}{};
9215: }
9216: if ($embed_file =~ m{/}) {
9217: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
9218: $path = &check_for_traversal($path,$url,$toplevel);
9219: my $item = $fname;
9220: if ($path ne '') {
9221: $item = $path.'/'.$fname;
9222: $subdependencies{$path}{$fname} = 1;
9223: } else {
9224: $dependencies{$item} = 1;
9225: }
9226: if ($absolutepath) {
9227: $mapping{$item} = $absolutepath;
9228: } else {
9229: $mapping{$item} = $embed_file;
9230: }
9231: } else {
9232: $dependencies{$embed_file} = 1;
9233: if ($absolutepath) {
9234: $mapping{$embed_file} = $absolutepath;
9235: } else {
9236: $mapping{$embed_file} = $embed_file;
9237: }
9238: }
9239: }
9240: }
9241: foreach my $path (keys(%subdependencies)) {
9242: my %currsubfile;
9243: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9244: my ($sublistref,$listerror) =
9245: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9246: if (ref($sublistref) eq 'ARRAY') {
9247: foreach my $line (@{$sublistref}) {
9248: my ($file_name,$rest) = split(/\&/,$line,2);
9249: $currsubfile{$file_name} = 1;
9250: }
9251: }
9252: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9253: if (opendir(my $dir,$url.'/'.$path)) {
9254: my @subdir_list = grep(!/^\./,readdir($dir));
9255: map {$currsubfile{$_} = 1;} @subdir_list;
9256: }
9257: }
9258: foreach my $file (keys(%{$subdependencies{$path}})) {
9259: if ($currsubfile{$file}) {
9260: my $item = $path.'/'.$file;
9261: unless ($mapping{$item} eq $item) {
9262: $pathchanges{$item} = 1;
9263: }
9264: $existing{$item} = 1;
9265: $numexisting ++;
9266: } else {
9267: $newfiles{$path.'/'.$file} = 1;
9268: }
9269: }
9270: }
9271: my %currfile;
9272: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9273: my ($dirlistref,$listerror) =
9274: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
9275: if (ref($dirlistref) eq 'ARRAY') {
9276: foreach my $line (@{$dirlistref}) {
9277: my ($file_name,$rest) = split(/\&/,$line,2);
9278: $currfile{$file_name} = 1;
9279: }
9280: }
9281: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9282: if (opendir(my $dir,$url)) {
9283: my @dir_list = grep(!/^\./,readdir($dir));
9284: map {$currfile{$_} = 1;} @dir_list;
9285: }
9286: }
9287: foreach my $file (keys(%dependencies)) {
9288: if ($currfile{$file}) {
9289: unless ($mapping{$file} eq $file) {
9290: $pathchanges{$file} = 1;
9291: }
9292: $existing{$file} = 1;
9293: $numexisting ++;
9294: } else {
9295: $newfiles{$file} = 1;
9296: }
9297: }
9298: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
9299: $upload_output .= &start_data_table_row().
9300: '<td><span class="LC_filename">'.$embed_file.'</span>';
9301: unless ($mapping{$embed_file} eq $embed_file) {
9302: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
9303: }
9304: $upload_output .= '</td><td>';
9305: if ($args->{'ignore_remote_references'}
9306: && $embed_file =~ m{^\w+://}) {
9307: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
9308: $numremref++;
9309: } elsif ($args->{'error_on_invalid_names'}
9310: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
9311:
9312: $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
9313: $numinvalid++;
9314: } else {
9315: $upload_output .= &embedded_file_element('upload_embedded',$num,
9316: $embed_file,\%mapping,
9317: $allfiles,$codebase);
9318: $num++;
9319: }
9320: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
9321: }
9322: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
9323: $upload_output .= &start_data_table_row().
9324: '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
9325: '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
9326: &Apache::loncommon::end_data_table_row()."\n";
9327: }
9328: if ($upload_output) {
9329: $upload_output = &start_data_table().
9330: $upload_output.
9331: &end_data_table()."\n";
9332: }
9333: my $applies = 0;
9334: if ($numremref) {
9335: $applies ++;
9336: }
9337: if ($numinvalid) {
9338: $applies ++;
9339: }
9340: if ($numexisting) {
9341: $applies ++;
9342: }
9343: if ($num) {
9344: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
9345: ' method="post" enctype="multipart/form-data">'."\n".
9346: $state.
9347: '<h3>'.&mt('Upload embedded files').
9348: ':</h3>'.$upload_output.'<br />'."\n".
9349: '<input type ="hidden" name="number_embedded_items" value="'.
9350: $num.'" />'."\n";
9351: if ($actionurl eq '') {
9352: $output .= '<input type="hidden" name="phase" value="three" />';
9353: }
9354: } elsif ($applies) {
9355: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
9356: if ($applies > 1) {
9357: $output .=
9358: &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
9359: if ($numremref) {
9360: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
9361: }
9362: if ($numinvalid) {
9363: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
9364: }
9365: if ($numexisting) {
9366: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
9367: }
9368: $output .= '</ul><br />';
9369: } elsif ($numremref) {
9370: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
9371: } elsif ($numinvalid) {
9372: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
9373: } elsif ($numexisting) {
9374: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
9375: }
9376: $output .= $upload_output.'<br />';
9377: }
9378: my ($pathchange_output,$chgcount);
9379: $chgcount = $num;
9380: if (keys(%pathchanges) > 0) {
9381: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
9382: if ($num) {
9383: $output .= &embedded_file_element('pathchange',$chgcount,
9384: $embed_file,\%mapping,
9385: $allfiles,$codebase);
9386: } else {
9387: $pathchange_output .=
9388: &start_data_table_row().
9389: '<td><input type ="checkbox" name="namechange" value="'.
9390: $chgcount.'" checked="checked" /></td>'.
9391: '<td>'.$mapping{$embed_file}.'</td>'.
9392: '<td>'.$embed_file.
9393: &embedded_file_element('pathchange',$numpathchg,$embed_file,
9394: \%mapping,$allfiles,$codebase).
9395: '</td>'.&end_data_table_row();
9396: }
9397: $numpathchg ++;
9398: $chgcount ++;
9399: }
9400: }
9401: if ($num) {
9402: if ($numpathchg) {
9403: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
9404: $numpathchg.'" />'."\n";
9405: }
9406: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9407: ($actionurl eq '/adm/imsimport')) {
9408: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
9409: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
9410: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
9411: }
9412: $output .= '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
9413: &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
9414: } elsif ($numpathchg) {
9415: my %pathchange = ();
9416: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
9417: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9418: $output .= '<p>'.&mt('or').'</p>';
9419: }
9420: }
9421: return ($output,$num,$numpathchg);
9422: }
9423:
9424: sub embedded_file_element {
9425: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
9426: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
9427: (ref($codebase) eq 'HASH'));
9428: my $output;
9429: if ($context eq 'upload_embedded') {
9430: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
9431: }
9432: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
9433: &escape($embed_file).'" />';
9434: unless (($context eq 'upload_embedded') &&
9435: ($mapping->{$embed_file} eq $embed_file)) {
9436: $output .='
9437: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
9438: }
9439: my $attrib;
9440: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
9441: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
9442: }
9443: $output .=
9444: "\n\t\t".
9445: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
9446: $attrib.'" />';
9447: if (exists($codebase->{$mapping->{$embed_file}})) {
9448: $output .=
9449: "\n\t\t".
9450: '<input name="codebase_'.$num.'" type="hidden" value="'.
9451: &escape($codebase->{$mapping->{$embed_file}}).'" />';
9452: }
9453: return $output;
9454: }
9455:
9456: sub upload_embedded {
9457: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
9458: $current_disk_usage,$hiddenstate,$actionurl) = @_;
9459: my (%pathchange,$output,$modifyform,$footer,$returnflag);
9460: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
9461: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
9462: my $orig_uploaded_filename =
9463: $env{'form.embedded_item_'.$i.'.filename'};
9464: foreach my $type ('orig','ref','attrib','codebase') {
9465: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
9466: $env{'form.embedded_'.$type.'_'.$i} =
9467: &unescape($env{'form.embedded_'.$type.'_'.$i});
9468: }
9469: }
9470: my ($path,$fname) =
9471: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
9472: # no path, whole string is fname
9473: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
9474: $fname = &Apache::lonnet::clean_filename($fname);
9475: # See if there is anything left
9476: next if ($fname eq '');
9477:
9478: # Check if file already exists as a file or directory.
9479: my ($state,$msg);
9480: if ($context eq 'portfolio') {
9481: my $port_path = $dirpath;
9482: if ($group ne '') {
9483: $port_path = "groups/$group/$port_path";
9484: }
9485: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
9486: $fname,$group,'embedded_item_'.$i,
9487: $dir_root,$port_path,$disk_quota,
9488: $current_disk_usage,$uname,$udom);
9489: if ($state eq 'will_exceed_quota'
9490: || $state eq 'file_locked') {
9491: $output .= $msg;
9492: next;
9493: }
9494: } elsif (($context eq 'author') || ($context eq 'testbank')) {
9495: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
9496: if ($state eq 'exists') {
9497: $output .= $msg;
9498: next;
9499: }
9500: }
9501: # Check if extension is valid
9502: if (($fname =~ /\.(\w+)$/) &&
9503: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
9504: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
9505: next;
9506: } elsif (($fname =~ /\.(\w+)$/) &&
9507: (!defined(&Apache::loncommon::fileembstyle($1)))) {
9508: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
9509: next;
9510: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
9511: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
9512: next;
9513: }
9514:
9515: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
9516: if ($context eq 'portfolio') {
9517: my $result;
9518: if ($state eq 'existingfile') {
9519: $result=
9520: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
9521: $dirpath.$env{'form.currentpath'}.$path);
9522: } else {
9523: $result=
9524: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
9525: $dirpath.
9526: $env{'form.currentpath'}.$path);
9527: if ($result !~ m|^/uploaded/|) {
9528: $output .= '<span class="LC_error">'
9529: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
9530: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
9531: .'</span><br />';
9532: next;
9533: } else {
9534: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9535: $path.$fname.'</span>').'<br />';
9536: }
9537: }
9538: } elsif ($context eq 'coursedoc') {
9539: my $result =
9540: &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
9541: $dirpath.'/'.$path);
9542: if ($result !~ m|^/uploaded/|) {
9543: $output .= '<span class="LC_error">'
9544: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
9545: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
9546: .'</span><br />';
9547: next;
9548: } else {
9549: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9550: $path.$fname.'</span>').'<br />';
9551: }
9552: } else {
9553: # Save the file
9554: my $target = $env{'form.embedded_item_'.$i};
9555: my $fullpath = $dir_root.$dirpath.'/'.$path;
9556: my $dest = $fullpath.$fname;
9557: my $url = $url_root.$dirpath.'/'.$path.$fname;
9558: my @parts=split(/\//,"$dirpath/$path");
9559: my $count;
9560: my $filepath = $dir_root;
9561: foreach my $subdir (@parts) {
9562: $filepath .= "/$subdir";
9563: if (!-e $filepath) {
9564: mkdir($filepath,0770);
9565: }
9566: }
9567: my $fh;
9568: if (!open($fh,'>'.$dest)) {
9569: &Apache::lonnet::logthis('Failed to create '.$dest);
9570: $output .= '<span class="LC_error">'.
9571: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
9572: '</span><br />';
9573: } else {
9574: if (!print $fh $env{'form.embedded_item_'.$i}) {
9575: &Apache::lonnet::logthis('Failed to write to '.$dest);
9576: $output .= '<span class="LC_error">'.
9577: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
9578: '</span><br />';
9579: } else {
9580: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9581: $url.'</span>').'<br />';
9582: unless ($context eq 'testbank') {
9583: $footer .= &mt('View embedded file: [_1]',
9584: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
9585: }
9586: }
9587: close($fh);
9588: }
9589: }
9590: if ($env{'form.embedded_ref_'.$i}) {
9591: $pathchange{$i} = 1;
9592: }
9593: }
9594: if ($output) {
9595: $output = '<p>'.$output.'</p>';
9596: }
9597: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
9598: $returnflag = 'ok';
9599: if (keys(%pathchange) > 0) {
9600: if ($context eq 'portfolio') {
9601: $output .= '<p>'.&mt('or').'</p>';
9602: } elsif ($context eq 'testbank') {
9603: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
9604: $returnflag = 'modify_orightml';
9605: }
9606: }
9607: return ($output.$footer,$returnflag);
9608: }
9609:
9610: sub modify_html_form {
9611: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
9612: my $end = 0;
9613: my $modifyform;
9614: if ($context eq 'upload_embedded') {
9615: return unless (ref($pathchange) eq 'HASH');
9616: if ($env{'form.number_embedded_items'}) {
9617: $end += $env{'form.number_embedded_items'};
9618: }
9619: if ($env{'form.number_pathchange_items'}) {
9620: $end += $env{'form.number_pathchange_items'};
9621: }
9622: if ($end) {
9623: for (my $i=0; $i<$end; $i++) {
9624: if ($i < $env{'form.number_embedded_items'}) {
9625: next unless($pathchange->{$i});
9626: }
9627: $modifyform .=
9628: &start_data_table_row().
9629: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
9630: 'checked="checked" /></td>'.
9631: '<td>'.$env{'form.embedded_ref_'.$i}.
9632: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
9633: &escape($env{'form.embedded_ref_'.$i}).'" />'.
9634: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
9635: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
9636: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
9637: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
9638: '<td>'.$env{'form.embedded_orig_'.$i}.
9639: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
9640: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
9641: &end_data_table_row();
9642: }
9643: }
9644: } else {
9645: $modifyform = $pathchgtable;
9646: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9647: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
9648: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9649: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
9650: }
9651: }
9652: if ($modifyform) {
9653: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
9654: '<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".
9655: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
9656: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
9657: '</ol></p>'."\n".'<p>'.
9658: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
9659: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
9660: &start_data_table()."\n".
9661: &start_data_table_header_row().
9662: '<th>'.&mt('Change?').'</th>'.
9663: '<th>'.&mt('Current reference').'</th>'.
9664: '<th>'.&mt('Required reference').'</th>'.
9665: &end_data_table_header_row()."\n".
9666: $modifyform.
9667: &end_data_table().'<br />'."\n".$hiddenstate.
9668: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
9669: '</form>'."\n";
9670: }
9671: return;
9672: }
9673:
9674: sub modify_html_refs {
9675: my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
9676: my $container;
9677: if ($context eq 'portfolio') {
9678: $container = $env{'form.container'};
9679: } elsif ($context eq 'coursedoc') {
9680: $container = $env{'form.primaryurl'};
9681: } else {
9682: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
9683: }
9684: my (%allfiles,%codebase,$output,$content);
9685: my @changes = &get_env_multiple('form.namechange');
9686: return unless (@changes > 0);
9687: if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
9688: return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
9689: $content = &Apache::lonnet::getfile($container);
9690: return if ($content eq '-1');
9691: } else {
9692: return unless ($container =~ /^\Q$dir_root\E/);
9693: if (open(my $fh,"<$container")) {
9694: $content = join('', <$fh>);
9695: close($fh);
9696: } else {
9697: return;
9698: }
9699: }
9700: my ($count,$codebasecount) = (0,0);
9701: my $mm = new File::MMagic;
9702: my $mime_type = $mm->checktype_contents($content);
9703: if ($mime_type eq 'text/html') {
9704: my $parse_result =
9705: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
9706: \%codebase,\$content);
9707: if ($parse_result eq 'ok') {
9708: foreach my $i (@changes) {
9709: my $orig = &unescape($env{'form.embedded_orig_'.$i});
9710: my $ref = &unescape($env{'form.embedded_ref_'.$i});
9711: if ($allfiles{$ref}) {
9712: my $newname = $orig;
9713: my ($attrib_regexp,$codebase);
9714: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
9715: if ($attrib_regexp =~ /:/) {
9716: $attrib_regexp =~ s/\:/|/g;
9717: }
9718: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
9719: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
9720: $count += $numchg;
9721: }
9722: if ($env{'form.embedded_codebase_'.$i} ne '') {
9723: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
9724: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
9725: $codebasecount ++;
9726: }
9727: }
9728: }
9729: if ($count || $codebasecount) {
9730: my $saveresult;
9731: if ($context eq 'portfolio' || $context eq 'coursedoc') {
9732: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
9733: if ($url eq $container) {
9734: my ($fname) = ($container =~ m{/([^/]+)$});
9735: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9736: $count,'<span class="LC_filename">'.
9737: $fname.'</span>').'</p>';
9738: } else {
9739: $output = '<p class="LC_error">'.
9740: &mt('Error: update failed for: [_1].',
9741: '<span class="LC_filename">'.
9742: $container.'</span>').'</p>';
9743: }
9744: } else {
9745: if (open(my $fh,">$container")) {
9746: print $fh $content;
9747: close($fh);
9748: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9749: $count,'<span class="LC_filename">'.
9750: $container.'</span>').'</p>';
9751: } else {
9752: $output = '<p class="LC_error">'.
9753: &mt('Error: could not update [_1].',
9754: '<span class="LC_filename">'.
9755: $container.'</span>').'</p>';
9756: }
9757: }
9758: }
9759: } else {
9760: &logthis('Failed to parse '.$container.
9761: ' to modify references: '.$parse_result);
9762: }
9763: }
9764: return $output;
9765: }
9766:
9767: sub check_for_existing {
9768: my ($path,$fname,$element) = @_;
9769: my ($state,$msg);
9770: if (-d $path.'/'.$fname) {
9771: $state = 'exists';
9772: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9773: } elsif (-e $path.'/'.$fname) {
9774: $state = 'exists';
9775: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9776: }
9777: if ($state eq 'exists') {
9778: $msg = '<span class="LC_error">'.$msg.'</span><br />';
9779: }
9780: return ($state,$msg);
9781: }
9782:
9783: sub check_for_upload {
9784: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
9785: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
9786: my $filesize = length($env{'form.'.$element});
9787: if (!$filesize) {
9788: my $msg = '<span class="LC_error">'.
9789: &mt('Unable to upload [_1]. (size = [_2] bytes)',
9790: '<span class="LC_filename">'.$fname.'</span>',
9791: $filesize).'<br />'.
9792: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
9793: '</span>';
9794: return ('zero_bytes',$msg);
9795: }
9796: $filesize = $filesize/1000; #express in k (1024?)
9797: my $getpropath = 1;
9798: my ($dirlistref,$listerror) =
9799: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
9800: my $found_file = 0;
9801: my $locked_file = 0;
9802: my @lockers;
9803: my $navmap;
9804: if ($env{'request.course.id'}) {
9805: $navmap = Apache::lonnavmaps::navmap->new();
9806: }
9807: if (ref($dirlistref) eq 'ARRAY') {
9808: foreach my $line (@{$dirlistref}) {
9809: my ($file_name,$rest)=split(/\&/,$line,2);
9810: if ($file_name eq $fname){
9811: $file_name = $path.$file_name;
9812: if ($group ne '') {
9813: $file_name = $group.$file_name;
9814: }
9815: $found_file = 1;
9816: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
9817: foreach my $lock (@lockers) {
9818: if (ref($lock) eq 'ARRAY') {
9819: my ($symb,$crsid) = @{$lock};
9820: if ($crsid eq $env{'request.course.id'}) {
9821: if (ref($navmap)) {
9822: my $res = $navmap->getBySymb($symb);
9823: foreach my $part (@{$res->parts()}) {
9824: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
9825: unless (($slot_status == $res->RESERVED) ||
9826: ($slot_status == $res->RESERVED_LOCATION)) {
9827: $locked_file = 1;
9828: }
9829: }
9830: } else {
9831: $locked_file = 1;
9832: }
9833: } else {
9834: $locked_file = 1;
9835: }
9836: }
9837: }
9838: } else {
9839: my @info = split(/\&/,$rest);
9840: my $currsize = $info[6]/1000;
9841: if ($currsize < $filesize) {
9842: my $extra = $filesize - $currsize;
9843: if (($current_disk_usage + $extra) > $disk_quota) {
9844: my $msg = '<span class="LC_error">'.
9845: &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.',
9846: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
9847: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9848: $disk_quota,$current_disk_usage);
9849: return ('will_exceed_quota',$msg);
9850: }
9851: }
9852: }
9853: }
9854: }
9855: }
9856: if (($current_disk_usage + $filesize) > $disk_quota){
9857: my $msg = '<span class="LC_error">'.
9858: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
9859: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
9860: return ('will_exceed_quota',$msg);
9861: } elsif ($found_file) {
9862: if ($locked_file) {
9863: my $msg = '<span class="LC_error">';
9864: $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>');
9865: $msg .= '</span><br />';
9866: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
9867: return ('file_locked',$msg);
9868: } else {
9869: my $msg = '<span class="LC_error">';
9870: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
9871: $msg .= '</span>';
9872: return ('existingfile',$msg);
9873: }
9874: }
9875: }
9876:
9877: sub check_for_traversal {
9878: my ($path,$url,$toplevel) = @_;
9879: my @parts=split(/\//,$path);
9880: my $cleanpath;
9881: my $fullpath = $url;
9882: for (my $i=0;$i<@parts;$i++) {
9883: next if ($parts[$i] eq '.');
9884: if ($parts[$i] eq '..') {
9885: $fullpath =~ s{([^/]+/)$}{};
9886: } else {
9887: $fullpath .= $parts[$i].'/';
9888: }
9889: }
9890: if ($fullpath =~ /^\Q$url\E(.*)$/) {
9891: $cleanpath = $1;
9892: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
9893: my $curr_toprel = $1;
9894: my @parts = split(/\//,$curr_toprel);
9895: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
9896: my @urlparts = split(/\//,$url_toprel);
9897: my $doubledots;
9898: my $startdiff = -1;
9899: for (my $i=0; $i<@urlparts; $i++) {
9900: if ($startdiff == -1) {
9901: unless ($urlparts[$i] eq $parts[$i]) {
9902: $startdiff = $i;
9903: $doubledots .= '../';
9904: }
9905: } else {
9906: $doubledots .= '../';
9907: }
9908: }
9909: if ($startdiff > -1) {
9910: $cleanpath = $doubledots;
9911: for (my $i=$startdiff; $i<@parts; $i++) {
9912: $cleanpath .= $parts[$i].'/';
9913: }
9914: }
9915: }
9916: $cleanpath =~ s{(/)$}{};
9917: return $cleanpath;
9918: }
9919:
9920: sub is_archive_file {
9921: my ($mimetype) = @_;
9922: if (($mimetype eq 'application/octet-stream') ||
9923: ($mimetype eq 'application/x-stuffit') ||
9924: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
9925: return 1;
9926: }
9927: return;
9928: }
9929:
9930: sub decompress_form {
9931: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
9932: my %lt = &Apache::lonlocal::texthash (
9933: this => 'This file is an archive file.',
9934: itsc => 'Its contents are as follows:',
9935: youm => 'You may wish to extract its contents.',
9936: camt => 'Extraction of contents is recommended for Camtasia zip files.',
9937: extr => 'Extract contents',
9938: yes => 'Yes',
9939: no => 'No',
9940: );
9941: my $output = '<p>'.$lt{'this'};
9942: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
9943: my (%toplevel,@paths);
9944: my $info = &list_archive_contents($fileloc,\@paths);
9945: if (@paths) {
9946: foreach my $path (@paths) {
9947: $path =~ s{^/}{};
9948: if ($path =~ m{^([^/]+)/}) {
9949: $toplevel{$1} = $path;
9950: } else {
9951: $toplevel{$path} = $path;
9952: }
9953: }
9954: }
9955: if ($info eq '') {
9956: $output .= ' '.$lt{'youm'}.'</p>'."\n";
9957: } else {
9958: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
9959: '<div><pre>'.$info.'</pre></div>';
9960: }
9961: my $duplicates;
9962: my $num = 0;
9963: if (ref($dirlist) eq 'ARRAY') {
9964: foreach my $item (@{$dirlist}) {
9965: if (ref($item) eq 'ARRAY') {
9966: if (exists($toplevel{$item->[0]})) {
9967: $duplicates .=
9968: &start_data_table_row().
9969: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
9970: 'value="0" checked="checked" />'.&mt('No').'</label>'.
9971: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
9972: 'value="1" />'.&mt('Yes').'</label>'.
9973: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
9974: '<td>'.$item->[0].'</td>';
9975: if ($item->[2]) {
9976: $duplicates .= '<td>'.&mt('Directory').'</td>';
9977: } else {
9978: $duplicates .= '<td>'.&mt('File').'</td>';
9979: }
9980: $duplicates .= '<td>'.$item->[3].'</td>'.
9981: '<td>'.
9982: &Apache::lonlocal::locallocaltime($item->[4]).
9983: '</td>'.
9984: &end_data_table_row();
9985: $num ++;
9986: }
9987: }
9988: }
9989: }
9990: my $itemcount;
9991: if (@paths > 0) {
9992: $itemcount = scalar(@paths);
9993: } else {
9994: $itemcount = 1;
9995: }
9996: $output .=
9997: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
9998: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'."\n";
9999: if ($duplicates ne '') {
10000: $output .= '<p><span class="LC_warning">'.
10001: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
10002: &start_data_table().
10003: &start_data_table_header_row().
10004: '<th>'.&mt('Overwrite?').'</th>'.
10005: '<th>'.&mt('Name').'</th>'.
10006: '<th>'.&mt('Type').'</th>'.
10007: '<th>'.&mt('Size').'</th>'.
10008: '<th>'.&mt('Last modified').'</th>'.
10009: &end_data_table_header_row().
10010: $duplicates.
10011: &end_data_table().
10012: '</p>';
10013: }
10014: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10015: $output .= '<p>'.$lt{'camt'}.'</p>';
10016: }
10017: $output .= <<"START";
10018: <div id="uploadfileresult">
10019: <form name="uploaded_decompress" action="$action" method="post">
10020: <input type="hidden" name="archiveurl" value="$archiveurl" />
10021: START
10022: if (ref($hiddenelements) eq 'HASH') {
10023: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10024: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10025: }
10026: }
10027: $output .= <<"END";
10028: <input type="submit" name="decompress" value="$lt{'extr'}" />
10029: </form>
10030: $noextract
10031: </div>
10032: END
10033: return $output;
10034: }
10035:
10036: sub decompression_utility {
10037: my ($program) = @_;
10038: my @utilities = ('tar','gunzip','bunzip2','unzip');
10039: my $location;
10040: if (grep(/^\Q$program\E$/,@utilities)) {
10041: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10042: '/usr/sbin/') {
10043: if (-x $dir.$program) {
10044: $location = $dir.$program;
10045: last;
10046: }
10047: }
10048: }
10049: return $location;
10050: }
10051:
10052: sub list_archive_contents {
10053: my ($file,$pathsref) = @_;
10054: my (@cmd,$output);
10055: my $needsregexp;
10056: if ($file =~ /\.zip$/) {
10057: @cmd = (&decompression_utility('unzip'),"-l");
10058: $needsregexp = 1;
10059: } elsif (($file =~ m/\.tar\.gz$/) ||
10060: ($file =~ /\.tgz$/)) {
10061: @cmd = (&decompression_utility('tar'),"-ztf");
10062: } elsif ($file =~ /\.tar\.bz2$/) {
10063: @cmd = (&decompression_utility('tar'),"-jtf");
10064: } elsif ($file =~ m|\.tar$|) {
10065: @cmd = (&decompression_utility('tar'),"-tf");
10066: }
10067: if (@cmd) {
10068: undef($!);
10069: undef($@);
10070: if (open(my $fh,"-|", @cmd, $file)) {
10071: while (my $line = <$fh>) {
10072: $output .= $line;
10073: chomp($line);
10074: my $item;
10075: if ($needsregexp) {
10076: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
10077: } else {
10078: $item = $line;
10079: }
10080: if ($item ne '') {
10081: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10082: push(@{$pathsref},$item);
10083: }
10084: }
10085: }
10086: close($fh);
10087: }
10088: }
10089: return $output;
10090: }
10091:
10092: sub decompress_uploaded_file {
10093: my ($file,$dir) = @_;
10094: &Apache::lonnet::appenv({'cgi.file' => $file});
10095: &Apache::lonnet::appenv({'cgi.dir' => $dir});
10096: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10097: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10098: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10099: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10100: my $decompressed = $env{'cgi.decompressed'};
10101: &Apache::lonnet::delenv('cgi.file');
10102: &Apache::lonnet::delenv('cgi.dir');
10103: &Apache::lonnet::delenv('cgi.decompressed');
10104: return ($decompressed,$result);
10105: }
10106:
10107: sub process_decompression {
10108: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10109: my ($dir,$error,$warning,$output);
10110: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10111: $error = &mt('File name not a supported archive file type.').
10112: '<br />'.&mt('File name should end with one of: [_1].',
10113: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10114: } else {
10115: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10116: if ($docuhome eq 'no_host') {
10117: $error = &mt('Could not determine home server for course.');
10118: } else {
10119: my @ids=&Apache::lonnet::current_machine_ids();
10120: my $currdir = "$dir_root/$destination";
10121: if (grep(/^\Q$docuhome\E$/,@ids)) {
10122: $dir = &LONCAPA::propath($docudom,$docuname).
10123: "$dir_root/$destination";
10124: } else {
10125: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10126: "$dir_root/$docudom/$docuname/$destination";
10127: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10128: $error = &mt('Archive file not found.');
10129: }
10130: }
10131: my (@to_overwrite,@to_skip);
10132: if ($env{'form.archive_overwrite_total'} > 0) {
10133: my $total = $env{'form.archive_overwrite_total'};
10134: for (my $i=0; $i<$total; $i++) {
10135: if ($env{'form.archive_overwrite_'.$i} == 1) {
10136: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10137: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10138: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10139: }
10140: }
10141: }
10142: my $numskip = scalar(@to_skip);
10143: if (($numskip > 0) &&
10144: ($numskip == $env{'form.archive_itemcount'})) {
10145: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
10146: } elsif ($dir eq '') {
10147: $error = &mt('Directory containing archive file unavailable.');
10148: } elsif (!$error) {
10149: my ($decompressed,$display);
10150: if ($numskip > 0) {
10151: my $tempdir = time.'_'.$$.int(rand(10000));
10152: mkdir("$dir/$tempdir",0755);
10153: system("mv $dir/$file $dir/$tempdir/$file");
10154: ($decompressed,$display) =
10155: &decompress_uploaded_file($file,"$dir/$tempdir");
10156: foreach my $item (@to_skip) {
10157: if (($item ne '') && ($item !~ /\.\./)) {
10158: if (-f "$dir/$tempdir/$item") {
10159: unlink("$dir/$tempdir/$item");
10160: } elsif (-d "$dir/$tempdir/$item") {
10161: system("rm -rf $dir/$tempdir/$item");
10162: }
10163: }
10164: }
10165: system("mv $dir/$tempdir/* $dir");
10166: rmdir("$dir/$tempdir");
10167: } else {
10168: ($decompressed,$display) =
10169: &decompress_uploaded_file($file,$dir);
10170: }
10171: if ($decompressed eq 'ok') {
10172: $output = '<p class="LC_info">'.
10173: &mt('Files extracted successfully from archive.').
10174: '</p>'."\n";
10175: my ($warning,$result,@contents);
10176: my ($newdirlistref,$newlisterror) =
10177: &Apache::lonnet::dirlist($currdir,$docudom,
10178: $docuname,1);
10179: my (%is_dir,%changes,@newitems);
10180: my $dirptr = 16384;
10181: if (ref($newdirlistref) eq 'ARRAY') {
10182: foreach my $dir_line (@{$newdirlistref}) {
10183: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10184: unless (($item =~ /^\.+$/) || ($item eq $file) ||
10185: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10186: push(@newitems,$item);
10187: if ($dirptr&$testdir) {
10188: $is_dir{$item} = 1;
10189: }
10190: $changes{$item} = 1;
10191: }
10192: }
10193: }
10194: if (keys(%changes) > 0) {
10195: foreach my $item (sort(@newitems)) {
10196: if ($changes{$item}) {
10197: push(@contents,$item);
10198: }
10199: }
10200: }
10201: if (@contents > 0) {
10202: my (%children,%parent,%dirorder,%titles);
10203: my $wantform = 1;
10204: my ($count,$datatable) = &get_extracted($docudom,$docuname,
10205: $currdir,\%is_dir,
10206: \%children,\%parent,
10207: \@contents,\%dirorder,
10208: \%titles,$wantform);
10209: if ($datatable ne '') {
10210: $output .= &archive_options_form('decompressed',$datatable,
10211: $count,$hiddenelem);
10212: my $startcount = 6;
10213: $output .= &archive_javascript($startcount,$count,
10214: \%titles,\%children);
10215: }
10216: } else {
10217: $warning = &mt('No new items extracted from archive file.');
10218: }
10219: } else {
10220: $output = $display;
10221: $error = &mt('An error occurred during extraction from the archive file.');
10222: }
10223: }
10224: }
10225: }
10226: if ($error) {
10227: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10228: $error.'</p>'."\n";
10229: }
10230: if ($warning) {
10231: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10232: }
10233: return $output;
10234: }
10235:
10236: sub get_extracted {
10237: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10238: $titles,$wantform) = @_;
10239: my $count = 0;
10240: my $depth = 0;
10241: my $datatable;
10242: my @hierarchy;
10243: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10244: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10245: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10246: foreach my $item (@{$contents}) {
10247: $count ++;
10248: @{$dirorder->{$count}} = @hierarchy;
10249: $titles->{$count} = $item;
10250: &archive_hierarchy($depth,$count,$parent,$children);
10251: if ($wantform) {
10252: $datatable .= &archive_row($is_dir->{$item},$item,
10253: $currdir,$depth,$count);
10254: }
10255: if ($is_dir->{$item}) {
10256: $depth ++;
10257: push(@hierarchy,$count);
10258: $parent->{$depth} = $count;
10259: $datatable .=
10260: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10261: \$depth,\$count,\@hierarchy,$dirorder,
10262: $children,$parent,$titles,$wantform);
10263: $depth --;
10264: pop(@hierarchy);
10265: }
10266: }
10267: return ($count,$datatable);
10268: }
10269:
10270: sub recurse_extracted_archive {
10271: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10272: $children,$parent,$titles,$wantform) = @_;
10273: my $result='';
10274: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
10275: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
10276: (ref($dirorder) eq 'HASH')) {
10277: return $result;
10278: }
10279: my $dirptr = 16384;
10280: my ($newdirlistref,$newlisterror) =
10281: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
10282: if (ref($newdirlistref) eq 'ARRAY') {
10283: foreach my $dir_line (@{$newdirlistref}) {
10284: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10285: unless ($item =~ /^\.+$/) {
10286: $$count ++;
10287: @{$dirorder->{$$count}} = @{$hierarchy};
10288: $titles->{$$count} = $item;
10289: &archive_hierarchy($$depth,$$count,$parent,$children);
10290:
10291: my $is_dir;
10292: if ($dirptr&$testdir) {
10293: $is_dir = 1;
10294: }
10295: if ($wantform) {
10296: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
10297: }
10298: if ($is_dir) {
10299: $$depth ++;
10300: push(@{$hierarchy},$$count);
10301: $parent->{$$depth} = $$count;
10302: $result .=
10303: &recurse_extracted_archive("$currdir/$item",$docudom,
10304: $docuname,$depth,$count,
10305: $hierarchy,$dirorder,$children,
10306: $parent,$titles,$wantform);
10307: $$depth --;
10308: pop(@{$hierarchy});
10309: }
10310: }
10311: }
10312: }
10313: return $result;
10314: }
10315:
10316: sub archive_hierarchy {
10317: my ($depth,$count,$parent,$children) =@_;
10318: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
10319: if (exists($parent->{$depth})) {
10320: $children->{$parent->{$depth}} .= $count.':';
10321: }
10322: }
10323: return;
10324: }
10325:
10326: sub archive_row {
10327: my ($is_dir,$item,$currdir,$depth,$count) = @_;
10328: my ($name) = ($item =~ m{([^/]+)$});
10329: my %choices = &Apache::lonlocal::texthash (
10330: 'display' => 'Add as file',
10331: 'dependency' => 'Include as dependency',
10332: 'discard' => 'Discard',
10333: );
10334: if ($is_dir) {
10335: $choices{'display'} = &mt('Add as folder');
10336: }
10337: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
10338: my $offset = 0;
10339: foreach my $action ('display','dependency','discard') {
10340: $offset ++;
10341: if ($action ne 'display') {
10342: $offset ++;
10343: }
10344: $output .= '<td><span class="LC_nobreak">'.
10345: '<label><input type="radio" name="archive_'.$count.
10346: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
10347: my $text = $choices{$action};
10348: if ($is_dir) {
10349: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
10350: if ($action eq 'display') {
10351: $text = &mt('Add as folder');
10352: }
10353: } else {
10354: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
10355:
10356: }
10357: $output .= ' /> '.$choices{$action}.'</label></span>';
10358: if ($action eq 'dependency') {
10359: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
10360: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
10361: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
10362: '<option value=""></option>'."\n".
10363: '</select>'."\n".
10364: '</div>';
10365: } elsif ($action eq 'display') {
10366: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
10367: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
10368: '</div>';
10369: }
10370: $output .= '</td>';
10371: }
10372: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
10373: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
10374: for (my $i=0; $i<$depth; $i++) {
10375: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
10376: }
10377: if ($is_dir) {
10378: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
10379: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
10380: } else {
10381: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
10382: }
10383: $output .= ' '.$name.'</td>'."\n".
10384: &end_data_table_row();
10385: return $output;
10386: }
10387:
10388: sub archive_options_form {
10389: my ($form,$display,$count,$hiddenelem) = @_;
10390: my %lt = &Apache::lonlocal::texthash(
10391: perm => 'Permanently remove archive file?',
10392: hows => 'How should each extracted item be incorporated in the course?',
10393: cont => 'Content actions for all',
10394: addf => 'Add as folder/file',
10395: incd => 'Include as dependency for a displayed file',
10396: disc => 'Discard',
10397: no => 'No',
10398: yes => 'Yes',
10399: save => 'Save',
10400: );
10401: my $output = <<"END";
10402: <form name="$form" method="post" action="">
10403: <p><span class="LC_nobreak">$lt{'perm'}
10404: <label>
10405: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
10406: </label>
10407:
10408: <label>
10409: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
10410: </span>
10411: </p>
10412: <input type="hidden" name="phase" value="decompress_cleanup" />
10413: <br />$lt{'hows'}
10414: <div class="LC_columnSection">
10415: <fieldset>
10416: <legend>$lt{'cont'}</legend>
10417: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
10418: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
10419: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
10420: </fieldset>
10421: </div>
10422: END
10423: return $output.
10424: &start_data_table()."\n".
10425: $display."\n".
10426: &end_data_table()."\n".
10427: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
10428: $hiddenelem.
10429: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
10430: '</form>';
10431: }
10432:
10433: sub archive_javascript {
10434: my ($startcount,$numitems,$titles,$children) = @_;
10435: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
10436: my $maintitle = $env{'form.comment'};
10437: my $scripttag = <<START;
10438: <script type="text/javascript">
10439: // <![CDATA[
10440:
10441: function checkAll(form,prefix) {
10442: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
10443: for (var i=0; i < form.elements.length; i++) {
10444: var id = form.elements[i].id;
10445: if ((id != '') && (id != undefined)) {
10446: if (idstr.test(id)) {
10447: if (form.elements[i].type == 'radio') {
10448: form.elements[i].checked = true;
10449: var nostart = i-$startcount;
10450: var offset = nostart%7;
10451: var count = (nostart-offset)/7;
10452: dependencyCheck(form,count,offset);
10453: }
10454: }
10455: }
10456: }
10457: }
10458:
10459: function propagateCheck(form,count) {
10460: if (count > 0) {
10461: var startelement = $startcount + ((count-1) * 7);
10462: for (var j=1; j<6; j++) {
10463: if ((j != 2) && (j != 4)) {
10464: var item = startelement + j;
10465: if (form.elements[item].type == 'radio') {
10466: if (form.elements[item].checked) {
10467: containerCheck(form,count,j);
10468: break;
10469: }
10470: }
10471: }
10472: }
10473: }
10474: }
10475:
10476: numitems = $numitems
10477: var titles = new Array(numitems);
10478: var parents = new Array(numitems);
10479: for (var i=0; i<numitems; i++) {
10480: parents[i] = new Array;
10481: }
10482: var maintitle = '$maintitle';
10483:
10484: START
10485:
10486: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
10487: my @contents = split(/:/,$children->{$container});
10488: for (my $i=0; $i<@contents; $i ++) {
10489: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
10490: }
10491: }
10492:
10493: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
10494: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
10495: }
10496:
10497: $scripttag .= <<END;
10498:
10499: function containerCheck(form,count,offset) {
10500: if (count > 0) {
10501: dependencyCheck(form,count,offset);
10502: var item = (offset+$startcount)+7*(count-1);
10503: form.elements[item].checked = true;
10504: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
10505: if (parents[count].length > 0) {
10506: for (var j=0; j<parents[count].length; j++) {
10507: containerCheck(form,parents[count][j],offset);
10508: }
10509: }
10510: }
10511: }
10512: }
10513:
10514: function dependencyCheck(form,count,offset) {
10515: if (count > 0) {
10516: var chosen = (offset+$startcount)+7*(count-1);
10517: var depitem = $startcount + ((count-1) * 7) + 4;
10518: var currtype = form.elements[depitem].type;
10519: if (form.elements[chosen].value == 'dependency') {
10520: document.getElementById('arc_depon_'+count).style.display='block';
10521: form.elements[depitem].options.length = 0;
10522: form.elements[depitem].options[0] = new Option('Select','',true,true);
10523: for (var i=1; i<count; i++) {
10524: var startelement = $startcount + (i-1) * 7;
10525: for (var j=1; j<6; j++) {
10526: if ((j != 2) && (j!= 4)) {
10527: var item = startelement + j;
10528: if (form.elements[item].type == 'radio') {
10529: if (form.elements[item].checked) {
10530: if (form.elements[item].value == 'display') {
10531: var n = form.elements[depitem].options.length;
10532: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
10533: }
10534: }
10535: }
10536: }
10537: }
10538: }
10539: } else {
10540: document.getElementById('arc_depon_'+count).style.display='none';
10541: form.elements[depitem].options.length = 0;
10542: form.elements[depitem].options[0] = new Option('Select','',true,true);
10543: }
10544: titleCheck(form,count,offset);
10545: }
10546: }
10547:
10548: function propagateSelect(form,count,offset) {
10549: if (count > 0) {
10550: var item = (1+offset+$startcount)+7*(count-1);
10551: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
10552: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10553: if (parents[count].length > 0) {
10554: for (var j=0; j<parents[count].length; j++) {
10555: containerSelect(form,parents[count][j],offset,picked);
10556: }
10557: }
10558: }
10559: }
10560: }
10561:
10562: function containerSelect(form,count,offset,picked) {
10563: if (count > 0) {
10564: var item = (offset+$startcount)+7*(count-1);
10565: if (form.elements[item].type == 'radio') {
10566: if (form.elements[item].value == 'dependency') {
10567: if (form.elements[item+1].type == 'select-one') {
10568: for (var i=0; i<form.elements[item+1].options.length; i++) {
10569: if (form.elements[item+1].options[i].value == picked) {
10570: form.elements[item+1].selectedIndex = i;
10571: break;
10572: }
10573: }
10574: }
10575: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10576: if (parents[count].length > 0) {
10577: for (var j=0; j<parents[count].length; j++) {
10578: containerSelect(form,parents[count][j],offset,picked);
10579: }
10580: }
10581: }
10582: }
10583: }
10584: }
10585: }
10586:
10587: function titleCheck(form,count,offset) {
10588: if (count > 0) {
10589: var chosen = (offset+$startcount)+7*(count-1);
10590: var depitem = $startcount + ((count-1) * 7) + 2;
10591: var currtype = form.elements[depitem].type;
10592: if (form.elements[chosen].value == 'display') {
10593: document.getElementById('arc_title_'+count).style.display='block';
10594: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
10595: document.getElementById('archive_title_'+count).value=maintitle;
10596: }
10597: } else {
10598: document.getElementById('arc_title_'+count).style.display='none';
10599: if (currtype == 'text') {
10600: document.getElementById('archive_title_'+count).value='';
10601: }
10602: }
10603: }
10604: return;
10605: }
10606:
10607: // ]]>
10608: </script>
10609: END
10610: return $scripttag;
10611: }
10612:
10613: sub process_extracted_files {
10614: my ($context,$docudom,$docuname,$url,$destination,$dir_root,$hiddenelem) = @_;
10615: my $numitems = $env{'form.archive_count'};
10616: return unless ($numitems);
10617: my @ids=&Apache::lonnet::current_machine_ids();
10618: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
10619: %folders,%containers,%mapinner);
10620: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10621: if (grep(/^\Q$docuhome\E$/,@ids)) {
10622: $prefix = &LONCAPA::propath($docudom,$docuname);
10623: $pathtocheck = "$dir_root/$destination";
10624: $dir = $dir_root;
10625: $ishome = 1;
10626: } else {
10627: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
10628: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
10629: $dir = "$dir_root/$docudom/$docuname";
10630: }
10631: my $currdir = "$dir_root/$destination";
10632: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
10633: if ($env{'form.folderpath'}) {
10634: my @items = split('&',$env{'form.folderpath'});
10635: $folders{'0'} = $items[-2];
10636: $containers{'0'}='sequence';
10637: } elsif ($env{'form.pagepath'}) {
10638: my @items = split('&',$env{'form.pagepath'});
10639: $folders{'0'} = $items[-2];
10640: $containers{'0'}='page';
10641: }
10642: my @archdirs = &get_env_multiple('form.archive_directory');
10643: if ($numitems) {
10644: for (my $i=1; $i<=$numitems; $i++) {
10645: my $path = $env{'form.archive_content_'.$i};
10646: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
10647: my $item = $1;
10648: $toplevelitems{$item} = $i;
10649: if (grep(/^\Q$i\E$/,@archdirs)) {
10650: $is_dir{$item} = 1;
10651: }
10652: }
10653: }
10654: }
10655: my ($output,%children,%parent,%titles,%dirorder);
10656: if (keys(%toplevelitems) > 0) {
10657: my @contents = sort(keys(%toplevelitems));
10658: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
10659: \%parent,\@contents,\%dirorder,\%titles);
10660: }
10661: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
10662: if ($numitems) {
10663: for (my $i=1; $i<=$numitems; $i++) {
10664: my $path = $env{'form.archive_content_'.$i};
10665: if ($path =~ /^\Q$pathtocheck\E/) {
10666: if ($env{'form.archive_'.$i} eq 'discard') {
10667: if ($prefix ne '' && $path ne '') {
10668: if (-e $prefix.$path) {
10669: if ((@archdirs > 0) &&
10670: (grep(/^\Q$i\E$/,@archdirs))) {
10671: $todeletedir{$prefix.$path} = 1;
10672: } else {
10673: $todelete{$prefix.$path} = 1;
10674: }
10675: }
10676: }
10677: } elsif ($env{'form.archive_'.$i} eq 'display') {
10678: my ($docstitle,$title,$url,$outer);
10679: ($title) = ($path =~ m{/([^/]+)$});
10680: $docstitle = $env{'form.archive_title_'.$i};
10681: if ($docstitle eq '') {
10682: $docstitle = $title;
10683: }
10684: $outer = 0;
10685: if (ref($dirorder{$i}) eq 'ARRAY') {
10686: if (@{$dirorder{$i}} > 0) {
10687: foreach my $item (reverse(@{$dirorder{$i}})) {
10688: if ($env{'form.archive_'.$item} eq 'display') {
10689: $outer = $item;
10690: last;
10691: }
10692: }
10693: }
10694: }
10695: my ($errtext,$fatal) =
10696: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
10697: '/'.$folders{$outer}.'.'.
10698: $containers{$outer});
10699: next if ($fatal);
10700: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
10701: if ($context eq 'coursedocs') {
10702: $mapinner{$i} = time;
10703: $folders{$i} = 'default_'.$mapinner{$i};
10704: $containers{$i} = 'sequence';
10705: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
10706: $folders{$i}.'.'.$containers{$i};
10707: my $newidx = &LONCAPA::map::getresidx();
10708: $LONCAPA::map::resources[$newidx]=
10709: $docstitle.':'.$url.':false:normal:res';
10710: push(@LONCAPA::map::order,$newidx);
10711: my ($outtext,$errtext) =
10712: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
10713: $docuname.'/'.$folders{$outer}.
10714: '.'.$containers{$outer},1);
10715: $newseqid{$i} = $newidx;
10716: }
10717: } else {
10718: if ($context eq 'coursedocs') {
10719: my $newidx=&LONCAPA::map::getresidx();
10720: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
10721: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
10722: $title;
10723: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
10724: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
10725: }
10726: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
10727: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
10728: }
10729: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
10730: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
10731: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
10732: }
10733: $LONCAPA::map::resources[$newidx]=
10734: $docstitle.':'.$url.':false:normal:res';
10735: push(@LONCAPA::map::order, $newidx);
10736: my ($outtext,$errtext)=
10737: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
10738: $docuname.'/'.$folders{$outer}.
10739: '.'.$containers{$outer},1);
10740: }
10741: }
10742: } elsif ($env{'form.archive_'.$i} eq 'dependency') {
10743: my ($title) = ($path =~ m{/([^/]+)$});
10744: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
10745: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
10746: if (ref($dirorder{$i}) eq 'ARRAY') {
10747: my ($itemidx,$fullpath);
10748: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
10749: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
10750: my $container = $dirorder{$referrer{$i}}->[-1];
10751: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
10752: if ($dirorder{$i}->[$j] eq $container) {
10753: $itemidx = $j;
10754: }
10755: }
10756: }
10757: }
10758: if ($itemidx ne '') {
10759: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
10760: if ($mapinner{$referrer{$i}}) {
10761: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
10762: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
10763: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
10764: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
10765: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
10766: if (!-e $fullpath) {
10767: mkdir($fullpath,0755);
10768: }
10769: }
10770: } else {
10771: last;
10772: }
10773: }
10774: }
10775: } elsif ($newdest{$referrer{$i}}) {
10776: $fullpath = $newdest{$referrer{$i}};
10777: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
10778: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
10779: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
10780: last;
10781: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
10782: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
10783: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
10784: if (!-e $fullpath) {
10785: mkdir($fullpath,0755);
10786: }
10787: }
10788: } else {
10789: last;
10790: }
10791: }
10792: }
10793: if ($fullpath ne '') {
10794: system("mv $prefix$path $fullpath/$title");
10795: }
10796: }
10797: }
10798: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
10799: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
10800: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
10801: }
10802: }
10803: } else {
10804: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
10805: }
10806: }
10807: if (keys(%todelete)) {
10808: foreach my $key (keys(%todelete)) {
10809: unlink($key);
10810: }
10811: }
10812: if (keys(%todeletedir)) {
10813: foreach my $key (keys(%todeletedir)) {
10814: rmdir($key);
10815: }
10816: }
10817: foreach my $dir (sort(keys(%is_dir))) {
10818: if (($pathtocheck ne '') && ($dir ne '')) {
10819: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
10820: }
10821: }
10822: } else {
10823: $warning = &mt('No items found in archive.');
10824: }
10825: if ($error) {
10826: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10827: $error.'</p>'."\n";
10828: }
10829: if ($warning) {
10830: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10831: }
10832: return $output;
10833: }
10834:
10835: sub cleanup_empty_dirs {
10836: my ($path) = @_;
10837: if (($path ne '') && (-d $path)) {
10838: if (opendir(my $dirh,$path)) {
10839: my @dircontents = grep(!/^\./,readdir($dirh));
10840: my $numitems = 0;
10841: foreach my $item (@dircontents) {
10842: if (-d "$path/$item") {
10843: &recurse_dirs("$path/$item");
10844: if (-e "$path/$item") {
10845: $numitems ++;
10846: }
10847: } else {
10848: $numitems ++;
10849: }
10850: }
10851: if ($numitems == 0) {
10852: rmdir($path);
10853: }
10854: closedir($dirh);
10855: }
10856: }
10857: return;
10858: }
10859:
10860: =pod
10861:
10862: =item * &get_turnedin_filepath()
10863:
10864: Determines path in a user's portfolio file for storage of files uploaded
10865: to a specific essayresponse or dropbox item.
10866:
10867: Inputs: 3 required + 1 optional.
10868: $symb is symb for resource, $uname and $udom are for current user (required).
10869: $caller is optional (can be "submission", if routine is called when storing
10870: an upoaded file when "Submit Answer" button was pressed).
10871:
10872: Returns array containing $path and $multiresp.
10873: $path is path in portfolio. $multiresp is 1 if this resource contains more
10874: than one file upload item. Callers of routine should append partid as a
10875: subdirectory to $path in cases where $multiresp is 1.
10876:
10877: Called by: homework/essayresponse.pm and homework/structuretags.pm
10878:
10879: =cut
10880:
10881: sub get_turnedin_filepath {
10882: my ($symb,$uname,$udom,$caller) = @_;
10883: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
10884: my $turnindir;
10885: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
10886: $turnindir = $userhash{'turnindir'};
10887: my ($path,$multiresp);
10888: if ($turnindir eq '') {
10889: if ($caller eq 'submission') {
10890: $turnindir = &mt('turned in');
10891: $turnindir =~ s/\W+/_/g;
10892: my %newhash = (
10893: 'turnindir' => $turnindir,
10894: );
10895: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
10896: }
10897: }
10898: if ($turnindir ne '') {
10899: $path = '/'.$turnindir.'/';
10900: my ($multipart,$turnin,@pathitems);
10901: my $navmap = Apache::lonnavmaps::navmap->new();
10902: if (defined($navmap)) {
10903: my $mapres = $navmap->getResourceByUrl($map);
10904: if (ref($mapres)) {
10905: my $pcslist = $mapres->map_hierarchy();
10906: if ($pcslist ne '') {
10907: foreach my $pc (split(/,/,$pcslist)) {
10908: my $res = $navmap->getByMapPc($pc);
10909: if (ref($res)) {
10910: my $title = $res->compTitle();
10911: $title =~ s/\W+/_/g;
10912: if ($title ne '') {
10913: push(@pathitems,$title);
10914: }
10915: }
10916: }
10917: }
10918: my $maptitle = $mapres->compTitle();
10919: $maptitle =~ s/\W+/_/g;
10920: if ($maptitle ne '') {
10921: push(@pathitems,$maptitle);
10922: }
10923: unless ($env{'request.state'} eq 'construct') {
10924: my $res = $navmap->getBySymb($symb);
10925: if (ref($res)) {
10926: my $partlist = $res->parts();
10927: my $totaluploads = 0;
10928: if (ref($partlist) eq 'ARRAY') {
10929: foreach my $part (@{$partlist}) {
10930: my @types = $res->responseType($part);
10931: my @ids = $res->responseIds($part);
10932: for (my $i=0; $i < scalar(@ids); $i++) {
10933: if ($types[$i] eq 'essay') {
10934: my $partid = $part.'_'.$ids[$i];
10935: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
10936: $totaluploads ++;
10937: }
10938: }
10939: }
10940: }
10941: if ($totaluploads > 1) {
10942: $multiresp = 1;
10943: }
10944: }
10945: }
10946: }
10947: } else {
10948: return;
10949: }
10950: } else {
10951: return;
10952: }
10953: my $restitle=&Apache::lonnet::gettitle($symb);
10954: $restitle =~ s/\W+/_/g;
10955: if ($restitle eq '') {
10956: $restitle = ($resurl =~ m{/[^/]+$});
10957: if ($restitle eq '') {
10958: $restitle = time;
10959: }
10960: }
10961: push(@pathitems,$restitle);
10962: $path .= join('/',@pathitems);
10963: }
10964: return ($path,$multiresp);
10965: }
10966:
10967: =pod
10968:
10969: =back
10970:
10971: =head1 CSV Upload/Handling functions
10972:
10973: =over 4
10974:
10975: =item * &upfile_store($r)
10976:
10977: Store uploaded file, $r should be the HTTP Request object,
10978: needs $env{'form.upfile'}
10979: returns $datatoken to be put into hidden field
10980:
10981: =cut
10982:
10983: sub upfile_store {
10984: my $r=shift;
10985: $env{'form.upfile'}=~s/\r/\n/gs;
10986: $env{'form.upfile'}=~s/\f/\n/gs;
10987: $env{'form.upfile'}=~s/\n+/\n/gs;
10988: $env{'form.upfile'}=~s/\n+$//gs;
10989:
10990: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
10991: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
10992: {
10993: my $datafile = $r->dir_config('lonDaemons').
10994: '/tmp/'.$datatoken.'.tmp';
10995: if ( open(my $fh,">$datafile") ) {
10996: print $fh $env{'form.upfile'};
10997: close($fh);
10998: }
10999: }
11000: return $datatoken;
11001: }
11002:
11003: =pod
11004:
11005: =item * &load_tmp_file($r)
11006:
11007: Load uploaded file from tmp, $r should be the HTTP Request object,
11008: needs $env{'form.datatoken'},
11009: sets $env{'form.upfile'} to the contents of the file
11010:
11011: =cut
11012:
11013: sub load_tmp_file {
11014: my $r=shift;
11015: my @studentdata=();
11016: {
11017: my $studentfile = $r->dir_config('lonDaemons').
11018: '/tmp/'.$env{'form.datatoken'}.'.tmp';
11019: if ( open(my $fh,"<$studentfile") ) {
11020: @studentdata=<$fh>;
11021: close($fh);
11022: }
11023: }
11024: $env{'form.upfile'}=join('',@studentdata);
11025: }
11026:
11027: =pod
11028:
11029: =item * &upfile_record_sep()
11030:
11031: Separate uploaded file into records
11032: returns array of records,
11033: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11034:
11035: =cut
11036:
11037: sub upfile_record_sep {
11038: if ($env{'form.upfiletype'} eq 'xml') {
11039: } else {
11040: my @records;
11041: foreach my $line (split(/\n/,$env{'form.upfile'})) {
11042: if ($line=~/^\s*$/) { next; }
11043: push(@records,$line);
11044: }
11045: return @records;
11046: }
11047: }
11048:
11049: =pod
11050:
11051: =item * &record_sep($record)
11052:
11053: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11054:
11055: =cut
11056:
11057: sub takeleft {
11058: my $index=shift;
11059: return substr('0000'.$index,-4,4);
11060: }
11061:
11062: sub record_sep {
11063: my $record=shift;
11064: my %components=();
11065: if ($env{'form.upfiletype'} eq 'xml') {
11066: } elsif ($env{'form.upfiletype'} eq 'space') {
11067: my $i=0;
11068: foreach my $field (split(/\s+/,$record)) {
11069: $field=~s/^(\"|\')//;
11070: $field=~s/(\"|\')$//;
11071: $components{&takeleft($i)}=$field;
11072: $i++;
11073: }
11074: } elsif ($env{'form.upfiletype'} eq 'tab') {
11075: my $i=0;
11076: foreach my $field (split(/\t/,$record)) {
11077: $field=~s/^(\"|\')//;
11078: $field=~s/(\"|\')$//;
11079: $components{&takeleft($i)}=$field;
11080: $i++;
11081: }
11082: } else {
11083: my $separator=',';
11084: if ($env{'form.upfiletype'} eq 'semisv') {
11085: $separator=';';
11086: }
11087: my $i=0;
11088: # the character we are looking for to indicate the end of a quote or a record
11089: my $looking_for=$separator;
11090: # do not add the characters to the fields
11091: my $ignore=0;
11092: # we just encountered a separator (or the beginning of the record)
11093: my $just_found_separator=1;
11094: # store the field we are working on here
11095: my $field='';
11096: # work our way through all characters in record
11097: foreach my $character ($record=~/(.)/g) {
11098: if ($character eq $looking_for) {
11099: if ($character ne $separator) {
11100: # Found the end of a quote, again looking for separator
11101: $looking_for=$separator;
11102: $ignore=1;
11103: } else {
11104: # Found a separator, store away what we got
11105: $components{&takeleft($i)}=$field;
11106: $i++;
11107: $just_found_separator=1;
11108: $ignore=0;
11109: $field='';
11110: }
11111: next;
11112: }
11113: # single or double quotation marks after a separator indicate beginning of a quote
11114: # we are now looking for the end of the quote and need to ignore separators
11115: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
11116: $looking_for=$character;
11117: next;
11118: }
11119: # ignore would be true after we reached the end of a quote
11120: if ($ignore) { next; }
11121: if (($just_found_separator) && ($character=~/\s/)) { next; }
11122: $field.=$character;
11123: $just_found_separator=0;
11124: }
11125: # catch the very last entry, since we never encountered the separator
11126: $components{&takeleft($i)}=$field;
11127: }
11128: return %components;
11129: }
11130:
11131: ######################################################
11132: ######################################################
11133:
11134: =pod
11135:
11136: =item * &upfile_select_html()
11137:
11138: Return HTML code to select a file from the users machine and specify
11139: the file type.
11140:
11141: =cut
11142:
11143: ######################################################
11144: ######################################################
11145: sub upfile_select_html {
11146: my %Types = (
11147: csv => &mt('CSV (comma separated values, spreadsheet)'),
11148: semisv => &mt('Semicolon separated values'),
11149: space => &mt('Space separated'),
11150: tab => &mt('Tabulator separated'),
11151: # xml => &mt('HTML/XML'),
11152: );
11153: my $Str = '<input type="file" name="upfile" size="50" />'.
11154: '<br />'.&mt('Type').': <select name="upfiletype">';
11155: foreach my $type (sort(keys(%Types))) {
11156: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
11157: }
11158: $Str .= "</select>\n";
11159: return $Str;
11160: }
11161:
11162: sub get_samples {
11163: my ($records,$toget) = @_;
11164: my @samples=({});
11165: my $got=0;
11166: foreach my $rec (@$records) {
11167: my %temp = &record_sep($rec);
11168: if (! grep(/\S/, values(%temp))) { next; }
11169: if (%temp) {
11170: $samples[$got]=\%temp;
11171: $got++;
11172: if ($got == $toget) { last; }
11173: }
11174: }
11175: return \@samples;
11176: }
11177:
11178: ######################################################
11179: ######################################################
11180:
11181: =pod
11182:
11183: =item * &csv_print_samples($r,$records)
11184:
11185: Prints a table of sample values from each column uploaded $r is an
11186: Apache Request ref, $records is an arrayref from
11187: &Apache::loncommon::upfile_record_sep
11188:
11189: =cut
11190:
11191: ######################################################
11192: ######################################################
11193: sub csv_print_samples {
11194: my ($r,$records) = @_;
11195: my $samples = &get_samples($records,5);
11196:
11197: $r->print(&mt('Samples').'<br />'.&start_data_table().
11198: &start_data_table_header_row());
11199: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11200: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
11201: $r->print(&end_data_table_header_row());
11202: foreach my $hash (@$samples) {
11203: $r->print(&start_data_table_row());
11204: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11205: $r->print('<td>');
11206: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
11207: $r->print('</td>');
11208: }
11209: $r->print(&end_data_table_row());
11210: }
11211: $r->print(&end_data_table().'<br />'."\n");
11212: }
11213:
11214: ######################################################
11215: ######################################################
11216:
11217: =pod
11218:
11219: =item * &csv_print_select_table($r,$records,$d)
11220:
11221: Prints a table to create associations between values and table columns.
11222:
11223: $r is an Apache Request ref,
11224: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11225: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
11226:
11227: =cut
11228:
11229: ######################################################
11230: ######################################################
11231: sub csv_print_select_table {
11232: my ($r,$records,$d) = @_;
11233: my $i=0;
11234: my $samples = &get_samples($records,1);
11235: $r->print(&mt('Associate columns with student attributes.')."\n".
11236: &start_data_table().&start_data_table_header_row().
11237: '<th>'.&mt('Attribute').'</th>'.
11238: '<th>'.&mt('Column').'</th>'.
11239: &end_data_table_header_row()."\n");
11240: foreach my $array_ref (@$d) {
11241: my ($value,$display,$defaultcol)=@{ $array_ref };
11242: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
11243:
11244: $r->print('<td><select name="f'.$i.'"'.
11245: ' onchange="javascript:flip(this.form,'.$i.');">');
11246: $r->print('<option value="none"></option>');
11247: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
11248: $r->print('<option value="'.$sample.'"'.
11249: ($sample eq $defaultcol ? ' selected="selected" ' : '').
11250: '>'.&mt('Column [_1]',($sample+1)).'</option>');
11251: }
11252: $r->print('</select></td>'.&end_data_table_row()."\n");
11253: $i++;
11254: }
11255: $r->print(&end_data_table());
11256: $i--;
11257: return $i;
11258: }
11259:
11260: ######################################################
11261: ######################################################
11262:
11263: =pod
11264:
11265: =item * &csv_samples_select_table($r,$records,$d)
11266:
11267: Prints a table of sample values from the upload and can make associate samples to internal names.
11268:
11269: $r is an Apache Request ref,
11270: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
11271: $d is an array of 2 element arrays (internal name, displayed name)
11272:
11273: =cut
11274:
11275: ######################################################
11276: ######################################################
11277: sub csv_samples_select_table {
11278: my ($r,$records,$d) = @_;
11279: my $i=0;
11280: #
11281: my $max_samples = 5;
11282: my $samples = &get_samples($records,$max_samples);
11283: $r->print(&start_data_table().
11284: &start_data_table_header_row().'<th>'.
11285: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
11286: &end_data_table_header_row());
11287:
11288: foreach my $key (sort(keys(%{ $samples->[0] }))) {
11289: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
11290: ' onchange="javascript:flip(this.form,'.$i.');">');
11291: foreach my $option (@$d) {
11292: my ($value,$display,$defaultcol)=@{ $option };
11293: $r->print('<option value="'.$value.'"'.
11294: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
11295: $display.'</option>');
11296: }
11297: $r->print('</select></td><td>');
11298: foreach my $line (0..($max_samples-1)) {
11299: if (defined($samples->[$line]{$key})) {
11300: $r->print($samples->[$line]{$key}."<br />\n");
11301: }
11302: }
11303: $r->print('</td>'.&end_data_table_row());
11304: $i++;
11305: }
11306: $r->print(&end_data_table());
11307: $i--;
11308: return($i);
11309: }
11310:
11311: ######################################################
11312: ######################################################
11313:
11314: =pod
11315:
11316: =item * &clean_excel_name($name)
11317:
11318: Returns a replacement for $name which does not contain any illegal characters.
11319:
11320: =cut
11321:
11322: ######################################################
11323: ######################################################
11324: sub clean_excel_name {
11325: my ($name) = @_;
11326: $name =~ s/[:\*\?\/\\]//g;
11327: if (length($name) > 31) {
11328: $name = substr($name,0,31);
11329: }
11330: return $name;
11331: }
11332:
11333: =pod
11334:
11335: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
11336:
11337: Returns either 1 or undef
11338:
11339: 1 if the part is to be hidden, undef if it is to be shown
11340:
11341: Arguments are:
11342:
11343: $id the id of the part to be checked
11344: $symb, optional the symb of the resource to check
11345: $udom, optional the domain of the user to check for
11346: $uname, optional the username of the user to check for
11347:
11348: =cut
11349:
11350: sub check_if_partid_hidden {
11351: my ($id,$symb,$udom,$uname) = @_;
11352: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
11353: $symb,$udom,$uname);
11354: my $truth=1;
11355: #if the string starts with !, then the list is the list to show not hide
11356: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
11357: my @hiddenlist=split(/,/,$hiddenparts);
11358: foreach my $checkid (@hiddenlist) {
11359: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
11360: }
11361: return !$truth;
11362: }
11363:
11364:
11365: ############################################################
11366: ############################################################
11367:
11368: =pod
11369:
11370: =back
11371:
11372: =head1 cgi-bin script and graphing routines
11373:
11374: =over 4
11375:
11376: =item * &get_cgi_id()
11377:
11378: Inputs: none
11379:
11380: Returns an id which can be used to pass environment variables
11381: to various cgi-bin scripts. These environment variables will
11382: be removed from the users environment after a given time by
11383: the routine &Apache::lonnet::transfer_profile_to_env.
11384:
11385: =cut
11386:
11387: ############################################################
11388: ############################################################
11389: my $uniq=0;
11390: sub get_cgi_id {
11391: $uniq=($uniq+1)%100000;
11392: return (time.'_'.$$.'_'.$uniq);
11393: }
11394:
11395: ############################################################
11396: ############################################################
11397:
11398: =pod
11399:
11400: =item * &DrawBarGraph()
11401:
11402: Facilitates the plotting of data in a (stacked) bar graph.
11403: Puts plot definition data into the users environment in order for
11404: graph.png to plot it. Returns an <img> tag for the plot.
11405: The bars on the plot are labeled '1','2',...,'n'.
11406:
11407: Inputs:
11408:
11409: =over 4
11410:
11411: =item $Title: string, the title of the plot
11412:
11413: =item $xlabel: string, text describing the X-axis of the plot
11414:
11415: =item $ylabel: string, text describing the Y-axis of the plot
11416:
11417: =item $Max: scalar, the maximum Y value to use in the plot
11418: If $Max is < any data point, the graph will not be rendered.
11419:
11420: =item $colors: array ref holding the colors to be used for the data sets when
11421: they are plotted. If undefined, default values will be used.
11422:
11423: =item $labels: array ref holding the labels to use on the x-axis for the bars.
11424:
11425: =item @Values: An array of array references. Each array reference holds data
11426: to be plotted in a stacked bar chart.
11427:
11428: =item If the final element of @Values is a hash reference the key/value
11429: pairs will be added to the graph definition.
11430:
11431: =back
11432:
11433: Returns:
11434:
11435: An <img> tag which references graph.png and the appropriate identifying
11436: information for the plot.
11437:
11438: =cut
11439:
11440: ############################################################
11441: ############################################################
11442: sub DrawBarGraph {
11443: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
11444: #
11445: if (! defined($colors)) {
11446: $colors = ['#33ff00',
11447: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
11448: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
11449: ];
11450: }
11451: my $extra_settings = {};
11452: if (ref($Values[-1]) eq 'HASH') {
11453: $extra_settings = pop(@Values);
11454: }
11455: #
11456: my $identifier = &get_cgi_id();
11457: my $id = 'cgi.'.$identifier;
11458: if (! @Values || ref($Values[0]) ne 'ARRAY') {
11459: return '';
11460: }
11461: #
11462: my @Labels;
11463: if (defined($labels)) {
11464: @Labels = @$labels;
11465: } else {
11466: for (my $i=0;$i<@{$Values[0]};$i++) {
11467: push (@Labels,$i+1);
11468: }
11469: }
11470: #
11471: my $NumBars = scalar(@{$Values[0]});
11472: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
11473: my %ValuesHash;
11474: my $NumSets=1;
11475: foreach my $array (@Values) {
11476: next if (! ref($array));
11477: $ValuesHash{$id.'.data.'.$NumSets++} =
11478: join(',',@$array);
11479: }
11480: #
11481: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
11482: if ($NumBars < 3) {
11483: $width = 120+$NumBars*32;
11484: $xskip = 1;
11485: $bar_width = 30;
11486: } elsif ($NumBars < 5) {
11487: $width = 120+$NumBars*20;
11488: $xskip = 1;
11489: $bar_width = 20;
11490: } elsif ($NumBars < 10) {
11491: $width = 120+$NumBars*15;
11492: $xskip = 1;
11493: $bar_width = 15;
11494: } elsif ($NumBars <= 25) {
11495: $width = 120+$NumBars*11;
11496: $xskip = 5;
11497: $bar_width = 8;
11498: } elsif ($NumBars <= 50) {
11499: $width = 120+$NumBars*8;
11500: $xskip = 5;
11501: $bar_width = 4;
11502: } else {
11503: $width = 120+$NumBars*8;
11504: $xskip = 5;
11505: $bar_width = 4;
11506: }
11507: #
11508: $Max = 1 if ($Max < 1);
11509: if ( int($Max) < $Max ) {
11510: $Max++;
11511: $Max = int($Max);
11512: }
11513: $Title = '' if (! defined($Title));
11514: $xlabel = '' if (! defined($xlabel));
11515: $ylabel = '' if (! defined($ylabel));
11516: $ValuesHash{$id.'.title'} = &escape($Title);
11517: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
11518: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
11519: $ValuesHash{$id.'.y_max_value'} = $Max;
11520: $ValuesHash{$id.'.NumBars'} = $NumBars;
11521: $ValuesHash{$id.'.NumSets'} = $NumSets;
11522: $ValuesHash{$id.'.PlotType'} = 'bar';
11523: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11524: $ValuesHash{$id.'.height'} = $height;
11525: $ValuesHash{$id.'.width'} = $width;
11526: $ValuesHash{$id.'.xskip'} = $xskip;
11527: $ValuesHash{$id.'.bar_width'} = $bar_width;
11528: $ValuesHash{$id.'.labels'} = join(',',@Labels);
11529: #
11530: # Deal with other parameters
11531: while (my ($key,$value) = each(%$extra_settings)) {
11532: $ValuesHash{$id.'.'.$key} = $value;
11533: }
11534: #
11535: &Apache::lonnet::appenv(\%ValuesHash);
11536: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11537: }
11538:
11539: ############################################################
11540: ############################################################
11541:
11542: =pod
11543:
11544: =item * &DrawXYGraph()
11545:
11546: Facilitates the plotting of data in an XY graph.
11547: Puts plot definition data into the users environment in order for
11548: graph.png to plot it. Returns an <img> tag for the plot.
11549:
11550: Inputs:
11551:
11552: =over 4
11553:
11554: =item $Title: string, the title of the plot
11555:
11556: =item $xlabel: string, text describing the X-axis of the plot
11557:
11558: =item $ylabel: string, text describing the Y-axis of the plot
11559:
11560: =item $Max: scalar, the maximum Y value to use in the plot
11561: If $Max is < any data point, the graph will not be rendered.
11562:
11563: =item $colors: Array ref containing the hex color codes for the data to be
11564: plotted in. If undefined, default values will be used.
11565:
11566: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
11567:
11568: =item $Ydata: Array ref containing Array refs.
11569: Each of the contained arrays will be plotted as a separate curve.
11570:
11571: =item %Values: hash indicating or overriding any default values which are
11572: passed to graph.png.
11573: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
11574:
11575: =back
11576:
11577: Returns:
11578:
11579: An <img> tag which references graph.png and the appropriate identifying
11580: information for the plot.
11581:
11582: =cut
11583:
11584: ############################################################
11585: ############################################################
11586: sub DrawXYGraph {
11587: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
11588: #
11589: # Create the identifier for the graph
11590: my $identifier = &get_cgi_id();
11591: my $id = 'cgi.'.$identifier;
11592: #
11593: $Title = '' if (! defined($Title));
11594: $xlabel = '' if (! defined($xlabel));
11595: $ylabel = '' if (! defined($ylabel));
11596: my %ValuesHash =
11597: (
11598: $id.'.title' => &escape($Title),
11599: $id.'.xlabel' => &escape($xlabel),
11600: $id.'.ylabel' => &escape($ylabel),
11601: $id.'.y_max_value'=> $Max,
11602: $id.'.labels' => join(',',@$Xlabels),
11603: $id.'.PlotType' => 'XY',
11604: );
11605: #
11606: if (defined($colors) && ref($colors) eq 'ARRAY') {
11607: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11608: }
11609: #
11610: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
11611: return '';
11612: }
11613: my $NumSets=1;
11614: foreach my $array (@{$Ydata}){
11615: next if (! ref($array));
11616: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
11617: }
11618: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
11619: #
11620: # Deal with other parameters
11621: while (my ($key,$value) = each(%Values)) {
11622: $ValuesHash{$id.'.'.$key} = $value;
11623: }
11624: #
11625: &Apache::lonnet::appenv(\%ValuesHash);
11626: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11627: }
11628:
11629: ############################################################
11630: ############################################################
11631:
11632: =pod
11633:
11634: =item * &DrawXYYGraph()
11635:
11636: Facilitates the plotting of data in an XY graph with two Y axes.
11637: Puts plot definition data into the users environment in order for
11638: graph.png to plot it. Returns an <img> tag for the plot.
11639:
11640: Inputs:
11641:
11642: =over 4
11643:
11644: =item $Title: string, the title of the plot
11645:
11646: =item $xlabel: string, text describing the X-axis of the plot
11647:
11648: =item $ylabel: string, text describing the Y-axis of the plot
11649:
11650: =item $colors: Array ref containing the hex color codes for the data to be
11651: plotted in. If undefined, default values will be used.
11652:
11653: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
11654:
11655: =item $Ydata1: The first data set
11656:
11657: =item $Min1: The minimum value of the left Y-axis
11658:
11659: =item $Max1: The maximum value of the left Y-axis
11660:
11661: =item $Ydata2: The second data set
11662:
11663: =item $Min2: The minimum value of the right Y-axis
11664:
11665: =item $Max2: The maximum value of the left Y-axis
11666:
11667: =item %Values: hash indicating or overriding any default values which are
11668: passed to graph.png.
11669: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
11670:
11671: =back
11672:
11673: Returns:
11674:
11675: An <img> tag which references graph.png and the appropriate identifying
11676: information for the plot.
11677:
11678: =cut
11679:
11680: ############################################################
11681: ############################################################
11682: sub DrawXYYGraph {
11683: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
11684: $Ydata2,$Min2,$Max2,%Values)=@_;
11685: #
11686: # Create the identifier for the graph
11687: my $identifier = &get_cgi_id();
11688: my $id = 'cgi.'.$identifier;
11689: #
11690: $Title = '' if (! defined($Title));
11691: $xlabel = '' if (! defined($xlabel));
11692: $ylabel = '' if (! defined($ylabel));
11693: my %ValuesHash =
11694: (
11695: $id.'.title' => &escape($Title),
11696: $id.'.xlabel' => &escape($xlabel),
11697: $id.'.ylabel' => &escape($ylabel),
11698: $id.'.labels' => join(',',@$Xlabels),
11699: $id.'.PlotType' => 'XY',
11700: $id.'.NumSets' => 2,
11701: $id.'.two_axes' => 1,
11702: $id.'.y1_max_value' => $Max1,
11703: $id.'.y1_min_value' => $Min1,
11704: $id.'.y2_max_value' => $Max2,
11705: $id.'.y2_min_value' => $Min2,
11706: );
11707: #
11708: if (defined($colors) && ref($colors) eq 'ARRAY') {
11709: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11710: }
11711: #
11712: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
11713: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
11714: return '';
11715: }
11716: my $NumSets=1;
11717: foreach my $array ($Ydata1,$Ydata2){
11718: next if (! ref($array));
11719: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
11720: }
11721: #
11722: # Deal with other parameters
11723: while (my ($key,$value) = each(%Values)) {
11724: $ValuesHash{$id.'.'.$key} = $value;
11725: }
11726: #
11727: &Apache::lonnet::appenv(\%ValuesHash);
11728: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11729: }
11730:
11731: ############################################################
11732: ############################################################
11733:
11734: =pod
11735:
11736: =back
11737:
11738: =head1 Statistics helper routines?
11739:
11740: Bad place for them but what the hell.
11741:
11742: =over 4
11743:
11744: =item * &chartlink()
11745:
11746: Returns a link to the chart for a specific student.
11747:
11748: Inputs:
11749:
11750: =over 4
11751:
11752: =item $linktext: The text of the link
11753:
11754: =item $sname: The students username
11755:
11756: =item $sdomain: The students domain
11757:
11758: =back
11759:
11760: =back
11761:
11762: =cut
11763:
11764: ############################################################
11765: ############################################################
11766: sub chartlink {
11767: my ($linktext, $sname, $sdomain) = @_;
11768: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
11769: '&SelectedStudent='.&escape($sname.':'.$sdomain).
11770: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
11771: '">'.$linktext.'</a>';
11772: }
11773:
11774: #######################################################
11775: #######################################################
11776:
11777: =pod
11778:
11779: =head1 Course Environment Routines
11780:
11781: =over 4
11782:
11783: =item * &restore_course_settings()
11784:
11785: =item * &store_course_settings()
11786:
11787: Restores/Store indicated form parameters from the course environment.
11788: Will not overwrite existing values of the form parameters.
11789:
11790: Inputs:
11791: a scalar describing the data (e.g. 'chart', 'problem_analysis')
11792:
11793: a hash ref describing the data to be stored. For example:
11794:
11795: %Save_Parameters = ('Status' => 'scalar',
11796: 'chartoutputmode' => 'scalar',
11797: 'chartoutputdata' => 'scalar',
11798: 'Section' => 'array',
11799: 'Group' => 'array',
11800: 'StudentData' => 'array',
11801: 'Maps' => 'array');
11802:
11803: Returns: both routines return nothing
11804:
11805: =back
11806:
11807: =cut
11808:
11809: #######################################################
11810: #######################################################
11811: sub store_course_settings {
11812: return &store_settings($env{'request.course.id'},@_);
11813: }
11814:
11815: sub store_settings {
11816: # save to the environment
11817: # appenv the same items, just to be safe
11818: my $udom = $env{'user.domain'};
11819: my $uname = $env{'user.name'};
11820: my ($context,$prefix,$Settings) = @_;
11821: my %SaveHash;
11822: my %AppHash;
11823: while (my ($setting,$type) = each(%$Settings)) {
11824: my $basename = join('.','internal',$context,$prefix,$setting);
11825: my $envname = 'environment.'.$basename;
11826: if (exists($env{'form.'.$setting})) {
11827: # Save this value away
11828: if ($type eq 'scalar' &&
11829: (! exists($env{$envname}) ||
11830: $env{$envname} ne $env{'form.'.$setting})) {
11831: $SaveHash{$basename} = $env{'form.'.$setting};
11832: $AppHash{$envname} = $env{'form.'.$setting};
11833: } elsif ($type eq 'array') {
11834: my $stored_form;
11835: if (ref($env{'form.'.$setting})) {
11836: $stored_form = join(',',
11837: map {
11838: &escape($_);
11839: } sort(@{$env{'form.'.$setting}}));
11840: } else {
11841: $stored_form =
11842: &escape($env{'form.'.$setting});
11843: }
11844: # Determine if the array contents are the same.
11845: if ($stored_form ne $env{$envname}) {
11846: $SaveHash{$basename} = $stored_form;
11847: $AppHash{$envname} = $stored_form;
11848: }
11849: }
11850: }
11851: }
11852: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
11853: $udom,$uname);
11854: if ($put_result !~ /^(ok|delayed)/) {
11855: &Apache::lonnet::logthis('unable to save form parameters, '.
11856: 'got error:'.$put_result);
11857: }
11858: # Make sure these settings stick around in this session, too
11859: &Apache::lonnet::appenv(\%AppHash);
11860: return;
11861: }
11862:
11863: sub restore_course_settings {
11864: return &restore_settings($env{'request.course.id'},@_);
11865: }
11866:
11867: sub restore_settings {
11868: my ($context,$prefix,$Settings) = @_;
11869: while (my ($setting,$type) = each(%$Settings)) {
11870: next if (exists($env{'form.'.$setting}));
11871: my $envname = 'environment.internal.'.$context.'.'.$prefix.
11872: '.'.$setting;
11873: if (exists($env{$envname})) {
11874: if ($type eq 'scalar') {
11875: $env{'form.'.$setting} = $env{$envname};
11876: } elsif ($type eq 'array') {
11877: $env{'form.'.$setting} = [
11878: map {
11879: &unescape($_);
11880: } split(',',$env{$envname})
11881: ];
11882: }
11883: }
11884: }
11885: }
11886:
11887: #######################################################
11888: #######################################################
11889:
11890: =pod
11891:
11892: =head1 Domain E-mail Routines
11893:
11894: =over 4
11895:
11896: =item * &build_recipient_list()
11897:
11898: Build recipient lists for five types of e-mail:
11899: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
11900: (d) Help requests, (e) Course requests needing approval, generated by
11901: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
11902: loncoursequeueadmin.pm respectively.
11903:
11904: Inputs:
11905: defmail (scalar - email address of default recipient),
11906: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
11907: defdom (domain for which to retrieve configuration settings),
11908: origmail (scalar - email address of recipient from loncapa.conf,
11909: i.e., predates configuration by DC via domainprefs.pm
11910:
11911: Returns: comma separated list of addresses to which to send e-mail.
11912:
11913: =back
11914:
11915: =cut
11916:
11917: ############################################################
11918: ############################################################
11919: sub build_recipient_list {
11920: my ($defmail,$mailing,$defdom,$origmail) = @_;
11921: my @recipients;
11922: my $otheremails;
11923: my %domconfig =
11924: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
11925: if (ref($domconfig{'contacts'}) eq 'HASH') {
11926: if (exists($domconfig{'contacts'}{$mailing})) {
11927: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
11928: my @contacts = ('adminemail','supportemail');
11929: foreach my $item (@contacts) {
11930: if ($domconfig{'contacts'}{$mailing}{$item}) {
11931: my $addr = $domconfig{'contacts'}{$item};
11932: if (!grep(/^\Q$addr\E$/,@recipients)) {
11933: push(@recipients,$addr);
11934: }
11935: }
11936: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
11937: }
11938: }
11939: } elsif ($origmail ne '') {
11940: push(@recipients,$origmail);
11941: }
11942: } elsif ($origmail ne '') {
11943: push(@recipients,$origmail);
11944: }
11945: if (defined($defmail)) {
11946: if ($defmail ne '') {
11947: push(@recipients,$defmail);
11948: }
11949: }
11950: if ($otheremails) {
11951: my @others;
11952: if ($otheremails =~ /,/) {
11953: @others = split(/,/,$otheremails);
11954: } else {
11955: push(@others,$otheremails);
11956: }
11957: foreach my $addr (@others) {
11958: if (!grep(/^\Q$addr\E$/,@recipients)) {
11959: push(@recipients,$addr);
11960: }
11961: }
11962: }
11963: my $recipientlist = join(',',@recipients);
11964: return $recipientlist;
11965: }
11966:
11967: ############################################################
11968: ############################################################
11969:
11970: =pod
11971:
11972: =head1 Course Catalog Routines
11973:
11974: =over 4
11975:
11976: =item * &gather_categories()
11977:
11978: Converts category definitions - keys of categories hash stored in
11979: coursecategories in configuration.db on the primary library server in a
11980: domain - to an array. Also generates javascript and idx hash used to
11981: generate Domain Coordinator interface for editing Course Categories.
11982:
11983: Inputs:
11984:
11985: categories (reference to hash of category definitions).
11986:
11987: cats (reference to array of arrays/hashes which encapsulates hierarchy of
11988: categories and subcategories).
11989:
11990: idx (reference to hash of counters used in Domain Coordinator interface for
11991: editing Course Categories).
11992:
11993: jsarray (reference to array of categories used to create Javascript arrays for
11994: Domain Coordinator interface for editing Course Categories).
11995:
11996: Returns: nothing
11997:
11998: Side effects: populates cats, idx and jsarray.
11999:
12000: =cut
12001:
12002: sub gather_categories {
12003: my ($categories,$cats,$idx,$jsarray) = @_;
12004: my %counters;
12005: my $num = 0;
12006: foreach my $item (keys(%{$categories})) {
12007: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12008: if ($container eq '' && $depth == 0) {
12009: $cats->[$depth][$categories->{$item}] = $cat;
12010: } else {
12011: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12012: }
12013: my ($escitem,$tail) = split(/:/,$item,2);
12014: if ($counters{$tail} eq '') {
12015: $counters{$tail} = $num;
12016: $num ++;
12017: }
12018: if (ref($idx) eq 'HASH') {
12019: $idx->{$item} = $counters{$tail};
12020: }
12021: if (ref($jsarray) eq 'ARRAY') {
12022: push(@{$jsarray->[$counters{$tail}]},$item);
12023: }
12024: }
12025: return;
12026: }
12027:
12028: =pod
12029:
12030: =item * &extract_categories()
12031:
12032: Used to generate breadcrumb trails for course categories.
12033:
12034: Inputs:
12035:
12036: categories (reference to hash of category definitions).
12037:
12038: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12039: categories and subcategories).
12040:
12041: trails (reference to array of breacrumb trails for each category).
12042:
12043: allitems (reference to hash - key is category key
12044: (format: escaped(name):escaped(parent category):depth in hierarchy).
12045:
12046: idx (reference to hash of counters used in Domain Coordinator interface for
12047: editing Course Categories).
12048:
12049: jsarray (reference to array of categories used to create Javascript arrays for
12050: Domain Coordinator interface for editing Course Categories).
12051:
12052: subcats (reference to hash of arrays containing all subcategories within each
12053: category, -recursive)
12054:
12055: Returns: nothing
12056:
12057: Side effects: populates trails and allitems hash references.
12058:
12059: =cut
12060:
12061: sub extract_categories {
12062: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12063: if (ref($categories) eq 'HASH') {
12064: &gather_categories($categories,$cats,$idx,$jsarray);
12065: if (ref($cats->[0]) eq 'ARRAY') {
12066: for (my $i=0; $i<@{$cats->[0]}; $i++) {
12067: my $name = $cats->[0][$i];
12068: my $item = &escape($name).'::0';
12069: my $trailstr;
12070: if ($name eq 'instcode') {
12071: $trailstr = &mt('Official courses (with institutional codes)');
12072: } elsif ($name eq 'communities') {
12073: $trailstr = &mt('Communities');
12074: } else {
12075: $trailstr = $name;
12076: }
12077: if ($allitems->{$item} eq '') {
12078: push(@{$trails},$trailstr);
12079: $allitems->{$item} = scalar(@{$trails})-1;
12080: }
12081: my @parents = ($name);
12082: if (ref($cats->[1]{$name}) eq 'ARRAY') {
12083: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12084: my $category = $cats->[1]{$name}[$j];
12085: if (ref($subcats) eq 'HASH') {
12086: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12087: }
12088: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12089: }
12090: } else {
12091: if (ref($subcats) eq 'HASH') {
12092: $subcats->{$item} = [];
12093: }
12094: }
12095: }
12096: }
12097: }
12098: return;
12099: }
12100:
12101: =pod
12102:
12103: =item *&recurse_categories()
12104:
12105: Recursively used to generate breadcrumb trails for course categories.
12106:
12107: Inputs:
12108:
12109: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12110: categories and subcategories).
12111:
12112: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12113:
12114: category (current course category, for which breadcrumb trail is being generated).
12115:
12116: trails (reference to array of breadcrumb trails for each category).
12117:
12118: allitems (reference to hash - key is category key
12119: (format: escaped(name):escaped(parent category):depth in hierarchy).
12120:
12121: parents (array containing containers directories for current category,
12122: back to top level).
12123:
12124: Returns: nothing
12125:
12126: Side effects: populates trails and allitems hash references
12127:
12128: =cut
12129:
12130: sub recurse_categories {
12131: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12132: my $shallower = $depth - 1;
12133: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12134: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12135: my $name = $cats->[$depth]{$category}[$k];
12136: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12137: my $trailstr = join(' -> ',(@{$parents},$category));
12138: if ($allitems->{$item} eq '') {
12139: push(@{$trails},$trailstr);
12140: $allitems->{$item} = scalar(@{$trails})-1;
12141: }
12142: my $deeper = $depth+1;
12143: push(@{$parents},$category);
12144: if (ref($subcats) eq 'HASH') {
12145: my $subcat = &escape($name).':'.$category.':'.$depth;
12146: for (my $j=@{$parents}; $j>=0; $j--) {
12147: my $higher;
12148: if ($j > 0) {
12149: $higher = &escape($parents->[$j]).':'.
12150: &escape($parents->[$j-1]).':'.$j;
12151: } else {
12152: $higher = &escape($parents->[$j]).'::'.$j;
12153: }
12154: push(@{$subcats->{$higher}},$subcat);
12155: }
12156: }
12157: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
12158: $subcats);
12159: pop(@{$parents});
12160: }
12161: } else {
12162: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12163: my $trailstr = join(' -> ',(@{$parents},$category));
12164: if ($allitems->{$item} eq '') {
12165: push(@{$trails},$trailstr);
12166: $allitems->{$item} = scalar(@{$trails})-1;
12167: }
12168: }
12169: return;
12170: }
12171:
12172: =pod
12173:
12174: =item *&assign_categories_table()
12175:
12176: Create a datatable for display of hierarchical categories in a domain,
12177: with checkboxes to allow a course to be categorized.
12178:
12179: Inputs:
12180:
12181: cathash - reference to hash of categories defined for the domain (from
12182: configuration.db)
12183:
12184: currcat - scalar with an & separated list of categories assigned to a course.
12185:
12186: type - scalar contains course type (Course or Community).
12187:
12188: Returns: $output (markup to be displayed)
12189:
12190: =cut
12191:
12192: sub assign_categories_table {
12193: my ($cathash,$currcat,$type) = @_;
12194: my $output;
12195: if (ref($cathash) eq 'HASH') {
12196: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
12197: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
12198: $maxdepth = scalar(@cats);
12199: if (@cats > 0) {
12200: my $itemcount = 0;
12201: if (ref($cats[0]) eq 'ARRAY') {
12202: my @currcategories;
12203: if ($currcat ne '') {
12204: @currcategories = split('&',$currcat);
12205: }
12206: my $table;
12207: for (my $i=0; $i<@{$cats[0]}; $i++) {
12208: my $parent = $cats[0][$i];
12209: next if ($parent eq 'instcode');
12210: if ($type eq 'Community') {
12211: next unless ($parent eq 'communities');
12212: } else {
12213: next if ($parent eq 'communities');
12214: }
12215: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12216: my $item = &escape($parent).'::0';
12217: my $checked = '';
12218: if (@currcategories > 0) {
12219: if (grep(/^\Q$item\E$/,@currcategories)) {
12220: $checked = ' checked="checked"';
12221: }
12222: }
12223: my $parent_title = $parent;
12224: if ($parent eq 'communities') {
12225: $parent_title = &mt('Communities');
12226: }
12227: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
12228: '<input type="checkbox" name="usecategory" value="'.
12229: $item.'"'.$checked.' />'.$parent_title.'</span>'.
12230: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
12231: my $depth = 1;
12232: push(@path,$parent);
12233: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
12234: pop(@path);
12235: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
12236: $itemcount ++;
12237: }
12238: if ($itemcount) {
12239: $output = &Apache::loncommon::start_data_table().
12240: $table.
12241: &Apache::loncommon::end_data_table();
12242: }
12243: }
12244: }
12245: }
12246: return $output;
12247: }
12248:
12249: =pod
12250:
12251: =item *&assign_category_rows()
12252:
12253: Create a datatable row for display of nested categories in a domain,
12254: with checkboxes to allow a course to be categorized,called recursively.
12255:
12256: Inputs:
12257:
12258: itemcount - track row number for alternating colors
12259:
12260: cats - reference to array of arrays/hashes which encapsulates hierarchy of
12261: categories and subcategories.
12262:
12263: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
12264:
12265: parent - parent of current category item
12266:
12267: path - Array containing all categories back up through the hierarchy from the
12268: current category to the top level.
12269:
12270: currcategories - reference to array of current categories assigned to the course
12271:
12272: Returns: $output (markup to be displayed).
12273:
12274: =cut
12275:
12276: sub assign_category_rows {
12277: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
12278: my ($text,$name,$item,$chgstr);
12279: if (ref($cats) eq 'ARRAY') {
12280: my $maxdepth = scalar(@{$cats});
12281: if (ref($cats->[$depth]) eq 'HASH') {
12282: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
12283: my $numchildren = @{$cats->[$depth]{$parent}};
12284: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
12285: $text .= '<td><table class="LC_datatable">';
12286: for (my $j=0; $j<$numchildren; $j++) {
12287: $name = $cats->[$depth]{$parent}[$j];
12288: $item = &escape($name).':'.&escape($parent).':'.$depth;
12289: my $deeper = $depth+1;
12290: my $checked = '';
12291: if (ref($currcategories) eq 'ARRAY') {
12292: if (@{$currcategories} > 0) {
12293: if (grep(/^\Q$item\E$/,@{$currcategories})) {
12294: $checked = ' checked="checked"';
12295: }
12296: }
12297: }
12298: $text .= '<tr><td><span class="LC_nobreak"><label>'.
12299: '<input type="checkbox" name="usecategory" value="'.
12300: $item.'"'.$checked.' />'.$name.'</label></span>'.
12301: '<input type="hidden" name="catname" value="'.$name.'" />'.
12302: '</td><td>';
12303: if (ref($path) eq 'ARRAY') {
12304: push(@{$path},$name);
12305: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
12306: pop(@{$path});
12307: }
12308: $text .= '</td></tr>';
12309: }
12310: $text .= '</table></td>';
12311: }
12312: }
12313: }
12314: return $text;
12315: }
12316:
12317: ############################################################
12318: ############################################################
12319:
12320:
12321: sub commit_customrole {
12322: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
12323: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
12324: ($start?', '.&mt('starting').' '.localtime($start):'').
12325: ($end?', ending '.localtime($end):'').': <b>'.
12326: &Apache::lonnet::assigncustomrole(
12327: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
12328: '</b><br />';
12329: return $output;
12330: }
12331:
12332: sub commit_standardrole {
12333: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
12334: my ($output,$logmsg,$linefeed);
12335: if ($context eq 'auto') {
12336: $linefeed = "\n";
12337: } else {
12338: $linefeed = "<br />\n";
12339: }
12340: if ($three eq 'st') {
12341: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
12342: $one,$two,$sec,$context);
12343: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
12344: ($result eq 'unknown_course') || ($result eq 'refused')) {
12345: $output = $logmsg.' '.&mt('Error: ').$result."\n";
12346: } else {
12347: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
12348: ($start?', '.&mt('starting').' '.localtime($start):'').
12349: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
12350: if ($context eq 'auto') {
12351: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
12352: } else {
12353: $output .= '<b>'.$result.'</b>'.$linefeed.
12354: &mt('Add to classlist').': <b>ok</b>';
12355: }
12356: $output .= $linefeed;
12357: }
12358: } else {
12359: $output = &mt('Assigning').' '.$three.' in '.$url.
12360: ($start?', '.&mt('starting').' '.localtime($start):'').
12361: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
12362: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
12363: if ($context eq 'auto') {
12364: $output .= $result.$linefeed;
12365: } else {
12366: $output .= '<b>'.$result.'</b>'.$linefeed;
12367: }
12368: }
12369: return $output;
12370: }
12371:
12372: sub commit_studentrole {
12373: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
12374: my ($result,$linefeed,$oldsecurl,$newsecurl);
12375: if ($context eq 'auto') {
12376: $linefeed = "\n";
12377: } else {
12378: $linefeed = '<br />'."\n";
12379: }
12380: if (defined($one) && defined($two)) {
12381: my $cid=$one.'_'.$two;
12382: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
12383: my $secchange = 0;
12384: my $expire_role_result;
12385: my $modify_section_result;
12386: if ($oldsec ne '-1') {
12387: if ($oldsec ne $sec) {
12388: $secchange = 1;
12389: my $now = time;
12390: my $uurl='/'.$cid;
12391: $uurl=~s/\_/\//g;
12392: if ($oldsec) {
12393: $uurl.='/'.$oldsec;
12394: }
12395: $oldsecurl = $uurl;
12396: $expire_role_result =
12397: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
12398: if ($env{'request.course.sec'} ne '') {
12399: if ($expire_role_result eq 'refused') {
12400: my @roles = ('st');
12401: my @statuses = ('previous');
12402: my @roledoms = ($one);
12403: my $withsec = 1;
12404: my %roleshash =
12405: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
12406: \@statuses,\@roles,\@roledoms,$withsec);
12407: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
12408: my ($oldstart,$oldend) =
12409: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
12410: if ($oldend > 0 && $oldend <= $now) {
12411: $expire_role_result = 'ok';
12412: }
12413: }
12414: }
12415: }
12416: $result = $expire_role_result;
12417: }
12418: }
12419: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
12420: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
12421: if ($modify_section_result =~ /^ok/) {
12422: if ($secchange == 1) {
12423: if ($sec eq '') {
12424: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
12425: } else {
12426: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
12427: }
12428: } elsif ($oldsec eq '-1') {
12429: if ($sec eq '') {
12430: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
12431: } else {
12432: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12433: }
12434: } else {
12435: if ($sec eq '') {
12436: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
12437: } else {
12438: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12439: }
12440: }
12441: } else {
12442: if ($secchange) {
12443: $$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;
12444: } else {
12445: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
12446: }
12447: }
12448: $result = $modify_section_result;
12449: } elsif ($secchange == 1) {
12450: if ($oldsec eq '') {
12451: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
12452: } else {
12453: $$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;
12454: }
12455: if ($expire_role_result eq 'refused') {
12456: my $newsecurl = '/'.$cid;
12457: $newsecurl =~ s/\_/\//g;
12458: if ($sec ne '') {
12459: $newsecurl.='/'.$sec;
12460: }
12461: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
12462: if ($sec eq '') {
12463: $$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;
12464: } else {
12465: $$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;
12466: }
12467: }
12468: }
12469: }
12470: } else {
12471: $$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;
12472: $result = "error: incomplete course id\n";
12473: }
12474: return $result;
12475: }
12476:
12477: ############################################################
12478: ############################################################
12479:
12480: sub check_clone {
12481: my ($args,$linefeed) = @_;
12482: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
12483: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
12484: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
12485: my $clonemsg;
12486: my $can_clone = 0;
12487: my $lctype = lc($args->{'crstype'});
12488: if ($lctype ne 'community') {
12489: $lctype = 'course';
12490: }
12491: if ($clonehome eq 'no_host') {
12492: if ($args->{'crstype'} eq 'Community') {
12493: $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'});
12494: } else {
12495: $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'});
12496: }
12497: } else {
12498: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
12499: if ($args->{'crstype'} eq 'Community') {
12500: if ($clonedesc{'type'} ne 'Community') {
12501: $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'});
12502: return ($can_clone, $clonemsg, $cloneid, $clonehome);
12503: }
12504: }
12505: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
12506: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
12507: $can_clone = 1;
12508: } else {
12509: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
12510: $args->{'clonedomain'},$args->{'clonecourse'});
12511: my @cloners = split(/,/,$clonehash{'cloners'});
12512: if (grep(/^\*$/,@cloners)) {
12513: $can_clone = 1;
12514: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
12515: $can_clone = 1;
12516: } else {
12517: my $ccrole = 'cc';
12518: if ($args->{'crstype'} eq 'Community') {
12519: $ccrole = 'co';
12520: }
12521: my %roleshash =
12522: &Apache::lonnet::get_my_roles($args->{'ccuname'},
12523: $args->{'ccdomain'},
12524: 'userroles',['active'],[$ccrole],
12525: [$args->{'clonedomain'}]);
12526: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
12527: $can_clone = 1;
12528: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
12529: $can_clone = 1;
12530: } else {
12531: if ($args->{'crstype'} eq 'Community') {
12532: $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'});
12533: } else {
12534: $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'});
12535: }
12536: }
12537: }
12538: }
12539: }
12540: return ($can_clone, $clonemsg, $cloneid, $clonehome);
12541: }
12542:
12543: sub construct_course {
12544: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
12545: my $outcome;
12546: my $linefeed = '<br />'."\n";
12547: if ($context eq 'auto') {
12548: $linefeed = "\n";
12549: }
12550:
12551: #
12552: # Are we cloning?
12553: #
12554: my ($can_clone, $clonemsg, $cloneid, $clonehome);
12555: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
12556: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
12557: if ($context ne 'auto') {
12558: if ($clonemsg ne '') {
12559: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
12560: }
12561: }
12562: $outcome .= $clonemsg.$linefeed;
12563:
12564: if (!$can_clone) {
12565: return (0,$outcome);
12566: }
12567: }
12568:
12569: #
12570: # Open course
12571: #
12572: my $crstype = lc($args->{'crstype'});
12573: my %cenv=();
12574: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
12575: $args->{'cdescr'},
12576: $args->{'curl'},
12577: $args->{'course_home'},
12578: $args->{'nonstandard'},
12579: $args->{'crscode'},
12580: $args->{'ccuname'}.':'.
12581: $args->{'ccdomain'},
12582: $args->{'crstype'},
12583: $cnum,$context,$category);
12584:
12585: # Note: The testing routines depend on this being output; see
12586: # Utils::Course. This needs to at least be output as a comment
12587: # if anyone ever decides to not show this, and Utils::Course::new
12588: # will need to be suitably modified.
12589: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
12590: if ($$courseid =~ /^error:/) {
12591: return (0,$outcome);
12592: }
12593:
12594: #
12595: # Check if created correctly
12596: #
12597: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
12598: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
12599: if ($crsuhome eq 'no_host') {
12600: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
12601: return (0,$outcome);
12602: }
12603: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
12604:
12605: #
12606: # Do the cloning
12607: #
12608: if ($can_clone && $cloneid) {
12609: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
12610: if ($context ne 'auto') {
12611: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
12612: }
12613: $outcome .= $clonemsg.$linefeed;
12614: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
12615: # Copy all files
12616: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
12617: # Restore URL
12618: $cenv{'url'}=$oldcenv{'url'};
12619: # Restore title
12620: $cenv{'description'}=$oldcenv{'description'};
12621: # Restore creation date, creator and creation context.
12622: $cenv{'internal.created'}=$oldcenv{'internal.created'};
12623: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
12624: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
12625: # Mark as cloned
12626: $cenv{'clonedfrom'}=$cloneid;
12627: # Need to clone grading mode
12628: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
12629: $cenv{'grading'}=$newenv{'grading'};
12630: # Do not clone these environment entries
12631: &Apache::lonnet::del('environment',
12632: ['default_enrollment_start_date',
12633: 'default_enrollment_end_date',
12634: 'question.email',
12635: 'policy.email',
12636: 'comment.email',
12637: 'pch.users.denied',
12638: 'plc.users.denied',
12639: 'hidefromcat',
12640: 'categories'],
12641: $$crsudom,$$crsunum);
12642: }
12643:
12644: #
12645: # Set environment (will override cloned, if existing)
12646: #
12647: my @sections = ();
12648: my @xlists = ();
12649: if ($args->{'crstype'}) {
12650: $cenv{'type'}=$args->{'crstype'};
12651: }
12652: if ($args->{'crsid'}) {
12653: $cenv{'courseid'}=$args->{'crsid'};
12654: }
12655: if ($args->{'crscode'}) {
12656: $cenv{'internal.coursecode'}=$args->{'crscode'};
12657: }
12658: if ($args->{'crsquota'} ne '') {
12659: $cenv{'internal.coursequota'}=$args->{'crsquota'};
12660: } else {
12661: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
12662: }
12663: if ($args->{'ccuname'}) {
12664: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
12665: ':'.$args->{'ccdomain'};
12666: } else {
12667: $cenv{'internal.courseowner'} = $args->{'curruser'};
12668: }
12669: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
12670: if ($args->{'crssections'}) {
12671: $cenv{'internal.sectionnums'} = '';
12672: if ($args->{'crssections'} =~ m/,/) {
12673: @sections = split/,/,$args->{'crssections'};
12674: } else {
12675: $sections[0] = $args->{'crssections'};
12676: }
12677: if (@sections > 0) {
12678: foreach my $item (@sections) {
12679: my ($sec,$gp) = split/:/,$item;
12680: my $class = $args->{'crscode'}.$sec;
12681: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
12682: $cenv{'internal.sectionnums'} .= $item.',';
12683: unless ($addcheck eq 'ok') {
12684: push @badclasses, $class;
12685: }
12686: }
12687: $cenv{'internal.sectionnums'} =~ s/,$//;
12688: }
12689: }
12690: # do not hide course coordinator from staff listing,
12691: # even if privileged
12692: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12693: # add crosslistings
12694: if ($args->{'crsxlist'}) {
12695: $cenv{'internal.crosslistings'}='';
12696: if ($args->{'crsxlist'} =~ m/,/) {
12697: @xlists = split/,/,$args->{'crsxlist'};
12698: } else {
12699: $xlists[0] = $args->{'crsxlist'};
12700: }
12701: if (@xlists > 0) {
12702: foreach my $item (@xlists) {
12703: my ($xl,$gp) = split/:/,$item;
12704: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
12705: $cenv{'internal.crosslistings'} .= $item.',';
12706: unless ($addcheck eq 'ok') {
12707: push @badclasses, $xl;
12708: }
12709: }
12710: $cenv{'internal.crosslistings'} =~ s/,$//;
12711: }
12712: }
12713: if ($args->{'autoadds'}) {
12714: $cenv{'internal.autoadds'}=$args->{'autoadds'};
12715: }
12716: if ($args->{'autodrops'}) {
12717: $cenv{'internal.autodrops'}=$args->{'autodrops'};
12718: }
12719: # check for notification of enrollment changes
12720: my @notified = ();
12721: if ($args->{'notify_owner'}) {
12722: if ($args->{'ccuname'} ne '') {
12723: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
12724: }
12725: }
12726: if ($args->{'notify_dc'}) {
12727: if ($uname ne '') {
12728: push(@notified,$uname.':'.$udom);
12729: }
12730: }
12731: if (@notified > 0) {
12732: my $notifylist;
12733: if (@notified > 1) {
12734: $notifylist = join(',',@notified);
12735: } else {
12736: $notifylist = $notified[0];
12737: }
12738: $cenv{'internal.notifylist'} = $notifylist;
12739: }
12740: if (@badclasses > 0) {
12741: my %lt=&Apache::lonlocal::texthash(
12742: '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',
12743: 'dnhr' => 'does not have rights to access enrollment in these classes',
12744: 'adby' => 'as determined by the policies of your institution on access to official classlists'
12745: );
12746: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
12747: ' ('.$lt{'adby'}.')';
12748: if ($context eq 'auto') {
12749: $outcome .= $badclass_msg.$linefeed;
12750: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
12751: foreach my $item (@badclasses) {
12752: if ($context eq 'auto') {
12753: $outcome .= " - $item\n";
12754: } else {
12755: $outcome .= "<li>$item</li>\n";
12756: }
12757: }
12758: if ($context eq 'auto') {
12759: $outcome .= $linefeed;
12760: } else {
12761: $outcome .= "</ul><br /><br /></div>\n";
12762: }
12763: }
12764: }
12765: if ($args->{'no_end_date'}) {
12766: $args->{'endaccess'} = 0;
12767: }
12768: $cenv{'internal.autostart'}=$args->{'enrollstart'};
12769: $cenv{'internal.autoend'}=$args->{'enrollend'};
12770: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
12771: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
12772: if ($args->{'showphotos'}) {
12773: $cenv{'internal.showphotos'}=$args->{'showphotos'};
12774: }
12775: $cenv{'internal.authtype'} = $args->{'authtype'};
12776: $cenv{'internal.autharg'} = $args->{'autharg'};
12777: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
12778: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
12779: 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');
12780: if ($context eq 'auto') {
12781: $outcome .= $krb_msg;
12782: } else {
12783: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
12784: }
12785: $outcome .= $linefeed;
12786: }
12787: }
12788: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
12789: if ($args->{'setpolicy'}) {
12790: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12791: }
12792: if ($args->{'setcontent'}) {
12793: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12794: }
12795: }
12796: if ($args->{'reshome'}) {
12797: $cenv{'reshome'}=$args->{'reshome'}.'/';
12798: $cenv{'reshome'}=~s/\/+$/\//;
12799: }
12800: #
12801: # course has keyed access
12802: #
12803: if ($args->{'setkeys'}) {
12804: $cenv{'keyaccess'}='yes';
12805: }
12806: # if specified, key authority is not course, but user
12807: # only active if keyaccess is yes
12808: if ($args->{'keyauth'}) {
12809: my ($user,$domain) = split(':',$args->{'keyauth'});
12810: $user = &LONCAPA::clean_username($user);
12811: $domain = &LONCAPA::clean_username($domain);
12812: if ($user ne '' && $domain ne '') {
12813: $cenv{'keyauth'}=$user.':'.$domain;
12814: }
12815: }
12816:
12817: if ($args->{'disresdis'}) {
12818: $cenv{'pch.roles.denied'}='st';
12819: }
12820: if ($args->{'disablechat'}) {
12821: $cenv{'plc.roles.denied'}='st';
12822: }
12823:
12824: # Record we've not yet viewed the Course Initialization Helper for this
12825: # course
12826: $cenv{'course.helper.not.run'} = 1;
12827: #
12828: # Use new Randomseed
12829: #
12830: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
12831: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
12832: #
12833: # The encryption code and receipt prefix for this course
12834: #
12835: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
12836: $cenv{'internal.encpref'}=100+int(9*rand(99));
12837: #
12838: # By default, use standard grading
12839: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
12840:
12841: $outcome .= $linefeed.&mt('Setting environment').': '.
12842: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
12843: #
12844: # Open all assignments
12845: #
12846: if ($args->{'openall'}) {
12847: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
12848: my %storecontent = ($storeunder => time,
12849: $storeunder.'.type' => 'date_start');
12850:
12851: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
12852: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
12853: }
12854: #
12855: # Set first page
12856: #
12857: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
12858: || ($cloneid)) {
12859: use LONCAPA::map;
12860: $outcome .= &mt('Setting first resource').': ';
12861:
12862: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
12863: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
12864:
12865: $outcome .= ($fatal?$errtext:'read ok').' - ';
12866: my $title; my $url;
12867: if ($args->{'firstres'} eq 'syl') {
12868: $title=&mt('Syllabus');
12869: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
12870: } else {
12871: $title=&mt('Table of Contents');
12872: $url='/adm/navmaps';
12873: }
12874:
12875: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
12876: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
12877:
12878: if ($errtext) { $fatal=2; }
12879: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
12880: }
12881:
12882: return (1,$outcome);
12883: }
12884:
12885: ############################################################
12886: ############################################################
12887:
12888: #SD
12889: # only Community and Course, or anything else?
12890: sub course_type {
12891: my ($cid) = @_;
12892: if (!defined($cid)) {
12893: $cid = $env{'request.course.id'};
12894: }
12895: if (defined($env{'course.'.$cid.'.type'})) {
12896: return $env{'course.'.$cid.'.type'};
12897: } else {
12898: return 'Course';
12899: }
12900: }
12901:
12902: sub group_term {
12903: my $crstype = &course_type();
12904: my %names = (
12905: 'Course' => 'group',
12906: 'Community' => 'group',
12907: );
12908: return $names{$crstype};
12909: }
12910:
12911: sub course_types {
12912: my @types = ('official','unofficial','community');
12913: my %typename = (
12914: official => 'Official course',
12915: unofficial => 'Unofficial course',
12916: community => 'Community',
12917: );
12918: return (\@types,\%typename);
12919: }
12920:
12921: sub icon {
12922: my ($file)=@_;
12923: my $curfext = lc((split(/\./,$file))[-1]);
12924: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
12925: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
12926: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
12927: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
12928: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
12929: $curfext.".gif") {
12930: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
12931: $curfext.".gif";
12932: }
12933: }
12934: return &lonhttpdurl($iconname);
12935: }
12936:
12937: sub lonhttpdurl {
12938: #
12939: # Had been used for "small fry" static images on separate port 8080.
12940: # Modify here if lightweight http functionality desired again.
12941: # Currently eliminated due to increasing firewall issues.
12942: #
12943: my ($url)=@_;
12944: return $url;
12945: }
12946:
12947: sub connection_aborted {
12948: my ($r)=@_;
12949: $r->print(" ");$r->rflush();
12950: my $c = $r->connection;
12951: return $c->aborted();
12952: }
12953:
12954: # Escapes strings that may have embedded 's that will be put into
12955: # strings as 'strings'.
12956: sub escape_single {
12957: my ($input) = @_;
12958: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
12959: $input =~ s/\'/\\\'/g; # Esacpe the 's....
12960: return $input;
12961: }
12962:
12963: # Same as escape_single, but escape's "'s This
12964: # can be used for "strings"
12965: sub escape_double {
12966: my ($input) = @_;
12967: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
12968: $input =~ s/\"/\\\"/g; # Esacpe the "s....
12969: return $input;
12970: }
12971:
12972: # Escapes the last element of a full URL.
12973: sub escape_url {
12974: my ($url) = @_;
12975: my @urlslices = split(/\//, $url,-1);
12976: my $lastitem = &escape(pop(@urlslices));
12977: return join('/',@urlslices).'/'.$lastitem;
12978: }
12979:
12980: sub compare_arrays {
12981: my ($arrayref1,$arrayref2) = @_;
12982: my (@difference,%count);
12983: @difference = ();
12984: %count = ();
12985: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
12986: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
12987: foreach my $element (keys(%count)) {
12988: if ($count{$element} == 1) {
12989: push(@difference,$element);
12990: }
12991: }
12992: }
12993: return @difference;
12994: }
12995:
12996: # -------------------------------------------------------- Initialize user login
12997: sub init_user_environment {
12998: my ($r, $username, $domain, $authhost, $form, $args) = @_;
12999: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13000:
13001: my $public=($username eq 'public' && $domain eq 'public');
13002:
13003: # See if old ID present, if so, remove
13004:
13005: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13006: my $now=time;
13007:
13008: if ($public) {
13009: my $max_public=100;
13010: my $oldest;
13011: my $oldest_time=0;
13012: for(my $next=1;$next<=$max_public;$next++) {
13013: if (-e $lonids."/publicuser_$next.id") {
13014: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13015: if ($mtime<$oldest_time || !$oldest_time) {
13016: $oldest_time=$mtime;
13017: $oldest=$next;
13018: }
13019: } else {
13020: $cookie="publicuser_$next";
13021: last;
13022: }
13023: }
13024: if (!$cookie) { $cookie="publicuser_$oldest"; }
13025: } else {
13026: # if this isn't a robot, kill any existing non-robot sessions
13027: if (!$args->{'robot'}) {
13028: opendir(DIR,$lonids);
13029: while ($filename=readdir(DIR)) {
13030: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13031: unlink($lonids.'/'.$filename);
13032: }
13033: }
13034: closedir(DIR);
13035: }
13036: # Give them a new cookie
13037: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13038: : $now.$$.int(rand(10000)));
13039: $cookie="$username\_$id\_$domain\_$authhost";
13040:
13041: # Initialize roles
13042:
13043: ($userroles,$firstaccenv,$timerintenv) =
13044: &Apache::lonnet::rolesinit($domain,$username,$authhost);
13045: }
13046: # ------------------------------------ Check browser type and MathML capability
13047:
13048: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13049: $clientunicode,$clientos) = &decode_user_agent($r);
13050:
13051: # ------------------------------------------------------------- Get environment
13052:
13053: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13054: my ($tmp) = keys(%userenv);
13055: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13056: } else {
13057: undef(%userenv);
13058: }
13059: if (($userenv{'interface'}) && (!$form->{'interface'})) {
13060: $form->{'interface'}=$userenv{'interface'};
13061: }
13062: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13063:
13064: # --------------- Do not trust query string to be put directly into environment
13065: foreach my $option ('interface','localpath','localres') {
13066: $form->{$option}=~s/[\n\r\=]//gs;
13067: }
13068: # --------------------------------------------------------- Write first profile
13069:
13070: {
13071: my %initial_env =
13072: ("user.name" => $username,
13073: "user.domain" => $domain,
13074: "user.home" => $authhost,
13075: "browser.type" => $clientbrowser,
13076: "browser.version" => $clientversion,
13077: "browser.mathml" => $clientmathml,
13078: "browser.unicode" => $clientunicode,
13079: "browser.os" => $clientos,
13080: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
13081: "request.course.fn" => '',
13082: "request.course.uri" => '',
13083: "request.course.sec" => '',
13084: "request.role" => 'cm',
13085: "request.role.adv" => $env{'user.adv'},
13086: "request.host" => $ENV{'REMOTE_ADDR'},);
13087:
13088: if ($form->{'localpath'}) {
13089: $initial_env{"browser.localpath"} = $form->{'localpath'};
13090: $initial_env{"browser.localres"} = $form->{'localres'};
13091: }
13092:
13093: if ($form->{'interface'}) {
13094: $form->{'interface'}=~s/\W//gs;
13095: $initial_env{"browser.interface"} = $form->{'interface'};
13096: $env{'browser.interface'}=$form->{'interface'};
13097: }
13098:
13099: my %is_adv = ( is_adv => $env{'user.adv'} );
13100: my %domdef;
13101: unless ($domain eq 'public') {
13102: %domdef = &Apache::lonnet::get_domain_defaults($domain);
13103: }
13104:
13105: foreach my $tool ('aboutme','blog','portfolio') {
13106: $userenv{'availabletools.'.$tool} =
13107: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13108: undef,\%userenv,\%domdef,\%is_adv);
13109: }
13110:
13111: foreach my $crstype ('official','unofficial','community') {
13112: $userenv{'canrequest.'.$crstype} =
13113: &Apache::lonnet::usertools_access($username,$domain,$crstype,
13114: 'reload','requestcourses',
13115: \%userenv,\%domdef,\%is_adv);
13116: }
13117:
13118: $env{'user.environment'} = "$lonids/$cookie.id";
13119:
13120: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
13121: &GDBM_WRCREAT(),0640)) {
13122: &_add_to_env(\%disk_env,\%initial_env);
13123: &_add_to_env(\%disk_env,\%userenv,'environment.');
13124: &_add_to_env(\%disk_env,$userroles);
13125: if (ref($firstaccenv) eq 'HASH') {
13126: &_add_to_env(\%disk_env,$firstaccenv);
13127: }
13128: if (ref($timerintenv) eq 'HASH') {
13129: &_add_to_env(\%disk_env,$timerintenv);
13130: }
13131: if (ref($args->{'extra_env'})) {
13132: &_add_to_env(\%disk_env,$args->{'extra_env'});
13133: }
13134: untie(%disk_env);
13135: } else {
13136: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
13137: 'Could not create environment storage in lonauth: '.$!.'</span>');
13138: return 'error: '.$!;
13139: }
13140: }
13141: $env{'request.role'}='cm';
13142: $env{'request.role.adv'}=$env{'user.adv'};
13143: $env{'browser.type'}=$clientbrowser;
13144:
13145: return $cookie;
13146:
13147: }
13148:
13149: sub _add_to_env {
13150: my ($idf,$env_data,$prefix) = @_;
13151: if (ref($env_data) eq 'HASH') {
13152: while (my ($key,$value) = each(%$env_data)) {
13153: $idf->{$prefix.$key} = $value;
13154: $env{$prefix.$key} = $value;
13155: }
13156: }
13157: }
13158:
13159: # --- Get the symbolic name of a problem and the url
13160: sub get_symb {
13161: my ($request,$silent) = @_;
13162: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
13163: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
13164: if ($symb eq '') {
13165: if (!$silent) {
13166: $request->print("Unable to handle ambiguous references:$url:.");
13167: return ();
13168: }
13169: }
13170: &Apache::lonenc::check_decrypt(\$symb);
13171: return ($symb);
13172: }
13173:
13174: # --------------------------------------------------------------Get annotation
13175:
13176: sub get_annotation {
13177: my ($symb,$enc) = @_;
13178:
13179: my $key = $symb;
13180: if (!$enc) {
13181: $key =
13182: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
13183: }
13184: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
13185: return $annotation{$key};
13186: }
13187:
13188: sub clean_symb {
13189: my ($symb,$delete_enc) = @_;
13190:
13191: &Apache::lonenc::check_decrypt(\$symb);
13192: my $enc = $env{'request.enc'};
13193: if ($delete_enc) {
13194: delete($env{'request.enc'});
13195: }
13196:
13197: return ($symb,$enc);
13198: }
13199:
13200: sub build_release_hashes {
13201: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
13202: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
13203: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
13204: (ref($randomizetry) eq 'HASH'));
13205: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
13206: my ($item,$name,$value) = split(/:/,$key);
13207: if ($item eq 'parameter') {
13208: if (ref($checkparms->{$name}) eq 'ARRAY') {
13209: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
13210: push(@{$checkparms->{$name}},$value);
13211: }
13212: } else {
13213: push(@{$checkparms->{$name}},$value);
13214: }
13215: } elsif ($item eq 'resourcetag') {
13216: if ($name eq 'responsetype') {
13217: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
13218: }
13219: } elsif ($item eq 'course') {
13220: if ($name eq 'crstype') {
13221: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
13222: }
13223: }
13224: }
13225: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
13226: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
13227: return;
13228: }
13229:
13230: =pod
13231:
13232: =back
13233:
13234: =cut
13235:
13236: 1;
13237: __END__;
13238:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>