File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1059:
download - view:
text,
annotated -
select for diffs
Sat Mar 17 20:11:26 2012 UTC (12 years, 5 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Uploading archive files directly into a course.
- For items to be included as files or folders, can specify title
to be used for item within a .sequence file.
- Default for top level item in archive is title entered in comment field
on itital upload page.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1059 2012/03/17 20:11:26 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) = @_;
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 %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
4092: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
4093: return ($startblock,$endblock);
4094: }
4095:
4096: my $startblock = 0;
4097: my $endblock = 0;
4098: my %live_courses = &findallcourses(undef,$uname,$udom);
4099:
4100: # If uname is for a user, and activity is course-specific, i.e.,
4101: # boards, chat or groups, check for blocking in current course only.
4102:
4103: if (($activity eq 'boards' || $activity eq 'chat' ||
4104: $activity eq 'groups') && ($env{'request.course.id'})) {
4105: foreach my $key (keys(%live_courses)) {
4106: if ($key ne $env{'request.course.id'}) {
4107: delete($live_courses{$key});
4108: }
4109: }
4110: }
4111:
4112: my $otheruser = 0;
4113: my %own_courses;
4114: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4115: # Resource belongs to user other than current user.
4116: $otheruser = 1;
4117: # Gather courses for current user
4118: %own_courses =
4119: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4120: }
4121:
4122: # Gather active course roles - course coordinator, instructor,
4123: # exam proctor, ta, student, or custom role.
4124:
4125: foreach my $course (keys(%live_courses)) {
4126: my ($cdom,$cnum);
4127: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4128: $cdom = $env{'course.'.$course.'.domain'};
4129: $cnum = $env{'course.'.$course.'.num'};
4130: } else {
4131: ($cdom,$cnum) = split(/_/,$course);
4132: }
4133: my $no_ownblock = 0;
4134: my $no_userblock = 0;
4135: if ($otheruser && $activity ne 'com') {
4136: # Check if current user has 'evb' priv for this
4137: if (defined($own_courses{$course})) {
4138: foreach my $sec (keys(%{$own_courses{$course}})) {
4139: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4140: if ($sec ne 'none') {
4141: $checkrole .= '/'.$sec;
4142: }
4143: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4144: $no_ownblock = 1;
4145: last;
4146: }
4147: }
4148: }
4149: # if they have 'evb' priv and are currently not playing student
4150: next if (($no_ownblock) &&
4151: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4152: }
4153: foreach my $sec (keys(%{$live_courses{$course}})) {
4154: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4155: if ($sec ne 'none') {
4156: $checkrole .= '/'.$sec;
4157: }
4158: if ($otheruser) {
4159: # Resource belongs to user other than current user.
4160: # Assemble privs for that user, and check for 'evb' priv.
4161: my (%allroles,%userroles);
4162: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4163: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4164: my ($trole,$tdom,$tnum,$tsec);
4165: if ($entry =~ /^cr/) {
4166: ($trole,$tdom,$tnum,$tsec) =
4167: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4168: } else {
4169: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4170: }
4171: my ($spec,$area,$trest);
4172: $area = '/'.$tdom.'/'.$tnum;
4173: $trest = $tnum;
4174: if ($tsec ne '') {
4175: $area .= '/'.$tsec;
4176: $trest .= '/'.$tsec;
4177: }
4178: $spec = $trole.'.'.$area;
4179: if ($trole =~ /^cr/) {
4180: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4181: $tdom,$spec,$trest,$area);
4182: } else {
4183: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4184: $tdom,$spec,$trest,$area);
4185: }
4186: }
4187: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4188: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4189: if ($1) {
4190: $no_userblock = 1;
4191: last;
4192: }
4193: }
4194: }
4195: } else {
4196: # Resource belongs to current user
4197: # Check for 'evb' priv via lonnet::allowed().
4198: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4199: $no_ownblock = 1;
4200: last;
4201: }
4202: }
4203: }
4204: # if they have the evb priv and are currently not playing student
4205: next if (($no_ownblock) &&
4206: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4207: next if ($no_userblock);
4208:
4209: # Retrieve blocking times and identity of locker for course
4210: # of specified user, unless user has 'evb' privilege.
4211:
4212: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
4213: if (($start != 0) &&
4214: (($startblock == 0) || ($startblock > $start))) {
4215: $startblock = $start;
4216: }
4217: if (($end != 0) &&
4218: (($endblock == 0) || ($endblock < $end))) {
4219: $endblock = $end;
4220: }
4221: }
4222: return ($startblock,$endblock);
4223: }
4224:
4225: sub get_blocks {
4226: my ($setters,$activity,$cdom,$cnum) = @_;
4227: my $startblock = 0;
4228: my $endblock = 0;
4229: my $course = $cdom.'_'.$cnum;
4230: $setters->{$course} = {};
4231: $setters->{$course}{'staff'} = [];
4232: $setters->{$course}{'times'} = [];
4233: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
4234: foreach my $record (keys(%records)) {
4235: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
4236: if ($start <= time && $end >= time) {
4237: my ($staff_name,$staff_dom,$title,$blocks) =
4238: &parse_block_record($records{$record});
4239: if ($blocks->{$activity} eq 'on') {
4240: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4241: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4242: if ( ($startblock == 0) || ($startblock > $start) ) {
4243: $startblock = $start;
4244: }
4245: if ( ($endblock == 0) || ($endblock < $end) ) {
4246: $endblock = $end;
4247: }
4248: }
4249: }
4250: }
4251: return ($startblock,$endblock);
4252: }
4253:
4254: sub parse_block_record {
4255: my ($record) = @_;
4256: my ($setuname,$setudom,$title,$blocks);
4257: if (ref($record) eq 'HASH') {
4258: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4259: $title = &unescape($record->{'event'});
4260: $blocks = $record->{'blocks'};
4261: } else {
4262: my @data = split(/:/,$record,3);
4263: if (scalar(@data) eq 2) {
4264: $title = $data[1];
4265: ($setuname,$setudom) = split(/@/,$data[0]);
4266: } else {
4267: ($setuname,$setudom,$title) = @data;
4268: }
4269: $blocks = { 'com' => 'on' };
4270: }
4271: return ($setuname,$setudom,$title,$blocks);
4272: }
4273:
4274: sub blocking_status {
4275: my ($activity,$uname,$udom) = @_;
4276: my %setters;
4277:
4278: # check for active blocking
4279: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
4280:
4281: my $blocked = $startblock && $endblock ? 1 : 0;
4282:
4283: # caller just wants to know whether a block is active
4284: if (!wantarray) { return $blocked; }
4285:
4286: # build a link to a popup window containing the details
4287: my $querystring = "?activity=$activity";
4288: # $uname and $udom decide whose portfolio the user is trying to look at
4289: $querystring .= "&udom=$udom" if $udom;
4290: $querystring .= "&uname=$uname" if $uname;
4291:
4292: my $output .= <<'END_MYBLOCK';
4293: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4294: var options = "width=" + w + ",height=" + h + ",";
4295: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4296: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4297: var newWin = window.open(url, wdwName, options);
4298: newWin.focus();
4299: }
4300: END_MYBLOCK
4301:
4302: $output = Apache::lonhtmlcommon::scripttag($output);
4303:
4304: my $popupUrl = "/adm/blockingstatus/$querystring";
4305: my $text = mt('Communication Blocked');
4306:
4307: $output .= <<"END_BLOCK";
4308: <div class='LC_comblock'>
4309: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4310: title='$text'>
4311: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4312: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4313: title='$text'>$text</a>
4314: </div>
4315:
4316: END_BLOCK
4317:
4318: return ($blocked, $output);
4319: }
4320:
4321: ###############################################
4322:
4323: sub check_ip_acc {
4324: my ($acc)=@_;
4325: &Apache::lonxml::debug("acc is $acc");
4326: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4327: return 1;
4328: }
4329: my $allowed=0;
4330: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4331:
4332: my $name;
4333: foreach my $pattern (split(',',$acc)) {
4334: $pattern =~ s/^\s*//;
4335: $pattern =~ s/\s*$//;
4336: if ($pattern =~ /\*$/) {
4337: #35.8.*
4338: $pattern=~s/\*//;
4339: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4340: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4341: #35.8.3.[34-56]
4342: my $low=$2;
4343: my $high=$3;
4344: $pattern=$1;
4345: if ($ip =~ /^\Q$pattern\E/) {
4346: my $last=(split(/\./,$ip))[3];
4347: if ($last <=$high && $last >=$low) { $allowed=1; }
4348: }
4349: } elsif ($pattern =~ /^\*/) {
4350: #*.msu.edu
4351: $pattern=~s/\*//;
4352: if (!defined($name)) {
4353: use Socket;
4354: my $netaddr=inet_aton($ip);
4355: ($name)=gethostbyaddr($netaddr,AF_INET);
4356: }
4357: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4358: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4359: #127.0.0.1
4360: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4361: } else {
4362: #some.name.com
4363: if (!defined($name)) {
4364: use Socket;
4365: my $netaddr=inet_aton($ip);
4366: ($name)=gethostbyaddr($netaddr,AF_INET);
4367: }
4368: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4369: }
4370: if ($allowed) { last; }
4371: }
4372: return $allowed;
4373: }
4374:
4375: ###############################################
4376:
4377: =pod
4378:
4379: =head1 Domain Template Functions
4380:
4381: =over 4
4382:
4383: =item * &determinedomain()
4384:
4385: Inputs: $domain (usually will be undef)
4386:
4387: Returns: Determines which domain should be used for designs
4388:
4389: =cut
4390:
4391: ###############################################
4392: sub determinedomain {
4393: my $domain=shift;
4394: if (! $domain) {
4395: # Determine domain if we have not been given one
4396: $domain = &Apache::lonnet::default_login_domain();
4397: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4398: if ($env{'request.role.domain'}) {
4399: $domain=$env{'request.role.domain'};
4400: }
4401: }
4402: return $domain;
4403: }
4404: ###############################################
4405:
4406: sub devalidate_domconfig_cache {
4407: my ($udom)=@_;
4408: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4409: }
4410:
4411: # ---------------------- Get domain configuration for a domain
4412: sub get_domainconf {
4413: my ($udom) = @_;
4414: my $cachetime=1800;
4415: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4416: if (defined($cached)) { return %{$result}; }
4417:
4418: my %domconfig = &Apache::lonnet::get_dom('configuration',
4419: ['login','rolecolors','autoenroll'],$udom);
4420: my (%designhash,%legacy);
4421: if (keys(%domconfig) > 0) {
4422: if (ref($domconfig{'login'}) eq 'HASH') {
4423: if (keys(%{$domconfig{'login'}})) {
4424: foreach my $key (keys(%{$domconfig{'login'}})) {
4425: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4426: if ($key eq 'loginvia') {
4427: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4428: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4429: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4430: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4431: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4432: $designhash{$udom.'.login.loginvia'} = $server;
4433: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4434:
4435: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4436: } else {
4437: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4438: }
4439: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4440: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4441: }
4442: }
4443: }
4444: }
4445: }
4446: } else {
4447: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4448: $designhash{$udom.'.login.'.$key.'_'.$img} =
4449: $domconfig{'login'}{$key}{$img};
4450: }
4451: }
4452: } else {
4453: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4454: }
4455: }
4456: } else {
4457: $legacy{'login'} = 1;
4458: }
4459: } else {
4460: $legacy{'login'} = 1;
4461: }
4462: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4463: if (keys(%{$domconfig{'rolecolors'}})) {
4464: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4465: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4466: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4467: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4468: }
4469: }
4470: }
4471: } else {
4472: $legacy{'rolecolors'} = 1;
4473: }
4474: } else {
4475: $legacy{'rolecolors'} = 1;
4476: }
4477: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4478: if ($domconfig{'autoenroll'}{'co-owners'}) {
4479: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4480: }
4481: }
4482: if (keys(%legacy) > 0) {
4483: my %legacyhash = &get_legacy_domconf($udom);
4484: foreach my $item (keys(%legacyhash)) {
4485: if ($item =~ /^\Q$udom\E\.login/) {
4486: if ($legacy{'login'}) {
4487: $designhash{$item} = $legacyhash{$item};
4488: }
4489: } else {
4490: if ($legacy{'rolecolors'}) {
4491: $designhash{$item} = $legacyhash{$item};
4492: }
4493: }
4494: }
4495: }
4496: } else {
4497: %designhash = &get_legacy_domconf($udom);
4498: }
4499: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4500: $cachetime);
4501: return %designhash;
4502: }
4503:
4504: sub get_legacy_domconf {
4505: my ($udom) = @_;
4506: my %legacyhash;
4507: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4508: my $designfile = $designdir.'/'.$udom.'.tab';
4509: if (-e $designfile) {
4510: if ( open (my $fh,"<$designfile") ) {
4511: while (my $line = <$fh>) {
4512: next if ($line =~ /^\#/);
4513: chomp($line);
4514: my ($key,$val)=(split(/\=/,$line));
4515: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4516: }
4517: close($fh);
4518: }
4519: }
4520: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4521: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4522: }
4523: return %legacyhash;
4524: }
4525:
4526: =pod
4527:
4528: =item * &domainlogo()
4529:
4530: Inputs: $domain (usually will be undef)
4531:
4532: Returns: A link to a domain logo, if the domain logo exists.
4533: If the domain logo does not exist, a description of the domain.
4534:
4535: =cut
4536:
4537: ###############################################
4538: sub domainlogo {
4539: my $domain = &determinedomain(shift);
4540: my %designhash = &get_domainconf($domain);
4541: # See if there is a logo
4542: if ($designhash{$domain.'.login.domlogo'} ne '') {
4543: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4544: if ($imgsrc =~ m{^/(adm|res)/}) {
4545: if ($imgsrc =~ m{^/res/}) {
4546: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4547: &Apache::lonnet::repcopy($local_name);
4548: }
4549: $imgsrc = &lonhttpdurl($imgsrc);
4550: }
4551: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4552: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4553: return &Apache::lonnet::domain($domain,'description');
4554: } else {
4555: return '';
4556: }
4557: }
4558: ##############################################
4559:
4560: =pod
4561:
4562: =item * &designparm()
4563:
4564: Inputs: $which parameter; $domain (usually will be undef)
4565:
4566: Returns: value of designparamter $which
4567:
4568: =cut
4569:
4570:
4571: ##############################################
4572: sub designparm {
4573: my ($which,$domain)=@_;
4574: if (exists($env{'environment.color.'.$which})) {
4575: return $env{'environment.color.'.$which};
4576: }
4577: $domain=&determinedomain($domain);
4578: my %domdesign;
4579: unless ($domain eq 'public') {
4580: %domdesign = &get_domainconf($domain);
4581: }
4582: my $output;
4583: if ($domdesign{$domain.'.'.$which} ne '') {
4584: $output = $domdesign{$domain.'.'.$which};
4585: } else {
4586: $output = $defaultdesign{$which};
4587: }
4588: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4589: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4590: if ($output =~ m{^/(adm|res)/}) {
4591: if ($output =~ m{^/res/}) {
4592: my $local_name = &Apache::lonnet::filelocation('',$output);
4593: &Apache::lonnet::repcopy($local_name);
4594: }
4595: $output = &lonhttpdurl($output);
4596: }
4597: }
4598: return $output;
4599: }
4600:
4601: ##############################################
4602: =pod
4603:
4604: =item * &authorspace()
4605:
4606: Inputs: $url (usually will be undef).
4607:
4608: Returns: Path to Construction Space containing the resource or
4609: directory being viewed (or for which action is being taken).
4610: If $url is provided, and begins /priv/<domain>/<uname>
4611: the path will be that portion of the $context argument.
4612: Otherwise the path will be for the author space of the current
4613: user when the current role is author, or for that of the
4614: co-author/assistant co-author space when the current role
4615: is co-author or assistant co-author.
4616:
4617: =cut
4618:
4619: sub authorspace {
4620: my ($url) = @_;
4621: if ($url ne '') {
4622: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4623: return $1;
4624: }
4625: }
4626: my $caname = '';
4627: my $cadom = '';
4628: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4629: ($cadom,$caname) =
4630: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4631: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4632: $caname = $env{'user.name'};
4633: $cadom = $env{'user.domain'};
4634: }
4635: if (($caname ne '') && ($cadom ne '')) {
4636: return "/priv/$cadom/$caname/";
4637: }
4638: return;
4639: }
4640:
4641: ##############################################
4642: =pod
4643:
4644: =item * &head_subbox()
4645:
4646: Inputs: $content (contains HTML code with page functions, etc.)
4647:
4648: Returns: HTML div with $content
4649: To be included in page header
4650:
4651: =cut
4652:
4653: sub head_subbox {
4654: my ($content)=@_;
4655: my $output =
4656: '<div class="LC_head_subbox">'
4657: .$content
4658: .'</div>'
4659: }
4660:
4661: ##############################################
4662: =pod
4663:
4664: =item * &CSTR_pageheader()
4665:
4666: Input: (optional) filename from which breadcrumb trail is built.
4667: In most cases no input as needed, as $env{'request.filename'}
4668: is appropriate for use in building the breadcrumb trail.
4669:
4670: Returns: HTML div with CSTR path and recent box
4671: To be included on Construction Space pages
4672:
4673: =cut
4674:
4675: sub CSTR_pageheader {
4676: my ($trailfile) = @_;
4677: if ($trailfile eq '') {
4678: $trailfile = $env{'request.filename'};
4679: }
4680:
4681: # this is for resources; directories have customtitle, and crumbs
4682: # and select recent are created in lonpubdir.pm
4683:
4684: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
4685: my ($udom,$uname,$thisdisfn)=
4686: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
4687: my $formaction = "/priv/$udom/$uname/$thisdisfn";
4688: $formaction =~ s{/+}{/}g;
4689:
4690: my $parentpath = '';
4691: my $lastitem = '';
4692: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4693: $parentpath = $1;
4694: $lastitem = $2;
4695: } else {
4696: $lastitem = $thisdisfn;
4697: }
4698:
4699: my $output =
4700: '<div>'
4701: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4702: .'<b>'.&mt('Construction Space:').'</b> '
4703: .'<form name="dirs" method="post" action="'.$formaction
4704: .'" target="_top">' #FIXME lonpubdir: target="_parent"
4705: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
4706:
4707: if ($lastitem) {
4708: $output .=
4709: '<span class="LC_filename">'
4710: .$lastitem
4711: .'</span>';
4712: }
4713: $output .=
4714: '<br />'
4715: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4716: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4717: .'</form>'
4718: .&Apache::lonmenu::constspaceform()
4719: .'</div>';
4720:
4721: return $output;
4722: }
4723:
4724: ###############################################
4725: ###############################################
4726:
4727: =pod
4728:
4729: =back
4730:
4731: =head1 HTML Helpers
4732:
4733: =over 4
4734:
4735: =item * &bodytag()
4736:
4737: Returns a uniform header for LON-CAPA web pages.
4738:
4739: Inputs:
4740:
4741: =over 4
4742:
4743: =item * $title, A title to be displayed on the page.
4744:
4745: =item * $function, the current role (can be undef).
4746:
4747: =item * $addentries, extra parameters for the <body> tag.
4748:
4749: =item * $bodyonly, if defined, only return the <body> tag.
4750:
4751: =item * $domain, if defined, force a given domain.
4752:
4753: =item * $forcereg, if page should register as content page (relevant for
4754: text interface only)
4755:
4756: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
4757: navigational links
4758:
4759: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4760:
4761: =item * $args, optional argument valid values are
4762: no_auto_mt_title -> prevents &mt()ing the title arg
4763: inherit_jsmath -> when creating popup window in a page,
4764: should it have jsmath forced on by the
4765: current page
4766:
4767: =back
4768:
4769: Returns: A uniform header for LON-CAPA web pages.
4770: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4771: If $bodyonly is undef or zero, an html string containing a <body> tag and
4772: other decorations will be returned.
4773:
4774: =cut
4775:
4776: sub bodytag {
4777: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
4778: $no_nav_bar,$bgcolor,$args)=@_;
4779:
4780: my $public;
4781: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
4782: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
4783: $public = 1;
4784: }
4785: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4786:
4787: $function = &get_users_function() if (!$function);
4788: my $img = &designparm($function.'.img',$domain);
4789: my $font = &designparm($function.'.font',$domain);
4790: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4791:
4792: my %design = ( 'style' => 'margin-top: 0',
4793: 'bgcolor' => $pgbg,
4794: 'text' => $font,
4795: 'alink' => &designparm($function.'.alink',$domain),
4796: 'vlink' => &designparm($function.'.vlink',$domain),
4797: 'link' => &designparm($function.'.link',$domain),);
4798: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4799:
4800: # role and realm
4801: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4802: if ($role eq 'ca') {
4803: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4804: $realm = &plainname($rname,$rdom);
4805: }
4806: # realm
4807: if ($env{'request.course.id'}) {
4808: if ($env{'request.role'} !~ /^cr/) {
4809: $role = &Apache::lonnet::plaintext($role,&course_type());
4810: }
4811: if ($env{'request.course.sec'}) {
4812: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
4813: }
4814: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4815: } else {
4816: $role = &Apache::lonnet::plaintext($role);
4817: }
4818:
4819: if (!$realm) { $realm=' '; }
4820:
4821: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4822:
4823: # construct main body tag
4824: my $bodytag = "<body $extra_body_attr>".
4825: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4826:
4827: if ($bodyonly) {
4828: return $bodytag;
4829: }
4830:
4831: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4832: if ($public) {
4833: undef($role);
4834: } else {
4835: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4836: }
4837:
4838: my $titleinfo = '<h1>'.$title.'</h1>';
4839: #
4840: # Extra info if you are the DC
4841: my $dc_info = '';
4842: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4843: $env{'course.'.$env{'request.course.id'}.
4844: '.domain'}.'/'})) {
4845: my $cid = $env{'request.course.id'};
4846: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4847: $dc_info =~ s/\s+$//;
4848: }
4849:
4850: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
4851: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
4852:
4853: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') {
4854: return $bodytag;
4855: }
4856:
4857: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
4858:
4859: # if ($env{'request.state'} eq 'construct') {
4860: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
4861: # }
4862:
4863:
4864:
4865: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
4866: if ($dc_info) {
4867: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
4868: }
4869: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
4870: <em>$realm</em> $dc_info</div>|;
4871: return $bodytag;
4872: }
4873:
4874: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
4875: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
4876: }
4877:
4878: $bodytag .= Apache::lonhtmlcommon::scripttag(
4879: Apache::lonmenu::utilityfunctions(), 'start');
4880:
4881: $bodytag .= Apache::lonmenu::primary_menu();
4882:
4883: if ($dc_info) {
4884: $dc_info = &dc_courseid_toggle($dc_info);
4885: }
4886: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
4887:
4888: #don't show menus for public users
4889: if (!$public){
4890: $bodytag .= Apache::lonmenu::secondary_menu();
4891: $bodytag .= Apache::lonmenu::serverform();
4892: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4893: if ($env{'request.state'} eq 'construct') {
4894: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
4895: $args->{'bread_crumbs'});
4896: } elsif ($forcereg) {
4897: $bodytag .= &Apache::lonmenu::innerregister($forcereg);
4898: }
4899: }else{
4900: # this is to seperate menu from content when there's no secondary
4901: # menu. Especially needed for public accessible ressources.
4902: $bodytag .= '<hr style="clear:both" />';
4903: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
4904: }
4905:
4906: return $bodytag;
4907: }
4908:
4909: sub dc_courseid_toggle {
4910: my ($dc_info) = @_;
4911: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
4912: '<a href="javascript:showCourseID();">'.
4913: &mt('(More ...)').'</a></span>'.
4914: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
4915: }
4916:
4917: sub make_attr_string {
4918: my ($register,$attr_ref) = @_;
4919:
4920: if ($attr_ref && !ref($attr_ref)) {
4921: die("addentries Must be a hash ref ".
4922: join(':',caller(1))." ".
4923: join(':',caller(0))." ");
4924: }
4925:
4926: if ($register) {
4927: my ($on_load,$on_unload);
4928: foreach my $key (keys(%{$attr_ref})) {
4929: if (lc($key) eq 'onload') {
4930: $on_load.=$attr_ref->{$key}.';';
4931: delete($attr_ref->{$key});
4932:
4933: } elsif (lc($key) eq 'onunload') {
4934: $on_unload.=$attr_ref->{$key}.';';
4935: delete($attr_ref->{$key});
4936: }
4937: }
4938: $attr_ref->{'onload'} = $on_load;
4939: $attr_ref->{'onunload'}= $on_unload;
4940: }
4941:
4942: my $attr_string;
4943: foreach my $attr (keys(%$attr_ref)) {
4944: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4945: }
4946: return $attr_string;
4947: }
4948:
4949:
4950: ###############################################
4951: ###############################################
4952:
4953: =pod
4954:
4955: =item * &endbodytag()
4956:
4957: Returns a uniform footer for LON-CAPA web pages.
4958:
4959: Inputs: 1 - optional reference to an args hash
4960: If in the hash, key for noredirectlink has a value which evaluates to true,
4961: a 'Continue' link is not displayed if the page contains an
4962: internal redirect in the <head></head> section,
4963: i.e., $env{'internal.head.redirect'} exists
4964:
4965: =cut
4966:
4967: sub endbodytag {
4968: my ($args) = @_;
4969: my $endbodytag='</body>';
4970: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4971: if ( exists( $env{'internal.head.redirect'} ) ) {
4972: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4973: $endbodytag=
4974: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4975: &mt('Continue').'</a>'.
4976: $endbodytag;
4977: }
4978: }
4979: return $endbodytag;
4980: }
4981:
4982: =pod
4983:
4984: =item * &standard_css()
4985:
4986: Returns a style sheet
4987:
4988: Inputs: (all optional)
4989: domain -> force to color decorate a page for a specific
4990: domain
4991: function -> force usage of a specific rolish color scheme
4992: bgcolor -> override the default page bgcolor
4993:
4994: =cut
4995:
4996: sub standard_css {
4997: my ($function,$domain,$bgcolor) = @_;
4998: $function = &get_users_function() if (!$function);
4999: my $img = &designparm($function.'.img', $domain);
5000: my $tabbg = &designparm($function.'.tabbg', $domain);
5001: my $font = &designparm($function.'.font', $domain);
5002: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5003: #second colour for later usage
5004: my $sidebg = &designparm($function.'.sidebg',$domain);
5005: my $pgbg_or_bgcolor =
5006: $bgcolor ||
5007: &designparm($function.'.pgbg', $domain);
5008: my $pgbg = &designparm($function.'.pgbg', $domain);
5009: my $alink = &designparm($function.'.alink', $domain);
5010: my $vlink = &designparm($function.'.vlink', $domain);
5011: my $link = &designparm($function.'.link', $domain);
5012:
5013: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5014: my $mono = 'monospace';
5015: my $data_table_head = $sidebg;
5016: my $data_table_light = '#FAFAFA';
5017: my $data_table_dark = '#F0F0F0';
5018: my $data_table_darker = '#CCCCCC';
5019: my $data_table_highlight = '#FFFF00';
5020: my $mail_new = '#FFBB77';
5021: my $mail_new_hover = '#DD9955';
5022: my $mail_read = '#BBBB77';
5023: my $mail_read_hover = '#999944';
5024: my $mail_replied = '#AAAA88';
5025: my $mail_replied_hover = '#888855';
5026: my $mail_other = '#99BBBB';
5027: my $mail_other_hover = '#669999';
5028: my $table_header = '#DDDDDD';
5029: my $feedback_link_bg = '#BBBBBB';
5030: my $lg_border_color = '#C8C8C8';
5031: my $button_hover = '#BF2317';
5032:
5033: my $border = ($env{'browser.type'} eq 'explorer' ||
5034: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5035: : '0 3px 0 4px';
5036:
5037:
5038: return <<END;
5039:
5040: /* needed for iframe to allow 100% height in FF */
5041: body, html {
5042: margin: 0;
5043: padding: 0 0.5%;
5044: height: 99%; /* to avoid scrollbars */
5045: }
5046:
5047: body {
5048: font-family: $sans;
5049: line-height:130%;
5050: font-size:0.83em;
5051: color:$font;
5052: }
5053:
5054: a:focus,
5055: a:focus img {
5056: color: red;
5057: }
5058:
5059: form, .inline {
5060: display: inline;
5061: }
5062:
5063: .LC_right {
5064: text-align:right;
5065: }
5066:
5067: .LC_middle {
5068: vertical-align:middle;
5069: }
5070:
5071: .LC_400Box {
5072: width:400px;
5073: }
5074:
5075: .LC_iframecontainer {
5076: width: 98%;
5077: margin: 0;
5078: position: fixed;
5079: top: 8.5em;
5080: bottom: 0;
5081: }
5082:
5083: .LC_iframecontainer iframe{
5084: border: none;
5085: width: 100%;
5086: height: 100%;
5087: }
5088:
5089: .LC_filename {
5090: font-family: $mono;
5091: white-space:pre;
5092: font-size: 120%;
5093: }
5094:
5095: .LC_fileicon {
5096: border: none;
5097: height: 1.3em;
5098: vertical-align: text-bottom;
5099: margin-right: 0.3em;
5100: text-decoration:none;
5101: }
5102:
5103: .LC_setting {
5104: text-decoration:underline;
5105: }
5106:
5107: .LC_error {
5108: color: red;
5109: font-size: larger;
5110: }
5111:
5112: .LC_warning,
5113: .LC_diff_removed {
5114: color: red;
5115: }
5116:
5117: .LC_info,
5118: .LC_success,
5119: .LC_diff_added {
5120: color: green;
5121: }
5122:
5123: div.LC_confirm_box {
5124: background-color: #FAFAFA;
5125: border: 1px solid $lg_border_color;
5126: margin-right: 0;
5127: padding: 5px;
5128: }
5129:
5130: div.LC_confirm_box .LC_error img,
5131: div.LC_confirm_box .LC_success img {
5132: vertical-align: middle;
5133: }
5134:
5135: .LC_icon {
5136: border: none;
5137: vertical-align: middle;
5138: }
5139:
5140: .LC_docs_spacer {
5141: width: 25px;
5142: height: 1px;
5143: border: none;
5144: }
5145:
5146: .LC_internal_info {
5147: color: #999999;
5148: }
5149:
5150: .LC_discussion {
5151: background: $data_table_dark;
5152: border: 1px solid black;
5153: margin: 2px;
5154: }
5155:
5156: .LC_disc_action_left {
5157: background: $sidebg;
5158: text-align: left;
5159: padding: 4px;
5160: margin: 2px;
5161: }
5162:
5163: .LC_disc_action_right {
5164: background: $sidebg;
5165: text-align: right;
5166: padding: 4px;
5167: margin: 2px;
5168: }
5169:
5170: .LC_disc_new_item {
5171: background: white;
5172: border: 2px solid red;
5173: margin: 4px;
5174: padding: 4px;
5175: }
5176:
5177: .LC_disc_old_item {
5178: background: white;
5179: margin: 4px;
5180: padding: 4px;
5181: }
5182:
5183: table.LC_pastsubmission {
5184: border: 1px solid black;
5185: margin: 2px;
5186: }
5187:
5188: table#LC_menubuttons {
5189: width: 100%;
5190: background: $pgbg;
5191: border: 2px;
5192: border-collapse: separate;
5193: padding: 0;
5194: }
5195:
5196: table#LC_title_bar a {
5197: color: $fontmenu;
5198: }
5199:
5200: table#LC_title_bar {
5201: clear: both;
5202: display: none;
5203: }
5204:
5205: table#LC_title_bar,
5206: table.LC_breadcrumbs, /* obsolete? */
5207: table#LC_title_bar.LC_with_remote {
5208: width: 100%;
5209: border-color: $pgbg;
5210: border-style: solid;
5211: border-width: $border;
5212: background: $pgbg;
5213: color: $fontmenu;
5214: border-collapse: collapse;
5215: padding: 0;
5216: margin: 0;
5217: }
5218:
5219: ul.LC_breadcrumb_tools_outerlist {
5220: margin: 0;
5221: padding: 0;
5222: position: relative;
5223: list-style: none;
5224: }
5225: ul.LC_breadcrumb_tools_outerlist li {
5226: display: inline;
5227: }
5228:
5229: .LC_breadcrumb_tools_navigation {
5230: padding: 0;
5231: margin: 0;
5232: float: left;
5233: }
5234: .LC_breadcrumb_tools_tools {
5235: padding: 0;
5236: margin: 0;
5237: float: right;
5238: }
5239:
5240: table#LC_title_bar td {
5241: background: $tabbg;
5242: }
5243:
5244: table#LC_menubuttons img {
5245: border: none;
5246: }
5247:
5248: .LC_breadcrumbs_component {
5249: float: right;
5250: margin: 0 1em;
5251: }
5252: .LC_breadcrumbs_component img {
5253: vertical-align: middle;
5254: }
5255:
5256: td.LC_table_cell_checkbox {
5257: text-align: center;
5258: }
5259:
5260: .LC_fontsize_small {
5261: font-size: 70%;
5262: }
5263:
5264: #LC_breadcrumbs {
5265: clear:both;
5266: background: $sidebg;
5267: border-bottom: 1px solid $lg_border_color;
5268: line-height: 2.5em;
5269: overflow: hidden;
5270: margin: 0;
5271: padding: 0;
5272: text-align: left;
5273: }
5274:
5275: .LC_head_subbox {
5276: clear:both;
5277: background: #F8F8F8; /* $sidebg; */
5278: border: 1px solid $sidebg;
5279: margin: 0 0 10px 0;
5280: padding: 3px;
5281: text-align: left;
5282: }
5283:
5284: .LC_fontsize_medium {
5285: font-size: 85%;
5286: }
5287:
5288: .LC_fontsize_large {
5289: font-size: 120%;
5290: }
5291:
5292: .LC_menubuttons_inline_text {
5293: color: $font;
5294: font-size: 90%;
5295: padding-left:3px;
5296: }
5297:
5298: .LC_menubuttons_inline_text img{
5299: vertical-align: middle;
5300: }
5301:
5302: li.LC_menubuttons_inline_text img {
5303: cursor:pointer;
5304: text-decoration: none;
5305: }
5306:
5307: .LC_menubuttons_link {
5308: text-decoration: none;
5309: }
5310:
5311: .LC_menubuttons_category {
5312: color: $font;
5313: background: $pgbg;
5314: font-size: larger;
5315: font-weight: bold;
5316: }
5317:
5318: td.LC_menubuttons_text {
5319: color: $font;
5320: }
5321:
5322: .LC_current_location {
5323: background: $tabbg;
5324: }
5325:
5326: table.LC_data_table {
5327: border: 1px solid #000000;
5328: border-collapse: separate;
5329: border-spacing: 1px;
5330: background: $pgbg;
5331: }
5332:
5333: .LC_data_table_dense {
5334: font-size: small;
5335: }
5336:
5337: table.LC_nested_outer {
5338: border: 1px solid #000000;
5339: border-collapse: collapse;
5340: border-spacing: 0;
5341: width: 100%;
5342: }
5343:
5344: table.LC_innerpickbox,
5345: table.LC_nested {
5346: border: none;
5347: border-collapse: collapse;
5348: border-spacing: 0;
5349: width: 100%;
5350: }
5351:
5352: table.LC_data_table tr th,
5353: table.LC_calendar tr th,
5354: table.LC_prior_tries tr th,
5355: table.LC_innerpickbox tr th {
5356: font-weight: bold;
5357: background-color: $data_table_head;
5358: color:$fontmenu;
5359: font-size:90%;
5360: }
5361:
5362: table.LC_innerpickbox tr th,
5363: table.LC_innerpickbox tr td {
5364: vertical-align: top;
5365: }
5366:
5367: table.LC_data_table tr.LC_info_row > td {
5368: background-color: #CCCCCC;
5369: font-weight: bold;
5370: text-align: left;
5371: }
5372:
5373: table.LC_data_table tr.LC_odd_row > td {
5374: background-color: $data_table_light;
5375: padding: 2px;
5376: vertical-align: top;
5377: }
5378:
5379: table.LC_pick_box tr > td.LC_odd_row {
5380: background-color: $data_table_light;
5381: vertical-align: top;
5382: }
5383:
5384: table.LC_data_table tr.LC_even_row > td {
5385: background-color: $data_table_dark;
5386: padding: 2px;
5387: vertical-align: top;
5388: }
5389:
5390: table.LC_pick_box tr > td.LC_even_row {
5391: background-color: $data_table_dark;
5392: vertical-align: top;
5393: }
5394:
5395: table.LC_data_table tr.LC_data_table_highlight td {
5396: background-color: $data_table_darker;
5397: }
5398:
5399: table.LC_data_table tr td.LC_leftcol_header {
5400: background-color: $data_table_head;
5401: font-weight: bold;
5402: }
5403:
5404: table.LC_data_table tr.LC_empty_row td,
5405: table.LC_nested tr.LC_empty_row td {
5406: font-weight: bold;
5407: font-style: italic;
5408: text-align: center;
5409: padding: 8px;
5410: }
5411:
5412: table.LC_data_table tr.LC_empty_row td {
5413: background-color: $sidebg;
5414: }
5415:
5416: table.LC_nested tr.LC_empty_row td {
5417: background-color: #FFFFFF;
5418: }
5419:
5420: table.LC_caption {
5421: }
5422:
5423: table.LC_nested tr.LC_empty_row td {
5424: padding: 4ex
5425: }
5426:
5427: table.LC_nested_outer tr th {
5428: font-weight: bold;
5429: color:$fontmenu;
5430: background-color: $data_table_head;
5431: font-size: small;
5432: border-bottom: 1px solid #000000;
5433: }
5434:
5435: table.LC_nested_outer tr td.LC_subheader {
5436: background-color: $data_table_head;
5437: font-weight: bold;
5438: font-size: small;
5439: border-bottom: 1px solid #000000;
5440: text-align: right;
5441: }
5442:
5443: table.LC_nested tr.LC_info_row td {
5444: background-color: #CCCCCC;
5445: font-weight: bold;
5446: font-size: small;
5447: text-align: center;
5448: }
5449:
5450: table.LC_nested tr.LC_info_row td.LC_left_item,
5451: table.LC_nested_outer tr th.LC_left_item {
5452: text-align: left;
5453: }
5454:
5455: table.LC_nested td {
5456: background-color: #FFFFFF;
5457: font-size: small;
5458: }
5459:
5460: table.LC_nested_outer tr th.LC_right_item,
5461: table.LC_nested tr.LC_info_row td.LC_right_item,
5462: table.LC_nested tr.LC_odd_row td.LC_right_item,
5463: table.LC_nested tr td.LC_right_item {
5464: text-align: right;
5465: }
5466:
5467: table.LC_nested tr.LC_odd_row td {
5468: background-color: #EEEEEE;
5469: }
5470:
5471: table.LC_createuser {
5472: }
5473:
5474: table.LC_createuser tr.LC_section_row td {
5475: font-size: small;
5476: }
5477:
5478: table.LC_createuser tr.LC_info_row td {
5479: background-color: #CCCCCC;
5480: font-weight: bold;
5481: text-align: center;
5482: }
5483:
5484: table.LC_calendar {
5485: border: 1px solid #000000;
5486: border-collapse: collapse;
5487: width: 98%;
5488: }
5489:
5490: table.LC_calendar_pickdate {
5491: font-size: xx-small;
5492: }
5493:
5494: table.LC_calendar tr td {
5495: border: 1px solid #000000;
5496: vertical-align: top;
5497: width: 14%;
5498: }
5499:
5500: table.LC_calendar tr td.LC_calendar_day_empty {
5501: background-color: $data_table_dark;
5502: }
5503:
5504: table.LC_calendar tr td.LC_calendar_day_current {
5505: background-color: $data_table_highlight;
5506: }
5507:
5508: table.LC_data_table tr td.LC_mail_new {
5509: background-color: $mail_new;
5510: }
5511:
5512: table.LC_data_table tr.LC_mail_new:hover {
5513: background-color: $mail_new_hover;
5514: }
5515:
5516: table.LC_data_table tr td.LC_mail_read {
5517: background-color: $mail_read;
5518: }
5519:
5520: /*
5521: table.LC_data_table tr.LC_mail_read:hover {
5522: background-color: $mail_read_hover;
5523: }
5524: */
5525:
5526: table.LC_data_table tr td.LC_mail_replied {
5527: background-color: $mail_replied;
5528: }
5529:
5530: /*
5531: table.LC_data_table tr.LC_mail_replied:hover {
5532: background-color: $mail_replied_hover;
5533: }
5534: */
5535:
5536: table.LC_data_table tr td.LC_mail_other {
5537: background-color: $mail_other;
5538: }
5539:
5540: /*
5541: table.LC_data_table tr.LC_mail_other:hover {
5542: background-color: $mail_other_hover;
5543: }
5544: */
5545:
5546: table.LC_data_table tr > td.LC_browser_file,
5547: table.LC_data_table tr > td.LC_browser_file_published {
5548: background: #AAEE77;
5549: }
5550:
5551: table.LC_data_table tr > td.LC_browser_file_locked,
5552: table.LC_data_table tr > td.LC_browser_file_unpublished {
5553: background: #FFAA99;
5554: }
5555:
5556: table.LC_data_table tr > td.LC_browser_file_obsolete {
5557: background: #888888;
5558: }
5559:
5560: table.LC_data_table tr > td.LC_browser_file_modified,
5561: table.LC_data_table tr > td.LC_browser_file_metamodified {
5562: background: #F8F866;
5563: }
5564:
5565: table.LC_data_table tr.LC_browser_folder > td {
5566: background: #E0E8FF;
5567: }
5568:
5569: table.LC_data_table tr > td.LC_roles_is {
5570: /* background: #77FF77; */
5571: }
5572:
5573: table.LC_data_table tr > td.LC_roles_future {
5574: border-right: 8px solid #FFFF77;
5575: }
5576:
5577: table.LC_data_table tr > td.LC_roles_will {
5578: border-right: 8px solid #FFAA77;
5579: }
5580:
5581: table.LC_data_table tr > td.LC_roles_expired {
5582: border-right: 8px solid #FF7777;
5583: }
5584:
5585: table.LC_data_table tr > td.LC_roles_will_not {
5586: border-right: 8px solid #AAFF77;
5587: }
5588:
5589: table.LC_data_table tr > td.LC_roles_selected {
5590: border-right: 8px solid #11CC55;
5591: }
5592:
5593: span.LC_current_location {
5594: font-size:larger;
5595: background: $pgbg;
5596: }
5597:
5598: span.LC_current_nav_location {
5599: font-weight:bold;
5600: background: $sidebg;
5601: }
5602:
5603: span.LC_parm_menu_item {
5604: font-size: larger;
5605: }
5606:
5607: span.LC_parm_scope_all {
5608: color: red;
5609: }
5610:
5611: span.LC_parm_scope_folder {
5612: color: green;
5613: }
5614:
5615: span.LC_parm_scope_resource {
5616: color: orange;
5617: }
5618:
5619: span.LC_parm_part {
5620: color: blue;
5621: }
5622:
5623: span.LC_parm_folder,
5624: span.LC_parm_symb {
5625: font-size: x-small;
5626: font-family: $mono;
5627: color: #AAAAAA;
5628: }
5629:
5630: ul.LC_parm_parmlist li {
5631: display: inline-block;
5632: padding: 0.3em 0.8em;
5633: vertical-align: top;
5634: width: 150px;
5635: border-top:1px solid $lg_border_color;
5636: }
5637:
5638: td.LC_parm_overview_level_menu,
5639: td.LC_parm_overview_map_menu,
5640: td.LC_parm_overview_parm_selectors,
5641: td.LC_parm_overview_restrictions {
5642: border: 1px solid black;
5643: border-collapse: collapse;
5644: }
5645:
5646: table.LC_parm_overview_restrictions td {
5647: border-width: 1px 4px 1px 4px;
5648: border-style: solid;
5649: border-color: $pgbg;
5650: text-align: center;
5651: }
5652:
5653: table.LC_parm_overview_restrictions th {
5654: background: $tabbg;
5655: border-width: 1px 4px 1px 4px;
5656: border-style: solid;
5657: border-color: $pgbg;
5658: }
5659:
5660: table#LC_helpmenu {
5661: border: none;
5662: height: 55px;
5663: border-spacing: 0;
5664: }
5665:
5666: table#LC_helpmenu fieldset legend {
5667: font-size: larger;
5668: }
5669:
5670: table#LC_helpmenu_links {
5671: width: 100%;
5672: border: 1px solid black;
5673: background: $pgbg;
5674: padding: 0;
5675: border-spacing: 1px;
5676: }
5677:
5678: table#LC_helpmenu_links tr td {
5679: padding: 1px;
5680: background: $tabbg;
5681: text-align: center;
5682: font-weight: bold;
5683: }
5684:
5685: table#LC_helpmenu_links a:link,
5686: table#LC_helpmenu_links a:visited,
5687: table#LC_helpmenu_links a:active {
5688: text-decoration: none;
5689: color: $font;
5690: }
5691:
5692: table#LC_helpmenu_links a:hover {
5693: text-decoration: underline;
5694: color: $vlink;
5695: }
5696:
5697: .LC_chrt_popup_exists {
5698: border: 1px solid #339933;
5699: margin: -1px;
5700: }
5701:
5702: .LC_chrt_popup_up {
5703: border: 1px solid yellow;
5704: margin: -1px;
5705: }
5706:
5707: .LC_chrt_popup {
5708: border: 1px solid #8888FF;
5709: background: #CCCCFF;
5710: }
5711:
5712: table.LC_pick_box {
5713: border-collapse: separate;
5714: background: white;
5715: border: 1px solid black;
5716: border-spacing: 1px;
5717: }
5718:
5719: table.LC_pick_box td.LC_pick_box_title {
5720: background: $sidebg;
5721: font-weight: bold;
5722: text-align: left;
5723: vertical-align: top;
5724: width: 184px;
5725: padding: 8px;
5726: }
5727:
5728: table.LC_pick_box td.LC_pick_box_value {
5729: text-align: left;
5730: padding: 8px;
5731: }
5732:
5733: table.LC_pick_box td.LC_pick_box_select {
5734: text-align: left;
5735: padding: 8px;
5736: }
5737:
5738: table.LC_pick_box td.LC_pick_box_separator {
5739: padding: 0;
5740: height: 1px;
5741: background: black;
5742: }
5743:
5744: table.LC_pick_box td.LC_pick_box_submit {
5745: text-align: right;
5746: }
5747:
5748: table.LC_pick_box td.LC_evenrow_value {
5749: text-align: left;
5750: padding: 8px;
5751: background-color: $data_table_light;
5752: }
5753:
5754: table.LC_pick_box td.LC_oddrow_value {
5755: text-align: left;
5756: padding: 8px;
5757: background-color: $data_table_light;
5758: }
5759:
5760: span.LC_helpform_receipt_cat {
5761: font-weight: bold;
5762: }
5763:
5764: table.LC_group_priv_box {
5765: background: white;
5766: border: 1px solid black;
5767: border-spacing: 1px;
5768: }
5769:
5770: table.LC_group_priv_box td.LC_pick_box_title {
5771: background: $tabbg;
5772: font-weight: bold;
5773: text-align: right;
5774: width: 184px;
5775: }
5776:
5777: table.LC_group_priv_box td.LC_groups_fixed {
5778: background: $data_table_light;
5779: text-align: center;
5780: }
5781:
5782: table.LC_group_priv_box td.LC_groups_optional {
5783: background: $data_table_dark;
5784: text-align: center;
5785: }
5786:
5787: table.LC_group_priv_box td.LC_groups_functionality {
5788: background: $data_table_darker;
5789: text-align: center;
5790: font-weight: bold;
5791: }
5792:
5793: table.LC_group_priv td {
5794: text-align: left;
5795: padding: 0;
5796: }
5797:
5798: .LC_navbuttons {
5799: margin: 2ex 0ex 2ex 0ex;
5800: }
5801:
5802: .LC_topic_bar {
5803: font-weight: bold;
5804: background: $tabbg;
5805: margin: 1em 0em 1em 2em;
5806: padding: 3px;
5807: font-size: 1.2em;
5808: }
5809:
5810: .LC_topic_bar span {
5811: left: 0.5em;
5812: position: absolute;
5813: vertical-align: middle;
5814: font-size: 1.2em;
5815: }
5816:
5817: table.LC_course_group_status {
5818: margin: 20px;
5819: }
5820:
5821: table.LC_status_selector td {
5822: vertical-align: top;
5823: text-align: center;
5824: padding: 4px;
5825: }
5826:
5827: div.LC_feedback_link {
5828: clear: both;
5829: background: $sidebg;
5830: width: 100%;
5831: padding-bottom: 10px;
5832: border: 1px $tabbg solid;
5833: height: 22px;
5834: line-height: 22px;
5835: padding-top: 5px;
5836: }
5837:
5838: div.LC_feedback_link img {
5839: height: 22px;
5840: vertical-align:middle;
5841: }
5842:
5843: div.LC_feedback_link a {
5844: text-decoration: none;
5845: }
5846:
5847: div.LC_comblock {
5848: display:inline;
5849: color:$font;
5850: font-size:90%;
5851: }
5852:
5853: div.LC_feedback_link div.LC_comblock {
5854: padding-left:5px;
5855: }
5856:
5857: div.LC_feedback_link div.LC_comblock a {
5858: color:$font;
5859: }
5860:
5861: span.LC_feedback_link {
5862: /* background: $feedback_link_bg; */
5863: font-size: larger;
5864: }
5865:
5866: span.LC_message_link {
5867: /* background: $feedback_link_bg; */
5868: font-size: larger;
5869: position: absolute;
5870: right: 1em;
5871: }
5872:
5873: table.LC_prior_tries {
5874: border: 1px solid #000000;
5875: border-collapse: separate;
5876: border-spacing: 1px;
5877: }
5878:
5879: table.LC_prior_tries td {
5880: padding: 2px;
5881: }
5882:
5883: .LC_answer_correct {
5884: background: lightgreen;
5885: color: darkgreen;
5886: padding: 6px;
5887: }
5888:
5889: .LC_answer_charged_try {
5890: background: #FFAAAA;
5891: color: darkred;
5892: padding: 6px;
5893: }
5894:
5895: .LC_answer_not_charged_try,
5896: .LC_answer_no_grade,
5897: .LC_answer_late {
5898: background: lightyellow;
5899: color: black;
5900: padding: 6px;
5901: }
5902:
5903: .LC_answer_previous {
5904: background: lightblue;
5905: color: darkblue;
5906: padding: 6px;
5907: }
5908:
5909: .LC_answer_no_message {
5910: background: #FFFFFF;
5911: color: black;
5912: padding: 6px;
5913: }
5914:
5915: .LC_answer_unknown {
5916: background: orange;
5917: color: black;
5918: padding: 6px;
5919: }
5920:
5921: span.LC_prior_numerical,
5922: span.LC_prior_string,
5923: span.LC_prior_custom,
5924: span.LC_prior_reaction,
5925: span.LC_prior_math {
5926: font-family: $mono;
5927: white-space: pre;
5928: }
5929:
5930: span.LC_prior_string {
5931: font-family: $mono;
5932: white-space: pre;
5933: }
5934:
5935: table.LC_prior_option {
5936: width: 100%;
5937: border-collapse: collapse;
5938: }
5939:
5940: table.LC_prior_rank,
5941: table.LC_prior_match {
5942: border-collapse: collapse;
5943: }
5944:
5945: table.LC_prior_option tr td,
5946: table.LC_prior_rank tr td,
5947: table.LC_prior_match tr td {
5948: border: 1px solid #000000;
5949: }
5950:
5951: .LC_nobreak {
5952: white-space: nowrap;
5953: }
5954:
5955: span.LC_cusr_emph {
5956: font-style: italic;
5957: }
5958:
5959: span.LC_cusr_subheading {
5960: font-weight: normal;
5961: font-size: 85%;
5962: }
5963:
5964: div.LC_docs_entry_move {
5965: border: 1px solid #BBBBBB;
5966: background: #DDDDDD;
5967: width: 22px;
5968: padding: 1px;
5969: margin: 0;
5970: }
5971:
5972: table.LC_data_table tr > td.LC_docs_entry_commands,
5973: table.LC_data_table tr > td.LC_docs_entry_parameter {
5974: background: #DDDDDD;
5975: font-size: x-small;
5976: }
5977:
5978: .LC_docs_entry_parameter {
5979: white-space: nowrap;
5980: }
5981:
5982: .LC_docs_copy {
5983: color: #000099;
5984: }
5985:
5986: .LC_docs_cut {
5987: color: #550044;
5988: }
5989:
5990: .LC_docs_rename {
5991: color: #009900;
5992: }
5993:
5994: .LC_docs_remove {
5995: color: #990000;
5996: }
5997:
5998: .LC_docs_reinit_warn,
5999: .LC_docs_ext_edit {
6000: font-size: x-small;
6001: }
6002:
6003: table.LC_docs_adddocs td,
6004: table.LC_docs_adddocs th {
6005: border: 1px solid #BBBBBB;
6006: padding: 4px;
6007: background: #DDDDDD;
6008: }
6009:
6010: table.LC_sty_begin {
6011: background: #BBFFBB;
6012: }
6013:
6014: table.LC_sty_end {
6015: background: #FFBBBB;
6016: }
6017:
6018: table.LC_double_column {
6019: border-width: 0;
6020: border-collapse: collapse;
6021: width: 100%;
6022: padding: 2px;
6023: }
6024:
6025: table.LC_double_column tr td.LC_left_col {
6026: top: 2px;
6027: left: 2px;
6028: width: 47%;
6029: vertical-align: top;
6030: }
6031:
6032: table.LC_double_column tr td.LC_right_col {
6033: top: 2px;
6034: right: 2px;
6035: width: 47%;
6036: vertical-align: top;
6037: }
6038:
6039: div.LC_left_float {
6040: float: left;
6041: padding-right: 5%;
6042: padding-bottom: 4px;
6043: }
6044:
6045: div.LC_clear_float_header {
6046: padding-bottom: 2px;
6047: }
6048:
6049: div.LC_clear_float_footer {
6050: padding-top: 10px;
6051: clear: both;
6052: }
6053:
6054: div.LC_grade_show_user {
6055: /* border-left: 5px solid $sidebg; */
6056: border-top: 5px solid #000000;
6057: margin: 50px 0 0 0;
6058: padding: 15px 0 5px 10px;
6059: }
6060:
6061: div.LC_grade_show_user_odd_row {
6062: /* border-left: 5px solid #000000; */
6063: }
6064:
6065: div.LC_grade_show_user div.LC_Box {
6066: margin-right: 50px;
6067: }
6068:
6069: div.LC_grade_submissions,
6070: div.LC_grade_message_center,
6071: div.LC_grade_info_links {
6072: margin: 5px;
6073: width: 99%;
6074: background: #FFFFFF;
6075: }
6076:
6077: div.LC_grade_submissions_header,
6078: div.LC_grade_message_center_header {
6079: font-weight: bold;
6080: font-size: large;
6081: }
6082:
6083: div.LC_grade_submissions_body,
6084: div.LC_grade_message_center_body {
6085: border: 1px solid black;
6086: width: 99%;
6087: background: #FFFFFF;
6088: }
6089:
6090: table.LC_scantron_action {
6091: width: 100%;
6092: }
6093:
6094: table.LC_scantron_action tr th {
6095: font-weight:bold;
6096: font-style:normal;
6097: }
6098:
6099: .LC_edit_problem_header,
6100: div.LC_edit_problem_footer {
6101: font-weight: normal;
6102: font-size: medium;
6103: margin: 2px;
6104: }
6105:
6106: div.LC_edit_problem_header,
6107: div.LC_edit_problem_header div,
6108: div.LC_edit_problem_footer,
6109: div.LC_edit_problem_footer div,
6110: div.LC_edit_problem_editxml_header,
6111: div.LC_edit_problem_editxml_header div {
6112: margin-top: 5px;
6113: }
6114:
6115: div.LC_edit_problem_header_title {
6116: font-weight: bold;
6117: font-size: larger;
6118: background: $tabbg;
6119: padding: 3px;
6120: }
6121:
6122: table.LC_edit_problem_header_title {
6123: width: 100%;
6124: background: $tabbg;
6125: }
6126:
6127: div.LC_edit_problem_discards {
6128: float: left;
6129: padding-bottom: 5px;
6130: }
6131:
6132: div.LC_edit_problem_saves {
6133: float: right;
6134: padding-bottom: 5px;
6135: }
6136:
6137: img.stift {
6138: border-width: 0;
6139: vertical-align: middle;
6140: }
6141:
6142: table td.LC_mainmenu_col_fieldset {
6143: vertical-align: top;
6144: }
6145:
6146: div.LC_createcourse {
6147: margin: 10px 10px 10px 10px;
6148: }
6149:
6150: .LC_dccid {
6151: margin: 0.2em 0 0 0;
6152: padding: 0;
6153: font-size: 90%;
6154: display:none;
6155: }
6156:
6157: ol.LC_primary_menu a:hover,
6158: ol#LC_MenuBreadcrumbs a:hover,
6159: ol#LC_PathBreadcrumbs a:hover,
6160: ul#LC_secondary_menu a:hover,
6161: .LC_FormSectionClearButton input:hover
6162: ul.LC_TabContent li:hover a {
6163: color:$button_hover;
6164: text-decoration:none;
6165: }
6166:
6167: h1 {
6168: padding: 0;
6169: line-height:130%;
6170: }
6171:
6172: h2,
6173: h3,
6174: h4,
6175: h5,
6176: h6 {
6177: margin: 5px 0 5px 0;
6178: padding: 0;
6179: line-height:130%;
6180: }
6181:
6182: .LC_hcell {
6183: padding:3px 15px 3px 15px;
6184: margin: 0;
6185: background-color:$tabbg;
6186: color:$fontmenu;
6187: border-bottom:solid 1px $lg_border_color;
6188: }
6189:
6190: .LC_Box > .LC_hcell {
6191: margin: 0 -10px 10px -10px;
6192: }
6193:
6194: .LC_noBorder {
6195: border: 0;
6196: }
6197:
6198: .LC_FormSectionClearButton input {
6199: background-color:transparent;
6200: border: none;
6201: cursor:pointer;
6202: text-decoration:underline;
6203: }
6204:
6205: .LC_help_open_topic {
6206: color: #FFFFFF;
6207: background-color: #EEEEFF;
6208: margin: 1px;
6209: padding: 4px;
6210: border: 1px solid #000033;
6211: white-space: nowrap;
6212: /* vertical-align: middle; */
6213: }
6214:
6215: dl,
6216: ul,
6217: div,
6218: fieldset {
6219: margin: 10px 10px 10px 0;
6220: /* overflow: hidden; */
6221: }
6222:
6223: fieldset > legend {
6224: font-weight: bold;
6225: padding: 0 5px 0 5px;
6226: }
6227:
6228: #LC_nav_bar {
6229: float: left;
6230: background-color: $pgbg_or_bgcolor;
6231: margin: 0 0 2px 0;
6232: }
6233:
6234: #LC_realm {
6235: margin: 0.2em 0 0 0;
6236: padding: 0;
6237: font-weight: bold;
6238: text-align: center;
6239: background-color: $pgbg_or_bgcolor;
6240: }
6241:
6242: #LC_nav_bar em {
6243: font-weight: bold;
6244: font-style: normal;
6245: }
6246:
6247: ol.LC_primary_menu {
6248: float: right;
6249: margin: 0;
6250: background-color: $pgbg_or_bgcolor;
6251: }
6252:
6253: ol#LC_PathBreadcrumbs {
6254: margin: 0;
6255: }
6256:
6257: ol.LC_primary_menu li {
6258: display: inline;
6259: padding: 5px 5px 0 10px;
6260: vertical-align: top;
6261: }
6262:
6263: ol.LC_primary_menu li img {
6264: vertical-align: bottom;
6265: height: 1.1em;
6266: }
6267:
6268: ol.LC_primary_menu a {
6269: color: RGB(80, 80, 80);
6270: text-decoration: none;
6271: }
6272:
6273: ol.LC_primary_menu a.LC_new_message {
6274: font-weight:bold;
6275: color: darkred;
6276: }
6277:
6278: ol.LC_docs_parameters {
6279: margin-left: 0;
6280: padding: 0;
6281: list-style: none;
6282: }
6283:
6284: ol.LC_docs_parameters li {
6285: margin: 0;
6286: padding-right: 20px;
6287: display: inline;
6288: }
6289:
6290: ol.LC_docs_parameters li:before {
6291: content: "\\002022 \\0020";
6292: }
6293:
6294: li.LC_docs_parameters_title {
6295: font-weight: bold;
6296: }
6297:
6298: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6299: content: "";
6300: }
6301:
6302: ul#LC_secondary_menu {
6303: clear: both;
6304: color: $fontmenu;
6305: background: $tabbg;
6306: list-style: none;
6307: padding: 0;
6308: margin: 0;
6309: width: 100%;
6310: text-align: left;
6311: }
6312:
6313: ul#LC_secondary_menu li {
6314: font-weight: bold;
6315: line-height: 1.8em;
6316: padding: 0 0.8em;
6317: border-right: 1px solid black;
6318: display: inline;
6319: vertical-align: middle;
6320: }
6321:
6322: ul.LC_TabContent {
6323: display:block;
6324: background: $sidebg;
6325: border-bottom: solid 1px $lg_border_color;
6326: list-style:none;
6327: margin: -1px -10px 0 -10px;
6328: padding: 0;
6329: }
6330:
6331: ul.LC_TabContent li,
6332: ul.LC_TabContentBigger li {
6333: float:left;
6334: }
6335:
6336: ul#LC_secondary_menu li a {
6337: color: $fontmenu;
6338: text-decoration: none;
6339: }
6340:
6341: ul.LC_TabContent {
6342: min-height:20px;
6343: }
6344:
6345: ul.LC_TabContent li {
6346: vertical-align:middle;
6347: padding: 0 16px 0 10px;
6348: background-color:$tabbg;
6349: border-bottom:solid 1px $lg_border_color;
6350: border-left: solid 1px $font;
6351: }
6352:
6353: ul.LC_TabContent .right {
6354: float:right;
6355: }
6356:
6357: ul.LC_TabContent li a,
6358: ul.LC_TabContent li {
6359: color:rgb(47,47,47);
6360: text-decoration:none;
6361: font-size:95%;
6362: font-weight:bold;
6363: min-height:20px;
6364: }
6365:
6366: ul.LC_TabContent li a:hover,
6367: ul.LC_TabContent li a:focus {
6368: color: $button_hover;
6369: background:none;
6370: outline:none;
6371: }
6372:
6373: ul.LC_TabContent li:hover {
6374: color: $button_hover;
6375: cursor:pointer;
6376: }
6377:
6378: ul.LC_TabContent li.active {
6379: color: $font;
6380: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6381: border-bottom:solid 1px #FFFFFF;
6382: cursor: default;
6383: }
6384:
6385: ul.LC_TabContent li.active a {
6386: color:$font;
6387: background:#FFFFFF;
6388: outline: none;
6389: }
6390:
6391: ul.LC_TabContent li.goback {
6392: float: left;
6393: border-left: none;
6394: }
6395:
6396: #maincoursedoc {
6397: clear:both;
6398: }
6399:
6400: ul.LC_TabContentBigger {
6401: display:block;
6402: list-style:none;
6403: padding: 0;
6404: }
6405:
6406: ul.LC_TabContentBigger li {
6407: vertical-align:bottom;
6408: height: 30px;
6409: font-size:110%;
6410: font-weight:bold;
6411: color: #737373;
6412: }
6413:
6414: ul.LC_TabContentBigger li.active {
6415: position: relative;
6416: top: 1px;
6417: }
6418:
6419: ul.LC_TabContentBigger li a {
6420: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6421: height: 30px;
6422: line-height: 30px;
6423: text-align: center;
6424: display: block;
6425: text-decoration: none;
6426: outline: none;
6427: }
6428:
6429: ul.LC_TabContentBigger li.active a {
6430: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6431: color:$font;
6432: }
6433:
6434: ul.LC_TabContentBigger li b {
6435: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6436: display: block;
6437: float: left;
6438: padding: 0 30px;
6439: border-bottom: 1px solid $lg_border_color;
6440: }
6441:
6442: ul.LC_TabContentBigger li:hover b {
6443: color:$button_hover;
6444: }
6445:
6446: ul.LC_TabContentBigger li.active b {
6447: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6448: color:$font;
6449: border: 0;
6450: }
6451:
6452:
6453: ul.LC_CourseBreadcrumbs {
6454: background: $sidebg;
6455: height: 2em;
6456: padding-left: 10px;
6457: margin: 0;
6458: list-style-position: inside;
6459: }
6460:
6461: ol#LC_MenuBreadcrumbs,
6462: ol#LC_PathBreadcrumbs {
6463: padding-left: 10px;
6464: margin: 0;
6465: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6466: }
6467:
6468: ol#LC_MenuBreadcrumbs li,
6469: ol#LC_PathBreadcrumbs li,
6470: ul.LC_CourseBreadcrumbs li {
6471: display: inline;
6472: white-space: normal;
6473: }
6474:
6475: ol#LC_MenuBreadcrumbs li a,
6476: ul.LC_CourseBreadcrumbs li a {
6477: text-decoration: none;
6478: font-size:90%;
6479: }
6480:
6481: ol#LC_MenuBreadcrumbs h1 {
6482: display: inline;
6483: font-size: 90%;
6484: line-height: 2.5em;
6485: margin: 0;
6486: padding: 0;
6487: }
6488:
6489: ol#LC_PathBreadcrumbs li a {
6490: text-decoration:none;
6491: font-size:100%;
6492: font-weight:bold;
6493: }
6494:
6495: .LC_Box {
6496: border: solid 1px $lg_border_color;
6497: padding: 0 10px 10px 10px;
6498: }
6499:
6500: .LC_DocsBox {
6501: border: solid 1px $lg_border_color;
6502: padding: 0 0 10px 10px;
6503: }
6504:
6505: .LC_AboutMe_Image {
6506: float:left;
6507: margin-right:10px;
6508: }
6509:
6510: .LC_Clear_AboutMe_Image {
6511: clear:left;
6512: }
6513:
6514: dl.LC_ListStyleClean dt {
6515: padding-right: 5px;
6516: display: table-header-group;
6517: }
6518:
6519: dl.LC_ListStyleClean dd {
6520: display: table-row;
6521: }
6522:
6523: .LC_ListStyleClean,
6524: .LC_ListStyleSimple,
6525: .LC_ListStyleNormal,
6526: .LC_ListStyleSpecial {
6527: /* display:block; */
6528: list-style-position: inside;
6529: list-style-type: none;
6530: overflow: hidden;
6531: padding: 0;
6532: }
6533:
6534: .LC_ListStyleSimple li,
6535: .LC_ListStyleSimple dd,
6536: .LC_ListStyleNormal li,
6537: .LC_ListStyleNormal dd,
6538: .LC_ListStyleSpecial li,
6539: .LC_ListStyleSpecial dd {
6540: margin: 0;
6541: padding: 5px 5px 5px 10px;
6542: clear: both;
6543: }
6544:
6545: .LC_ListStyleClean li,
6546: .LC_ListStyleClean dd {
6547: padding-top: 0;
6548: padding-bottom: 0;
6549: }
6550:
6551: .LC_ListStyleSimple dd,
6552: .LC_ListStyleSimple li {
6553: border-bottom: solid 1px $lg_border_color;
6554: }
6555:
6556: .LC_ListStyleSpecial li,
6557: .LC_ListStyleSpecial dd {
6558: list-style-type: none;
6559: background-color: RGB(220, 220, 220);
6560: margin-bottom: 4px;
6561: }
6562:
6563: table.LC_SimpleTable {
6564: margin:5px;
6565: border:solid 1px $lg_border_color;
6566: }
6567:
6568: table.LC_SimpleTable tr {
6569: padding: 0;
6570: border:solid 1px $lg_border_color;
6571: }
6572:
6573: table.LC_SimpleTable thead {
6574: background:rgb(220,220,220);
6575: }
6576:
6577: div.LC_columnSection {
6578: display: block;
6579: clear: both;
6580: overflow: hidden;
6581: margin: 0;
6582: }
6583:
6584: div.LC_columnSection>* {
6585: float: left;
6586: margin: 10px 20px 10px 0;
6587: overflow:hidden;
6588: }
6589:
6590: table em {
6591: font-weight: bold;
6592: font-style: normal;
6593: }
6594:
6595: table.LC_tableBrowseRes,
6596: table.LC_tableOfContent {
6597: border:none;
6598: border-spacing: 1px;
6599: padding: 3px;
6600: background-color: #FFFFFF;
6601: font-size: 90%;
6602: }
6603:
6604: table.LC_tableOfContent {
6605: border-collapse: collapse;
6606: }
6607:
6608: table.LC_tableBrowseRes a,
6609: table.LC_tableOfContent a {
6610: background-color: transparent;
6611: text-decoration: none;
6612: }
6613:
6614: table.LC_tableOfContent img {
6615: border: none;
6616: height: 1.3em;
6617: vertical-align: text-bottom;
6618: margin-right: 0.3em;
6619: }
6620:
6621: a#LC_content_toolbar_firsthomework {
6622: background-image:url(/res/adm/pages/open-first-problem.gif);
6623: }
6624:
6625: a#LC_content_toolbar_everything {
6626: background-image:url(/res/adm/pages/show-all.gif);
6627: }
6628:
6629: a#LC_content_toolbar_uncompleted {
6630: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
6631: }
6632:
6633: #LC_content_toolbar_clearbubbles {
6634: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
6635: }
6636:
6637: a#LC_content_toolbar_changefolder {
6638: background : url(/res/adm/pages/close-all-folders.gif) top center ;
6639: }
6640:
6641: a#LC_content_toolbar_changefolder_toggled {
6642: background-image:url(/res/adm/pages/open-all-folders.gif);
6643: }
6644:
6645: a#LC_content_toolbar_edittoplevel {
6646: background-image:url(/res/adm/pages/edittoplevel.gif);
6647: }
6648:
6649: ul#LC_toolbar li a:hover {
6650: background-position: bottom center;
6651: }
6652:
6653: ul#LC_toolbar {
6654: padding: 0;
6655: margin: 2px;
6656: list-style:none;
6657: position:relative;
6658: background-color:white;
6659: }
6660:
6661: ul#LC_toolbar li {
6662: border:1px solid white;
6663: padding: 0;
6664: margin: 0;
6665: float: left;
6666: display:inline;
6667: vertical-align:middle;
6668: }
6669:
6670:
6671: a.LC_toolbarItem {
6672: display:block;
6673: padding: 0;
6674: margin: 0;
6675: height: 32px;
6676: width: 32px;
6677: color:white;
6678: border: none;
6679: background-repeat:no-repeat;
6680: background-color:transparent;
6681: }
6682:
6683: ul.LC_funclist {
6684: margin: 0;
6685: padding: 0.5em 1em 0.5em 0;
6686: }
6687:
6688: ul.LC_funclist > li:first-child {
6689: font-weight:bold;
6690: margin-left:0.8em;
6691: }
6692:
6693: ul.LC_funclist + ul.LC_funclist {
6694: /*
6695: left border as a seperator if we have more than
6696: one list
6697: */
6698: border-left: 1px solid $sidebg;
6699: /*
6700: this hides the left border behind the border of the
6701: outer box if element is wrapped to the next 'line'
6702: */
6703: margin-left: -1px;
6704: }
6705:
6706: ul.LC_funclist li {
6707: display: inline;
6708: white-space: nowrap;
6709: margin: 0 0 0 25px;
6710: line-height: 150%;
6711: }
6712:
6713: .LC_hidden {
6714: display: none;
6715: }
6716:
6717: .LCmodal-overlay {
6718: position:fixed;
6719: top:0;
6720: right:0;
6721: bottom:0;
6722: left:0;
6723: height:100%;
6724: width:100%;
6725: margin:0;
6726: padding:0;
6727: background:#999;
6728: opacity:.75;
6729: filter: alpha(opacity=75);
6730: -moz-opacity: 0.75;
6731: z-index:101;
6732: }
6733:
6734: * html .LCmodal-overlay {
6735: position: absolute;
6736: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
6737: }
6738:
6739: .LCmodal-window {
6740: position:fixed;
6741: top:50%;
6742: left:50%;
6743: margin:0;
6744: padding:0;
6745: z-index:102;
6746: }
6747:
6748: * html .LCmodal-window {
6749: position:absolute;
6750: }
6751:
6752: .LCclose-window {
6753: position:absolute;
6754: width:32px;
6755: height:32px;
6756: right:8px;
6757: top:8px;
6758: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
6759: text-indent:-99999px;
6760: overflow:hidden;
6761: cursor:pointer;
6762: }
6763:
6764: END
6765: }
6766:
6767: =pod
6768:
6769: =item * &headtag()
6770:
6771: Returns a uniform footer for LON-CAPA web pages.
6772:
6773: Inputs: $title - optional title for the head
6774: $head_extra - optional extra HTML to put inside the <head>
6775: $args - optional arguments
6776: force_register - if is true call registerurl so the remote is
6777: informed
6778: redirect -> array ref of
6779: 1- seconds before redirect occurs
6780: 2- url to redirect to
6781: 3- whether the side effect should occur
6782: (side effect of setting
6783: $env{'internal.head.redirect'} to the url
6784: redirected too)
6785: domain -> force to color decorate a page for a specific
6786: domain
6787: function -> force usage of a specific rolish color scheme
6788: bgcolor -> override the default page bgcolor
6789: no_auto_mt_title
6790: -> prevent &mt()ing the title arg
6791:
6792: =cut
6793:
6794: sub headtag {
6795: my ($title,$head_extra,$args) = @_;
6796:
6797: my $function = $args->{'function'} || &get_users_function();
6798: my $domain = $args->{'domain'} || &determinedomain();
6799: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
6800: my $url = join(':',$env{'user.name'},$env{'user.domain'},
6801: $Apache::lonnet::perlvar{'lonVersion'},
6802: #time(),
6803: $env{'environment.color.timestamp'},
6804: $function,$domain,$bgcolor);
6805:
6806: $url = '/adm/css/'.&escape($url).'.css';
6807:
6808: my $result =
6809: '<head>'.
6810: &font_settings();
6811:
6812: if (!$args->{'frameset'}) {
6813: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
6814: }
6815: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
6816: $result .= Apache::lonxml::display_title();
6817: }
6818: if (!$args->{'no_nav_bar'}
6819: && !$args->{'only_body'}
6820: && !$args->{'frameset'}) {
6821: $result .= &help_menu_js();
6822: $result.=&modal_window();
6823: $result.=&togglebox_script();
6824: $result.=&wishlist_window();
6825: $result.=&LCprogressbarUpdate_script();
6826: } else {
6827: if ($args->{'add_modal'}) {
6828: $result.=&modal_window();
6829: }
6830: if ($args->{'add_wishlist'}) {
6831: $result.=&wishlist_window();
6832: }
6833: if ($args->{'add_togglebox'}) {
6834: $result.=&togglebox_script();
6835: }
6836: if ($args->{'add_progressbar'}) {
6837: $result.=&LCprogressbarUpdate_script();
6838: }
6839: }
6840: if (ref($args->{'redirect'})) {
6841: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
6842: $url = &Apache::lonenc::check_encrypt($url);
6843: if (!$inhibit_continue) {
6844: $env{'internal.head.redirect'} = $url;
6845: }
6846: $result.=<<ADDMETA
6847: <meta http-equiv="pragma" content="no-cache" />
6848: <meta http-equiv="Refresh" content="$time; url=$url" />
6849: ADDMETA
6850: }
6851: if (!defined($title)) {
6852: $title = 'The LearningOnline Network with CAPA';
6853: }
6854: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6855: $result .= '<title> LON-CAPA '.$title.'</title>'
6856: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
6857: .$head_extra;
6858: return $result.'</head>';
6859: }
6860:
6861: =pod
6862:
6863: =item * &font_settings()
6864:
6865: Returns neccessary <meta> to set the proper encoding
6866:
6867: Inputs: none
6868:
6869: =cut
6870:
6871: sub font_settings {
6872: my $headerstring='';
6873: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
6874: $headerstring.=
6875: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
6876: }
6877: return $headerstring;
6878: }
6879:
6880: =pod
6881:
6882: =item * &xml_begin()
6883:
6884: Returns the needed doctype and <html>
6885:
6886: Inputs: none
6887:
6888: =cut
6889:
6890: sub xml_begin {
6891: my $output='';
6892:
6893: if ($env{'browser.mathml'}) {
6894: $output='<?xml version="1.0"?>'
6895: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
6896: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
6897:
6898: # .'<!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">] >'
6899: .'<!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">'
6900: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
6901: .'xmlns="http://www.w3.org/1999/xhtml">';
6902: } else {
6903: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
6904: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
6905: }
6906: return $output;
6907: }
6908:
6909: =pod
6910:
6911: =item * &start_page()
6912:
6913: Returns a complete <html> .. <body> section for LON-CAPA web pages.
6914:
6915: Inputs:
6916:
6917: =over 4
6918:
6919: $title - optional title for the page
6920:
6921: $head_extra - optional extra HTML to incude inside the <head>
6922:
6923: $args - additional optional args supported are:
6924:
6925: =over 8
6926:
6927: only_body -> is true will set &bodytag() onlybodytag
6928: arg on
6929: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
6930: add_entries -> additional attributes to add to the <body>
6931: domain -> force to color decorate a page for a
6932: specific domain
6933: function -> force usage of a specific rolish color
6934: scheme
6935: redirect -> see &headtag()
6936: bgcolor -> override the default page bg color
6937: js_ready -> return a string ready for being used in
6938: a javascript writeln
6939: html_encode -> return a string ready for being used in
6940: a html attribute
6941: force_register -> if is true will turn on the &bodytag()
6942: $forcereg arg
6943: frameset -> if true will start with a <frameset>
6944: rather than <body>
6945: skip_phases -> hash ref of
6946: head -> skip the <html><head> generation
6947: body -> skip all <body> generation
6948: no_auto_mt_title -> prevent &mt()ing the title arg
6949: inherit_jsmath -> when creating popup window in a page,
6950: should it have jsmath forced on by the
6951: current page
6952: bread_crumbs -> Array containing breadcrumbs
6953: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
6954:
6955: =back
6956:
6957: =back
6958:
6959: =cut
6960:
6961: sub start_page {
6962: my ($title,$head_extra,$args) = @_;
6963: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6964:
6965: $env{'internal.start_page'}++;
6966: my $result;
6967:
6968: if (! exists($args->{'skip_phases'}{'head'}) ) {
6969: $result .= &xml_begin() . &headtag($title, $head_extra, $args);
6970: }
6971:
6972: if (! exists($args->{'skip_phases'}{'body'}) ) {
6973: if ($args->{'frameset'}) {
6974: my $attr_string = &make_attr_string($args->{'force_register'},
6975: $args->{'add_entries'});
6976: $result .= "\n<frameset $attr_string>\n";
6977: } else {
6978: $result .=
6979: &bodytag($title,
6980: $args->{'function'}, $args->{'add_entries'},
6981: $args->{'only_body'}, $args->{'domain'},
6982: $args->{'force_register'}, $args->{'no_nav_bar'},
6983: $args->{'bgcolor'}, $args);
6984: }
6985: }
6986:
6987: if ($args->{'js_ready'}) {
6988: $result = &js_ready($result);
6989: }
6990: if ($args->{'html_encode'}) {
6991: $result = &html_encode($result);
6992: }
6993:
6994: # Preparation for new and consistent functionlist at top of screen
6995: # if ($args->{'functionlist'}) {
6996: # $result .= &build_functionlist();
6997: #}
6998:
6999: # Don't add anything more if only_body wanted or in const space
7000: return $result if $args->{'only_body'}
7001: || $env{'request.state'} eq 'construct';
7002:
7003: #Breadcrumbs
7004: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7005: &Apache::lonhtmlcommon::clear_breadcrumbs();
7006: #if any br links exists, add them to the breadcrumbs
7007: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7008: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7009: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7010: }
7011: }
7012:
7013: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7014: if(exists($args->{'bread_crumbs_component'})){
7015: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7016: }else{
7017: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7018: }
7019: }
7020: return $result;
7021: }
7022:
7023: sub end_page {
7024: my ($args) = @_;
7025: $env{'internal.end_page'}++;
7026: my $result;
7027: if ($args->{'discussion'}) {
7028: my ($target,$parser);
7029: if (ref($args->{'discussion'})) {
7030: ($target,$parser) =($args->{'discussion'}{'target'},
7031: $args->{'discussion'}{'parser'});
7032: }
7033: $result .= &Apache::lonxml::xmlend($target,$parser);
7034: }
7035: if ($args->{'frameset'}) {
7036: $result .= '</frameset>';
7037: } else {
7038: $result .= &endbodytag($args);
7039: }
7040: $result .= "\n</html>";
7041:
7042: if ($args->{'js_ready'}) {
7043: $result = &js_ready($result);
7044: }
7045:
7046: if ($args->{'html_encode'}) {
7047: $result = &html_encode($result);
7048: }
7049:
7050: return $result;
7051: }
7052:
7053: sub wishlist_window {
7054: return(<<'ENDWISHLIST');
7055: <script type="text/javascript">
7056: // <![CDATA[
7057: // <!-- BEGIN LON-CAPA Internal
7058: function set_wishlistlink(title, path) {
7059: if (!title) {
7060: title = document.title;
7061: title = title.replace(/^LON-CAPA /,'');
7062: }
7063: if (!path) {
7064: path = location.pathname;
7065: }
7066: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7067: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7068: }
7069: // END LON-CAPA Internal -->
7070: // ]]>
7071: </script>
7072: ENDWISHLIST
7073: }
7074:
7075: sub modal_window {
7076: return(<<'ENDMODAL');
7077: <script type="text/javascript">
7078: // <![CDATA[
7079: // <!-- BEGIN LON-CAPA Internal
7080: var modalWindow = {
7081: parent:"body",
7082: windowId:null,
7083: content:null,
7084: width:null,
7085: height:null,
7086: close:function()
7087: {
7088: $(".LCmodal-window").remove();
7089: $(".LCmodal-overlay").remove();
7090: },
7091: open:function()
7092: {
7093: var modal = "";
7094: modal += "<div class=\"LCmodal-overlay\"></div>";
7095: 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;\">";
7096: modal += this.content;
7097: modal += "</div>";
7098:
7099: $(this.parent).append(modal);
7100:
7101: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7102: $(".LCclose-window").click(function(){modalWindow.close();});
7103: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7104: }
7105: };
7106: var openMyModal = function(source,width,height,scrolling)
7107: {
7108: modalWindow.windowId = "myModal";
7109: modalWindow.width = width;
7110: modalWindow.height = height;
7111: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'></iframe>";
7112: modalWindow.open();
7113: };
7114: // END LON-CAPA Internal -->
7115: // ]]>
7116: </script>
7117: ENDMODAL
7118: }
7119:
7120: sub modal_link {
7121: my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
7122: unless ($width) { $width=480; }
7123: unless ($height) { $height=400; }
7124: unless ($scrolling) { $scrolling='yes'; }
7125: return '<a href="'.$link.'" target="'.$target.'" title="'.$title.'" onclick="openMyModal(\''.$link.'\','.$width.','.$height.',\''.$scrolling.'\'); return false;">'.
7126: $linktext.'</a>';
7127: }
7128:
7129: sub modal_adhoc_script {
7130: my ($funcname,$width,$height,$content)=@_;
7131: return (<<ENDADHOC);
7132: <script type="text/javascript">
7133: // <![CDATA[
7134: var $funcname = function()
7135: {
7136: modalWindow.windowId = "myModal";
7137: modalWindow.width = $width;
7138: modalWindow.height = $height;
7139: modalWindow.content = '$content';
7140: modalWindow.open();
7141: };
7142: // ]]>
7143: </script>
7144: ENDADHOC
7145: }
7146:
7147: sub modal_adhoc_inner {
7148: my ($funcname,$width,$height,$content)=@_;
7149: my $innerwidth=$width-20;
7150: $content=&js_ready(
7151: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7152: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
7153: $content.
7154: &end_scrollbox().
7155: &end_page()
7156: );
7157: return &modal_adhoc_script($funcname,$width,$height,$content);
7158: }
7159:
7160: sub modal_adhoc_window {
7161: my ($funcname,$width,$height,$content,$linktext)=@_;
7162: return &modal_adhoc_inner($funcname,$width,$height,$content).
7163: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7164: }
7165:
7166: sub modal_adhoc_launch {
7167: my ($funcname,$width,$height,$content)=@_;
7168: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7169: <script type="text/javascript">
7170: // <![CDATA[
7171: $funcname();
7172: // ]]>
7173: </script>
7174: ENDLAUNCH
7175: }
7176:
7177: sub modal_adhoc_close {
7178: return (<<ENDCLOSE);
7179: <script type="text/javascript">
7180: // <![CDATA[
7181: modalWindow.close();
7182: // ]]>
7183: </script>
7184: ENDCLOSE
7185: }
7186:
7187: sub togglebox_script {
7188: return(<<ENDTOGGLE);
7189: <script type="text/javascript">
7190: // <![CDATA[
7191: function LCtoggleDisplay(id,hidetext,showtext) {
7192: link = document.getElementById(id + "link").childNodes[0];
7193: with (document.getElementById(id).style) {
7194: if (display == "none" ) {
7195: display = "inline";
7196: link.nodeValue = hidetext;
7197: } else {
7198: display = "none";
7199: link.nodeValue = showtext;
7200: }
7201: }
7202: }
7203: // ]]>
7204: </script>
7205: ENDTOGGLE
7206: }
7207:
7208: sub start_togglebox {
7209: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7210: unless ($heading) { $heading=''; } else { $heading.=' '; }
7211: unless ($showtext) { $showtext=&mt('show'); }
7212: unless ($hidetext) { $hidetext=&mt('hide'); }
7213: unless ($headerbg) { $headerbg='#FFFFFF'; }
7214: return &start_data_table().
7215: &start_data_table_header_row().
7216: '<td bgcolor="'.$headerbg.'">'.$heading.
7217: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7218: $showtext.'\')">'.$showtext.'</a>]</td>'.
7219: &end_data_table_header_row().
7220: '<tr id="'.$id.'" style="display:none""><td>';
7221: }
7222:
7223: sub end_togglebox {
7224: return '</td></tr>'.&end_data_table();
7225: }
7226:
7227: sub LCprogressbar_script {
7228: my ($id)=@_;
7229: return(<<ENDPROGRESS);
7230: <script type="text/javascript">
7231: // <![CDATA[
7232: \$('#progressbar$id').progressbar({
7233: value: 0,
7234: change: function(event, ui) {
7235: var newVal = \$(this).progressbar('option', 'value');
7236: \$('.pblabel', this).text(LCprogressTxt);
7237: }
7238: });
7239: // ]]>
7240: </script>
7241: ENDPROGRESS
7242: }
7243:
7244: sub LCprogressbarUpdate_script {
7245: return(<<ENDPROGRESSUPDATE);
7246: <style type="text/css">
7247: .ui-progressbar { position:relative; }
7248: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7249: </style>
7250: <script type="text/javascript">
7251: // <![CDATA[
7252: var LCprogressTxt='---';
7253:
7254: function LCupdateProgress(percent,progresstext,id) {
7255: LCprogressTxt=progresstext;
7256: \$('#progressbar'+id).progressbar('value',percent);
7257: }
7258: // ]]>
7259: </script>
7260: ENDPROGRESSUPDATE
7261: }
7262:
7263: my $LClastpercent;
7264: my $LCidcnt;
7265: my $LCcurrentid;
7266:
7267: sub LCprogressbar {
7268: my ($r)=(@_);
7269: $LClastpercent=0;
7270: $LCidcnt++;
7271: $LCcurrentid=$$.'_'.$LCidcnt;
7272: my $starting=&mt('Starting');
7273: my $content=(<<ENDPROGBAR);
7274: <p>
7275: <div id="progressbar$LCcurrentid">
7276: <span class="pblabel">$starting</span>
7277: </div>
7278: </p>
7279: ENDPROGBAR
7280: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7281: }
7282:
7283: sub LCprogressbarUpdate {
7284: my ($r,$val,$text)=@_;
7285: unless ($val) {
7286: if ($LClastpercent) {
7287: $val=$LClastpercent;
7288: } else {
7289: $val=0;
7290: }
7291: }
7292: if ($val<0) { $val=0; }
7293: if ($val>100) { $val=0; }
7294: $LClastpercent=$val;
7295: unless ($text) { $text=$val.'%'; }
7296: $text=&js_ready($text);
7297: &r_print($r,<<ENDUPDATE);
7298: <script type="text/javascript">
7299: // <![CDATA[
7300: LCupdateProgress($val,'$text','$LCcurrentid');
7301: // ]]>
7302: </script>
7303: ENDUPDATE
7304: }
7305:
7306: sub LCprogressbarClose {
7307: my ($r)=@_;
7308: $LClastpercent=0;
7309: &r_print($r,<<ENDCLOSE);
7310: <script type="text/javascript">
7311: // <![CDATA[
7312: \$("#progressbar$LCcurrentid").hide('slow');
7313: // ]]>
7314: </script>
7315: ENDCLOSE
7316: }
7317:
7318: sub r_print {
7319: my ($r,$to_print)=@_;
7320: if ($r) {
7321: $r->print($to_print);
7322: $r->rflush();
7323: } else {
7324: print($to_print);
7325: }
7326: }
7327:
7328: sub html_encode {
7329: my ($result) = @_;
7330:
7331: $result = &HTML::Entities::encode($result,'<>&"');
7332:
7333: return $result;
7334: }
7335:
7336: sub js_ready {
7337: my ($result) = @_;
7338:
7339: $result =~ s/[\n\r]/ /xmsg;
7340: $result =~ s/\\/\\\\/xmsg;
7341: $result =~ s/'/\\'/xmsg;
7342: $result =~ s{</}{<\\/}xmsg;
7343:
7344: return $result;
7345: }
7346:
7347: sub validate_page {
7348: if ( exists($env{'internal.start_page'})
7349: && $env{'internal.start_page'} > 1) {
7350: &Apache::lonnet::logthis('start_page called multiple times '.
7351: $env{'internal.start_page'}.' '.
7352: $ENV{'request.filename'});
7353: }
7354: if ( exists($env{'internal.end_page'})
7355: && $env{'internal.end_page'} > 1) {
7356: &Apache::lonnet::logthis('end_page called multiple times '.
7357: $env{'internal.end_page'}.' '.
7358: $env{'request.filename'});
7359: }
7360: if ( exists($env{'internal.start_page'})
7361: && ! exists($env{'internal.end_page'})) {
7362: &Apache::lonnet::logthis('start_page called without end_page '.
7363: $env{'request.filename'});
7364: }
7365: if ( ! exists($env{'internal.start_page'})
7366: && exists($env{'internal.end_page'})) {
7367: &Apache::lonnet::logthis('end_page called without start_page'.
7368: $env{'request.filename'});
7369: }
7370: }
7371:
7372:
7373: sub start_scrollbox {
7374: my ($outerwidth,$width,$height,$id)=@_;
7375: unless ($outerwidth) { $outerwidth='520px'; }
7376: unless ($width) { $width='500px'; }
7377: unless ($height) { $height='200px'; }
7378: my ($table_id,$div_id);
7379: if ($id ne '') {
7380: $table_id = " id='table_$id'";
7381: $div_id = " id='div_$id'";
7382: }
7383: 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>";
7384: }
7385:
7386: sub end_scrollbox {
7387: return '</div></td></tr></table>';
7388: }
7389:
7390: sub simple_error_page {
7391: my ($r,$title,$msg) = @_;
7392: my $page =
7393: &Apache::loncommon::start_page($title).
7394: &mt($msg).
7395: &Apache::loncommon::end_page();
7396: if (ref($r)) {
7397: $r->print($page);
7398: return;
7399: }
7400: return $page;
7401: }
7402:
7403: {
7404: my @row_count;
7405:
7406: sub start_data_table_count {
7407: unshift(@row_count, 0);
7408: return;
7409: }
7410:
7411: sub end_data_table_count {
7412: shift(@row_count);
7413: return;
7414: }
7415:
7416: sub start_data_table {
7417: my ($add_class,$id) = @_;
7418: my $css_class = (join(' ','LC_data_table',$add_class));
7419: my $table_id;
7420: if (defined($id)) {
7421: $table_id = ' id="'.$id.'"';
7422: }
7423: &start_data_table_count();
7424: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
7425: }
7426:
7427: sub end_data_table {
7428: &end_data_table_count();
7429: return '</table>'."\n";;
7430: }
7431:
7432: sub start_data_table_row {
7433: my ($add_class, $id) = @_;
7434: $row_count[0]++;
7435: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7436: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7437: $id = (' id="'.$id.'"') unless ($id eq '');
7438: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7439: }
7440:
7441: sub continue_data_table_row {
7442: my ($add_class, $id) = @_;
7443: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7444: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7445: $id = (' id="'.$id.'"') unless ($id eq '');
7446: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7447: }
7448:
7449: sub end_data_table_row {
7450: return '</tr>'."\n";;
7451: }
7452:
7453: sub start_data_table_empty_row {
7454: # $row_count[0]++;
7455: return '<tr class="LC_empty_row" >'."\n";;
7456: }
7457:
7458: sub end_data_table_empty_row {
7459: return '</tr>'."\n";;
7460: }
7461:
7462: sub start_data_table_header_row {
7463: return '<tr class="LC_header_row">'."\n";;
7464: }
7465:
7466: sub end_data_table_header_row {
7467: return '</tr>'."\n";;
7468: }
7469:
7470: sub data_table_caption {
7471: my $caption = shift;
7472: return "<caption class=\"LC_caption\">$caption</caption>";
7473: }
7474: }
7475:
7476: =pod
7477:
7478: =item * &inhibit_menu_check($arg)
7479:
7480: Checks for a inhibitmenu state and generates output to preserve it
7481:
7482: Inputs: $arg - can be any of
7483: - undef - in which case the return value is a string
7484: to add into arguments list of a uri
7485: - 'input' - in which case the return value is a HTML
7486: <form> <input> field of type hidden to
7487: preserve the value
7488: - a url - in which case the return value is the url with
7489: the neccesary cgi args added to preserve the
7490: inhibitmenu state
7491: - a ref to a url - no return value, but the string is
7492: updated to include the neccessary cgi
7493: args to preserve the inhibitmenu state
7494:
7495: =cut
7496:
7497: sub inhibit_menu_check {
7498: my ($arg) = @_;
7499: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
7500: if ($arg eq 'input') {
7501: if ($env{'form.inhibitmenu'}) {
7502: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
7503: } else {
7504: return
7505: }
7506: }
7507: if ($env{'form.inhibitmenu'}) {
7508: if (ref($arg)) {
7509: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7510: } elsif ($arg eq '') {
7511: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
7512: } else {
7513: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
7514: }
7515: }
7516: if (!ref($arg)) {
7517: return $arg;
7518: }
7519: }
7520:
7521: ###############################################
7522:
7523: =pod
7524:
7525: =back
7526:
7527: =head1 User Information Routines
7528:
7529: =over 4
7530:
7531: =item * &get_users_function()
7532:
7533: Used by &bodytag to determine the current users primary role.
7534: Returns either 'student','coordinator','admin', or 'author'.
7535:
7536: =cut
7537:
7538: ###############################################
7539: sub get_users_function {
7540: my $function = 'norole';
7541: if ($env{'request.role'}=~/^(st)/) {
7542: $function='student';
7543: }
7544: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
7545: $function='coordinator';
7546: }
7547: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
7548: $function='admin';
7549: }
7550: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
7551: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
7552: $function='author';
7553: }
7554: return $function;
7555: }
7556:
7557: ###############################################
7558:
7559: =pod
7560:
7561: =item * &show_course()
7562:
7563: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
7564: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
7565:
7566: Inputs:
7567: None
7568:
7569: Outputs:
7570: Scalar: 1 if 'Course' to be used, 0 otherwise.
7571:
7572: =cut
7573:
7574: ###############################################
7575: sub show_course {
7576: my $course = !$env{'user.adv'};
7577: if (!$env{'user.adv'}) {
7578: foreach my $env (keys(%env)) {
7579: next if ($env !~ m/^user\.priv\./);
7580: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
7581: $course = 0;
7582: last;
7583: }
7584: }
7585: }
7586: return $course;
7587: }
7588:
7589: ###############################################
7590:
7591: =pod
7592:
7593: =item * &check_user_status()
7594:
7595: Determines current status of supplied role for a
7596: specific user. Roles can be active, previous or future.
7597:
7598: Inputs:
7599: user's domain, user's username, course's domain,
7600: course's number, optional section ID.
7601:
7602: Outputs:
7603: role status: active, previous or future.
7604:
7605: =cut
7606:
7607: sub check_user_status {
7608: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
7609: my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
7610: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
7611: my @uroles = keys %userinfo;
7612: my $srchstr;
7613: my $active_chk = 'none';
7614: my $now = time;
7615: if (@uroles > 0) {
7616: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
7617: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
7618: } else {
7619: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
7620: }
7621: if (grep/^\Q$srchstr\E$/,@uroles) {
7622: my $role_end = 0;
7623: my $role_start = 0;
7624: $active_chk = 'active';
7625: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
7626: $role_end = $1;
7627: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
7628: $role_start = $1;
7629: }
7630: }
7631: if ($role_start > 0) {
7632: if ($now < $role_start) {
7633: $active_chk = 'future';
7634: }
7635: }
7636: if ($role_end > 0) {
7637: if ($now > $role_end) {
7638: $active_chk = 'previous';
7639: }
7640: }
7641: }
7642: }
7643: return $active_chk;
7644: }
7645:
7646: ###############################################
7647:
7648: =pod
7649:
7650: =item * &get_sections()
7651:
7652: Determines all the sections for a course including
7653: sections with students and sections containing other roles.
7654: Incoming parameters:
7655:
7656: 1. domain
7657: 2. course number
7658: 3. reference to array containing roles for which sections should
7659: be gathered (optional).
7660: 4. reference to array containing status types for which sections
7661: should be gathered (optional).
7662:
7663: If the third argument is undefined, sections are gathered for any role.
7664: If the fourth argument is undefined, sections are gathered for any status.
7665: Permissible values are 'active' or 'future' or 'previous'.
7666:
7667: Returns section hash (keys are section IDs, values are
7668: number of users in each section), subject to the
7669: optional roles filter, optional status filter
7670:
7671: =cut
7672:
7673: ###############################################
7674: sub get_sections {
7675: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
7676: if (!defined($cdom) || !defined($cnum)) {
7677: my $cid = $env{'request.course.id'};
7678:
7679: return if (!defined($cid));
7680:
7681: $cdom = $env{'course.'.$cid.'.domain'};
7682: $cnum = $env{'course.'.$cid.'.num'};
7683: }
7684:
7685: my %sectioncount;
7686: my $now = time;
7687:
7688: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
7689: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
7690: my $sec_index = &Apache::loncoursedata::CL_SECTION();
7691: my $status_index = &Apache::loncoursedata::CL_STATUS();
7692: my $start_index = &Apache::loncoursedata::CL_START();
7693: my $end_index = &Apache::loncoursedata::CL_END();
7694: my $status;
7695: while (my ($student,$data) = each(%$classlist)) {
7696: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
7697: $data->[$status_index],
7698: $data->[$start_index],
7699: $data->[$end_index]);
7700: if ($stu_status eq 'Active') {
7701: $status = 'active';
7702: } elsif ($end < $now) {
7703: $status = 'previous';
7704: } elsif ($start > $now) {
7705: $status = 'future';
7706: }
7707: if ($section ne '-1' && $section !~ /^\s*$/) {
7708: if ((!defined($possible_status)) || (($status ne '') &&
7709: (grep/^\Q$status\E$/,@{$possible_status}))) {
7710: $sectioncount{$section}++;
7711: }
7712: }
7713: }
7714: }
7715: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7716: foreach my $user (sort(keys(%courseroles))) {
7717: if ($user !~ /^(\w{2})/) { next; }
7718: my ($role) = ($user =~ /^(\w{2})/);
7719: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
7720: my ($section,$status);
7721: if ($role eq 'cr' &&
7722: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
7723: $section=$1;
7724: }
7725: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
7726: if (!defined($section) || $section eq '-1') { next; }
7727: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
7728: if ($end == -1 && $start == -1) {
7729: next; #deleted role
7730: }
7731: if (!defined($possible_status)) {
7732: $sectioncount{$section}++;
7733: } else {
7734: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
7735: $status = 'active';
7736: } elsif ($end < $now) {
7737: $status = 'future';
7738: } elsif ($start > $now) {
7739: $status = 'previous';
7740: }
7741: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
7742: $sectioncount{$section}++;
7743: }
7744: }
7745: }
7746: return %sectioncount;
7747: }
7748:
7749: ###############################################
7750:
7751: =pod
7752:
7753: =item * &get_course_users()
7754:
7755: Retrieves usernames:domains for users in the specified course
7756: with specific role(s), and access status.
7757:
7758: Incoming parameters:
7759: 1. course domain
7760: 2. course number
7761: 3. access status: users must have - either active,
7762: previous, future, or all.
7763: 4. reference to array of permissible roles
7764: 5. reference to array of section restrictions (optional)
7765: 6. reference to results object (hash of hashes).
7766: 7. reference to optional userdata hash
7767: 8. reference to optional statushash
7768: 9. flag if privileged users (except those set to unhide in
7769: course settings) should be excluded
7770: Keys of top level results hash are roles.
7771: Keys of inner hashes are username:domain, with
7772: values set to access type.
7773: Optional userdata hash returns an array with arguments in the
7774: same order as loncoursedata::get_classlist() for student data.
7775:
7776: Optional statushash returns
7777:
7778: Entries for end, start, section and status are blank because
7779: of the possibility of multiple values for non-student roles.
7780:
7781: =cut
7782:
7783: ###############################################
7784:
7785: sub get_course_users {
7786: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
7787: my %idx = ();
7788: my %seclists;
7789:
7790: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
7791: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
7792: $idx{end} = &Apache::loncoursedata::CL_END();
7793: $idx{start} = &Apache::loncoursedata::CL_START();
7794: $idx{id} = &Apache::loncoursedata::CL_ID();
7795: $idx{section} = &Apache::loncoursedata::CL_SECTION();
7796: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
7797: $idx{status} = &Apache::loncoursedata::CL_STATUS();
7798:
7799: if (grep(/^st$/,@{$roles})) {
7800: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
7801: my $now = time;
7802: foreach my $student (keys(%{$classlist})) {
7803: my $match = 0;
7804: my $secmatch = 0;
7805: my $section = $$classlist{$student}[$idx{section}];
7806: my $status = $$classlist{$student}[$idx{status}];
7807: if ($section eq '') {
7808: $section = 'none';
7809: }
7810: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7811: if (grep(/^all$/,@{$sections})) {
7812: $secmatch = 1;
7813: } elsif ($$classlist{$student}[$idx{section}] eq '') {
7814: if (grep(/^none$/,@{$sections})) {
7815: $secmatch = 1;
7816: }
7817: } else {
7818: if (grep(/^\Q$section\E$/,@{$sections})) {
7819: $secmatch = 1;
7820: }
7821: }
7822: if (!$secmatch) {
7823: next;
7824: }
7825: }
7826: if (defined($$types{'active'})) {
7827: if ($$classlist{$student}[$idx{status}] eq 'Active') {
7828: push(@{$$users{st}{$student}},'active');
7829: $match = 1;
7830: }
7831: }
7832: if (defined($$types{'previous'})) {
7833: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
7834: push(@{$$users{st}{$student}},'previous');
7835: $match = 1;
7836: }
7837: }
7838: if (defined($$types{'future'})) {
7839: if ($$classlist{$student}[$idx{status}] eq 'Future') {
7840: push(@{$$users{st}{$student}},'future');
7841: $match = 1;
7842: }
7843: }
7844: if ($match) {
7845: push(@{$seclists{$student}},$section);
7846: if (ref($userdata) eq 'HASH') {
7847: $$userdata{$student} = $$classlist{$student};
7848: }
7849: if (ref($statushash) eq 'HASH') {
7850: $statushash->{$student}{'st'}{$section} = $status;
7851: }
7852: }
7853: }
7854: }
7855: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
7856: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7857: my $now = time;
7858: my %displaystatus = ( previous => 'Expired',
7859: active => 'Active',
7860: future => 'Future',
7861: );
7862: my %nothide;
7863: if ($hidepriv) {
7864: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
7865: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
7866: if ($user !~ /:/) {
7867: $nothide{join(':',split(/[\@]/,$user))}=1;
7868: } else {
7869: $nothide{$user} = 1;
7870: }
7871: }
7872: }
7873: foreach my $person (sort(keys(%coursepersonnel))) {
7874: my $match = 0;
7875: my $secmatch = 0;
7876: my $status;
7877: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
7878: $user =~ s/:$//;
7879: my ($end,$start) = split(/:/,$coursepersonnel{$person});
7880: if ($end == -1 || $start == -1) {
7881: next;
7882: }
7883: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
7884: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
7885: my ($uname,$udom) = split(/:/,$user);
7886: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
7887: if (grep(/^all$/,@{$sections})) {
7888: $secmatch = 1;
7889: } elsif ($usec eq '') {
7890: if (grep(/^none$/,@{$sections})) {
7891: $secmatch = 1;
7892: }
7893: } else {
7894: if (grep(/^\Q$usec\E$/,@{$sections})) {
7895: $secmatch = 1;
7896: }
7897: }
7898: if (!$secmatch) {
7899: next;
7900: }
7901: }
7902: if ($usec eq '') {
7903: $usec = 'none';
7904: }
7905: if ($uname ne '' && $udom ne '') {
7906: if ($hidepriv) {
7907: if ((&Apache::lonnet::privileged($uname,$udom)) &&
7908: (!$nothide{$uname.':'.$udom})) {
7909: next;
7910: }
7911: }
7912: if ($end > 0 && $end < $now) {
7913: $status = 'previous';
7914: } elsif ($start > $now) {
7915: $status = 'future';
7916: } else {
7917: $status = 'active';
7918: }
7919: foreach my $type (keys(%{$types})) {
7920: if ($status eq $type) {
7921: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
7922: push(@{$$users{$role}{$user}},$type);
7923: }
7924: $match = 1;
7925: }
7926: }
7927: if (($match) && (ref($userdata) eq 'HASH')) {
7928: if (!exists($$userdata{$uname.':'.$udom})) {
7929: &get_user_info($udom,$uname,\%idx,$userdata);
7930: }
7931: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
7932: push(@{$seclists{$uname.':'.$udom}},$usec);
7933: }
7934: if (ref($statushash) eq 'HASH') {
7935: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
7936: }
7937: }
7938: }
7939: }
7940: }
7941: if (grep(/^ow$/,@{$roles})) {
7942: if ((defined($cdom)) && (defined($cnum))) {
7943: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
7944: if ( defined($csettings{'internal.courseowner'}) ) {
7945: my $owner = $csettings{'internal.courseowner'};
7946: next if ($owner eq '');
7947: my ($ownername,$ownerdom);
7948: if ($owner =~ /^([^:]+):([^:]+)$/) {
7949: $ownername = $1;
7950: $ownerdom = $2;
7951: } else {
7952: $ownername = $owner;
7953: $ownerdom = $cdom;
7954: $owner = $ownername.':'.$ownerdom;
7955: }
7956: @{$$users{'ow'}{$owner}} = 'any';
7957: if (defined($userdata) &&
7958: !exists($$userdata{$owner})) {
7959: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
7960: if (!grep(/^none$/,@{$seclists{$owner}})) {
7961: push(@{$seclists{$owner}},'none');
7962: }
7963: if (ref($statushash) eq 'HASH') {
7964: $statushash->{$owner}{'ow'}{'none'} = 'Any';
7965: }
7966: }
7967: }
7968: }
7969: }
7970: foreach my $user (keys(%seclists)) {
7971: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
7972: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
7973: }
7974: }
7975: return;
7976: }
7977:
7978: sub get_user_info {
7979: my ($udom,$uname,$idx,$userdata) = @_;
7980: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
7981: &plainname($uname,$udom,'lastname');
7982: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
7983: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
7984: my %idhash = &Apache::lonnet::idrget($udom,($uname));
7985: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
7986: return;
7987: }
7988:
7989: ###############################################
7990:
7991: =pod
7992:
7993: =item * &get_user_quota()
7994:
7995: Retrieves quota assigned for storage of portfolio files for a user
7996:
7997: Incoming parameters:
7998: 1. user's username
7999: 2. user's domain
8000:
8001: Returns:
8002: 1. Disk quota (in Mb) assigned to student.
8003: 2. (Optional) Type of setting: custom or default
8004: (individually assigned or default for user's
8005: institutional status).
8006: 3. (Optional) - User's institutional status (e.g., faculty, staff
8007: or student - types as defined in localenroll::inst_usertypes
8008: for user's domain, which determines default quota for user.
8009: 4. (Optional) - Default quota which would apply to the user.
8010:
8011: If a value has been stored in the user's environment,
8012: it will return that, otherwise it returns the maximal default
8013: defined for the user's instituional status(es) in the domain.
8014:
8015: =cut
8016:
8017: ###############################################
8018:
8019:
8020: sub get_user_quota {
8021: my ($uname,$udom) = @_;
8022: my ($quota,$quotatype,$settingstatus,$defquota);
8023: if (!defined($udom)) {
8024: $udom = $env{'user.domain'};
8025: }
8026: if (!defined($uname)) {
8027: $uname = $env{'user.name'};
8028: }
8029: if (($udom eq '' || $uname eq '') ||
8030: ($udom eq 'public') && ($uname eq 'public')) {
8031: $quota = 0;
8032: $quotatype = 'default';
8033: $defquota = 0;
8034: } else {
8035: my $inststatus;
8036: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8037: $quota = $env{'environment.portfolioquota'};
8038: $inststatus = $env{'environment.inststatus'};
8039: } else {
8040: my %userenv =
8041: &Apache::lonnet::get('environment',['portfolioquota',
8042: 'inststatus'],$udom,$uname);
8043: my ($tmp) = keys(%userenv);
8044: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8045: $quota = $userenv{'portfolioquota'};
8046: $inststatus = $userenv{'inststatus'};
8047: } else {
8048: undef(%userenv);
8049: }
8050: }
8051: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
8052: if ($quota eq '') {
8053: $quota = $defquota;
8054: $quotatype = 'default';
8055: } else {
8056: $quotatype = 'custom';
8057: }
8058: }
8059: if (wantarray) {
8060: return ($quota,$quotatype,$settingstatus,$defquota);
8061: } else {
8062: return $quota;
8063: }
8064: }
8065:
8066: ###############################################
8067:
8068: =pod
8069:
8070: =item * &default_quota()
8071:
8072: Retrieves default quota assigned for storage of user portfolio files,
8073: given an (optional) user's institutional status.
8074:
8075: Incoming parameters:
8076: 1. domain
8077: 2. (Optional) institutional status(es). This is a : separated list of
8078: status types (e.g., faculty, staff, student etc.)
8079: which apply to the user for whom the default is being retrieved.
8080: If the institutional status string in undefined, the domain
8081: default quota will be returned.
8082:
8083: Returns:
8084: 1. Default disk quota (in Mb) for user portfolios in the domain.
8085: 2. (Optional) institutional type which determined the value of the
8086: default quota.
8087:
8088: If a value has been stored in the domain's configuration db,
8089: it will return that, otherwise it returns 20 (for backwards
8090: compatibility with domains which have not set up a configuration
8091: db file; the original statically defined portfolio quota was 20 Mb).
8092:
8093: If the user's status includes multiple types (e.g., staff and student),
8094: the largest default quota which applies to the user determines the
8095: default quota returned.
8096:
8097: =back
8098:
8099: =cut
8100:
8101: ###############################################
8102:
8103:
8104: sub default_quota {
8105: my ($udom,$inststatus) = @_;
8106: my ($defquota,$settingstatus);
8107: my %quotahash = &Apache::lonnet::get_dom('configuration',
8108: ['quotas'],$udom);
8109: if (ref($quotahash{'quotas'}) eq 'HASH') {
8110: if ($inststatus ne '') {
8111: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8112: foreach my $item (@statuses) {
8113: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8114: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
8115: if ($defquota eq '') {
8116: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8117: $settingstatus = $item;
8118: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
8119: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8120: $settingstatus = $item;
8121: }
8122: }
8123: } else {
8124: if ($quotahash{'quotas'}{$item} ne '') {
8125: if ($defquota eq '') {
8126: $defquota = $quotahash{'quotas'}{$item};
8127: $settingstatus = $item;
8128: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8129: $defquota = $quotahash{'quotas'}{$item};
8130: $settingstatus = $item;
8131: }
8132: }
8133: }
8134: }
8135: }
8136: if ($defquota eq '') {
8137: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8138: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
8139: } else {
8140: $defquota = $quotahash{'quotas'}{'default'};
8141: }
8142: $settingstatus = 'default';
8143: }
8144: } else {
8145: $settingstatus = 'default';
8146: $defquota = 20;
8147: }
8148: if (wantarray) {
8149: return ($defquota,$settingstatus);
8150: } else {
8151: return $defquota;
8152: }
8153: }
8154:
8155: sub get_secgrprole_info {
8156: my ($cdom,$cnum,$needroles,$type) = @_;
8157: my %sections_count = &get_sections($cdom,$cnum);
8158: my @sections = (sort {$a <=> $b} keys(%sections_count));
8159: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8160: my @groups = sort(keys(%curr_groups));
8161: my $allroles = [];
8162: my $rolehash;
8163: my $accesshash = {
8164: active => 'Currently has access',
8165: future => 'Will have future access',
8166: previous => 'Previously had access',
8167: };
8168: if ($needroles) {
8169: $rolehash = {'all' => 'all'};
8170: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8171: if (&Apache::lonnet::error(%user_roles)) {
8172: undef(%user_roles);
8173: }
8174: foreach my $item (keys(%user_roles)) {
8175: my ($role)=split(/\:/,$item,2);
8176: if ($role eq 'cr') { next; }
8177: if ($role =~ /^cr/) {
8178: $$rolehash{$role} = (split('/',$role))[3];
8179: } else {
8180: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
8181: }
8182: }
8183: foreach my $key (sort(keys(%{$rolehash}))) {
8184: push(@{$allroles},$key);
8185: }
8186: push (@{$allroles},'st');
8187: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
8188: }
8189: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
8190: }
8191:
8192: sub user_picker {
8193: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
8194: my $currdom = $dom;
8195: my %curr_selected = (
8196: srchin => 'dom',
8197: srchby => 'lastname',
8198: );
8199: my $srchterm;
8200: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
8201: if ($srch->{'srchby'} ne '') {
8202: $curr_selected{'srchby'} = $srch->{'srchby'};
8203: }
8204: if ($srch->{'srchin'} ne '') {
8205: $curr_selected{'srchin'} = $srch->{'srchin'};
8206: }
8207: if ($srch->{'srchtype'} ne '') {
8208: $curr_selected{'srchtype'} = $srch->{'srchtype'};
8209: }
8210: if ($srch->{'srchdomain'} ne '') {
8211: $currdom = $srch->{'srchdomain'};
8212: }
8213: $srchterm = $srch->{'srchterm'};
8214: }
8215: my %lt=&Apache::lonlocal::texthash(
8216: 'usr' => 'Search criteria',
8217: 'doma' => 'Domain/institution to search',
8218: 'uname' => 'username',
8219: 'lastname' => 'last name',
8220: 'lastfirst' => 'last name, first name',
8221: 'crs' => 'in this course',
8222: 'dom' => 'in selected LON-CAPA domain',
8223: 'alc' => 'all LON-CAPA',
8224: 'instd' => 'in institutional directory for selected domain',
8225: 'exact' => 'is',
8226: 'contains' => 'contains',
8227: 'begins' => 'begins with',
8228: 'youm' => "You must include some text to search for.",
8229: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
8230: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
8231: 'yomc' => "You must choose a domain when using an institutional directory search.",
8232: 'ymcd' => "You must choose a domain when using a domain search.",
8233: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
8234: 'whse' => "When searching by last,first you must include at least one character in the first name.",
8235: 'thfo' => "The following need to be corrected before the search can be run:",
8236: );
8237: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
8238: my $srchinsel = ' <select name="srchin">';
8239:
8240: my @srchins = ('crs','dom','alc','instd');
8241:
8242: foreach my $option (@srchins) {
8243: # FIXME 'alc' option unavailable until
8244: # loncreateuser::print_user_query_page()
8245: # has been completed.
8246: next if ($option eq 'alc');
8247: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
8248: next if ($option eq 'crs' && !$env{'request.course.id'});
8249: if ($curr_selected{'srchin'} eq $option) {
8250: $srchinsel .= '
8251: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8252: } else {
8253: $srchinsel .= '
8254: <option value="'.$option.'">'.$lt{$option}.'</option>';
8255: }
8256: }
8257: $srchinsel .= "\n </select>\n";
8258:
8259: my $srchbysel = ' <select name="srchby">';
8260: foreach my $option ('lastname','lastfirst','uname') {
8261: if ($curr_selected{'srchby'} eq $option) {
8262: $srchbysel .= '
8263: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8264: } else {
8265: $srchbysel .= '
8266: <option value="'.$option.'">'.$lt{$option}.'</option>';
8267: }
8268: }
8269: $srchbysel .= "\n </select>\n";
8270:
8271: my $srchtypesel = ' <select name="srchtype">';
8272: foreach my $option ('begins','contains','exact') {
8273: if ($curr_selected{'srchtype'} eq $option) {
8274: $srchtypesel .= '
8275: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8276: } else {
8277: $srchtypesel .= '
8278: <option value="'.$option.'">'.$lt{$option}.'</option>';
8279: }
8280: }
8281: $srchtypesel .= "\n </select>\n";
8282:
8283: my ($newuserscript,$new_user_create);
8284: my $context_dom = $env{'request.role.domain'};
8285: if ($context eq 'requestcrs') {
8286: if ($env{'form.coursedom'} ne '') {
8287: $context_dom = $env{'form.coursedom'};
8288: }
8289: }
8290: if ($forcenewuser) {
8291: if (ref($srch) eq 'HASH') {
8292: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
8293: if ($cancreate) {
8294: $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>';
8295: } else {
8296: my $helplink = 'javascript:helpMenu('."'display'".')';
8297: my %usertypetext = (
8298: official => 'institutional',
8299: unofficial => 'non-institutional',
8300: );
8301: $new_user_create = '<p class="LC_warning">'
8302: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
8303: .' '
8304: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
8305: ,'<a href="'.$helplink.'">','</a>')
8306: .'</p><br />';
8307: }
8308: }
8309: }
8310:
8311: $newuserscript = <<"ENDSCRIPT";
8312:
8313: function setSearch(createnew,callingForm) {
8314: if (createnew == 1) {
8315: for (var i=0; i<callingForm.srchby.length; i++) {
8316: if (callingForm.srchby.options[i].value == 'uname') {
8317: callingForm.srchby.selectedIndex = i;
8318: }
8319: }
8320: for (var i=0; i<callingForm.srchin.length; i++) {
8321: if ( callingForm.srchin.options[i].value == 'dom') {
8322: callingForm.srchin.selectedIndex = i;
8323: }
8324: }
8325: for (var i=0; i<callingForm.srchtype.length; i++) {
8326: if (callingForm.srchtype.options[i].value == 'exact') {
8327: callingForm.srchtype.selectedIndex = i;
8328: }
8329: }
8330: for (var i=0; i<callingForm.srchdomain.length; i++) {
8331: if (callingForm.srchdomain.options[i].value == '$context_dom') {
8332: callingForm.srchdomain.selectedIndex = i;
8333: }
8334: }
8335: }
8336: }
8337: ENDSCRIPT
8338:
8339: }
8340:
8341: my $output = <<"END_BLOCK";
8342: <script type="text/javascript">
8343: // <![CDATA[
8344: function validateEntry(callingForm) {
8345:
8346: var checkok = 1;
8347: var srchin;
8348: for (var i=0; i<callingForm.srchin.length; i++) {
8349: if ( callingForm.srchin[i].checked ) {
8350: srchin = callingForm.srchin[i].value;
8351: }
8352: }
8353:
8354: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
8355: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
8356: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
8357: var srchterm = callingForm.srchterm.value;
8358: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
8359: var msg = "";
8360:
8361: if (srchterm == "") {
8362: checkok = 0;
8363: msg += "$lt{'youm'}\\n";
8364: }
8365:
8366: if (srchtype== 'begins') {
8367: if (srchterm.length < 2) {
8368: checkok = 0;
8369: msg += "$lt{'thte'}\\n";
8370: }
8371: }
8372:
8373: if (srchtype== 'contains') {
8374: if (srchterm.length < 3) {
8375: checkok = 0;
8376: msg += "$lt{'thet'}\\n";
8377: }
8378: }
8379: if (srchin == 'instd') {
8380: if (srchdomain == '') {
8381: checkok = 0;
8382: msg += "$lt{'yomc'}\\n";
8383: }
8384: }
8385: if (srchin == 'dom') {
8386: if (srchdomain == '') {
8387: checkok = 0;
8388: msg += "$lt{'ymcd'}\\n";
8389: }
8390: }
8391: if (srchby == 'lastfirst') {
8392: if (srchterm.indexOf(",") == -1) {
8393: checkok = 0;
8394: msg += "$lt{'whus'}\\n";
8395: }
8396: if (srchterm.indexOf(",") == srchterm.length -1) {
8397: checkok = 0;
8398: msg += "$lt{'whse'}\\n";
8399: }
8400: }
8401: if (checkok == 0) {
8402: alert("$lt{'thfo'}\\n"+msg);
8403: return;
8404: }
8405: if (checkok == 1) {
8406: callingForm.submit();
8407: }
8408: }
8409:
8410: $newuserscript
8411:
8412: // ]]>
8413: </script>
8414:
8415: $new_user_create
8416:
8417: END_BLOCK
8418:
8419: $output .= &Apache::lonhtmlcommon::start_pick_box().
8420: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8421: $domform.
8422: &Apache::lonhtmlcommon::row_closure().
8423: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8424: $srchbysel.
8425: $srchtypesel.
8426: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8427: $srchinsel.
8428: &Apache::lonhtmlcommon::row_closure(1).
8429: &Apache::lonhtmlcommon::end_pick_box().
8430: '<br />';
8431: return $output;
8432: }
8433:
8434: sub user_rule_check {
8435: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
8436: my $response;
8437: if (ref($usershash) eq 'HASH') {
8438: foreach my $user (keys(%{$usershash})) {
8439: my ($uname,$udom) = split(/:/,$user);
8440: next if ($udom eq '' || $uname eq '');
8441: my ($id,$newuser);
8442: if (ref($usershash->{$user}) eq 'HASH') {
8443: $newuser = $usershash->{$user}->{'newuser'};
8444: $id = $usershash->{$user}->{'id'};
8445: }
8446: my $inst_response;
8447: if (ref($checks) eq 'HASH') {
8448: if (defined($checks->{'username'})) {
8449: ($inst_response,%{$inst_results->{$user}}) =
8450: &Apache::lonnet::get_instuser($udom,$uname);
8451: } elsif (defined($checks->{'id'})) {
8452: ($inst_response,%{$inst_results->{$user}}) =
8453: &Apache::lonnet::get_instuser($udom,undef,$id);
8454: }
8455: } else {
8456: ($inst_response,%{$inst_results->{$user}}) =
8457: &Apache::lonnet::get_instuser($udom,$uname);
8458: return;
8459: }
8460: if (!$got_rules->{$udom}) {
8461: my %domconfig = &Apache::lonnet::get_dom('configuration',
8462: ['usercreation'],$udom);
8463: if (ref($domconfig{'usercreation'}) eq 'HASH') {
8464: foreach my $item ('username','id') {
8465: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
8466: $$curr_rules{$udom}{$item} =
8467: $domconfig{'usercreation'}{$item.'_rule'};
8468: }
8469: }
8470: }
8471: $got_rules->{$udom} = 1;
8472: }
8473: foreach my $item (keys(%{$checks})) {
8474: if (ref($$curr_rules{$udom}) eq 'HASH') {
8475: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
8476: if (@{$$curr_rules{$udom}{$item}} > 0) {
8477: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
8478: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
8479: if ($rule_check{$rule}) {
8480: $$rulematch{$user}{$item} = $rule;
8481: if ($inst_response eq 'ok') {
8482: if (ref($inst_results) eq 'HASH') {
8483: if (ref($inst_results->{$user}) eq 'HASH') {
8484: if (keys(%{$inst_results->{$user}}) == 0) {
8485: $$alerts{$item}{$udom}{$uname} = 1;
8486: }
8487: }
8488: }
8489: }
8490: last;
8491: }
8492: }
8493: }
8494: }
8495: }
8496: }
8497: }
8498: }
8499: return;
8500: }
8501:
8502: sub user_rule_formats {
8503: my ($domain,$domdesc,$curr_rules,$check) = @_;
8504: my %text = (
8505: 'username' => 'Usernames',
8506: 'id' => 'IDs',
8507: );
8508: my $output;
8509: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
8510: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
8511: if (@{$ruleorder} > 0) {
8512: $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>';
8513: foreach my $rule (@{$ruleorder}) {
8514: if (ref($curr_rules) eq 'ARRAY') {
8515: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
8516: if (ref($rules->{$rule}) eq 'HASH') {
8517: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
8518: $rules->{$rule}{'desc'}.'</li>';
8519: }
8520: }
8521: }
8522: }
8523: $output .= '</ul>';
8524: }
8525: }
8526: return $output;
8527: }
8528:
8529: sub instrule_disallow_msg {
8530: my ($checkitem,$domdesc,$count,$mode) = @_;
8531: my $response;
8532: my %text = (
8533: item => 'username',
8534: items => 'usernames',
8535: match => 'matches',
8536: do => 'does',
8537: action => 'a username',
8538: one => 'one',
8539: );
8540: if ($count > 1) {
8541: $text{'item'} = 'usernames';
8542: $text{'match'} ='match';
8543: $text{'do'} = 'do';
8544: $text{'action'} = 'usernames',
8545: $text{'one'} = 'ones';
8546: }
8547: if ($checkitem eq 'id') {
8548: $text{'items'} = 'IDs';
8549: $text{'item'} = 'ID';
8550: $text{'action'} = 'an ID';
8551: if ($count > 1) {
8552: $text{'item'} = 'IDs';
8553: $text{'action'} = 'IDs';
8554: }
8555: }
8556: $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 />';
8557: if ($mode eq 'upload') {
8558: if ($checkitem eq 'username') {
8559: $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'}.");
8560: } elsif ($checkitem eq 'id') {
8561: $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.");
8562: }
8563: } elsif ($mode eq 'selfcreate') {
8564: if ($checkitem eq 'id') {
8565: $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.");
8566: }
8567: } else {
8568: if ($checkitem eq 'username') {
8569: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
8570: } elsif ($checkitem eq 'id') {
8571: $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.");
8572: }
8573: }
8574: return $response;
8575: }
8576:
8577: sub personal_data_fieldtitles {
8578: my %fieldtitles = &Apache::lonlocal::texthash (
8579: id => 'Student/Employee ID',
8580: permanentemail => 'E-mail address',
8581: lastname => 'Last Name',
8582: firstname => 'First Name',
8583: middlename => 'Middle Name',
8584: generation => 'Generation',
8585: gen => 'Generation',
8586: inststatus => 'Affiliation',
8587: );
8588: return %fieldtitles;
8589: }
8590:
8591: sub sorted_inst_types {
8592: my ($dom) = @_;
8593: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
8594: my $othertitle = &mt('All users');
8595: if ($env{'request.course.id'}) {
8596: $othertitle = &mt('Any users');
8597: }
8598: my @types;
8599: if (ref($order) eq 'ARRAY') {
8600: @types = @{$order};
8601: }
8602: if (@types == 0) {
8603: if (ref($usertypes) eq 'HASH') {
8604: @types = sort(keys(%{$usertypes}));
8605: }
8606: }
8607: if (keys(%{$usertypes}) > 0) {
8608: $othertitle = &mt('Other users');
8609: }
8610: return ($othertitle,$usertypes,\@types);
8611: }
8612:
8613: sub get_institutional_codes {
8614: my ($settings,$allcourses,$LC_code) = @_;
8615: # Get complete list of course sections to update
8616: my @currsections = ();
8617: my @currxlists = ();
8618: my $coursecode = $$settings{'internal.coursecode'};
8619:
8620: if ($$settings{'internal.sectionnums'} ne '') {
8621: @currsections = split(/,/,$$settings{'internal.sectionnums'});
8622: }
8623:
8624: if ($$settings{'internal.crosslistings'} ne '') {
8625: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
8626: }
8627:
8628: if (@currxlists > 0) {
8629: foreach (@currxlists) {
8630: if (m/^([^:]+):(\w*)$/) {
8631: unless (grep/^$1$/,@{$allcourses}) {
8632: push @{$allcourses},$1;
8633: $$LC_code{$1} = $2;
8634: }
8635: }
8636: }
8637: }
8638:
8639: if (@currsections > 0) {
8640: foreach (@currsections) {
8641: if (m/^(\w+):(\w*)$/) {
8642: my $sec = $coursecode.$1;
8643: my $lc_sec = $2;
8644: unless (grep/^$sec$/,@{$allcourses}) {
8645: push @{$allcourses},$sec;
8646: $$LC_code{$sec} = $lc_sec;
8647: }
8648: }
8649: }
8650: }
8651: return;
8652: }
8653:
8654: sub get_standard_codeitems {
8655: return ('Year','Semester','Department','Number','Section');
8656: }
8657:
8658: =pod
8659:
8660: =head1 Slot Helpers
8661:
8662: =over 4
8663:
8664: =item * sorted_slots()
8665:
8666: Sorts an array of slot names in order of an optional sort key,
8667: default sort is by slot start time (earliest first).
8668:
8669: Inputs:
8670:
8671: =over 4
8672:
8673: slotsarr - Reference to array of unsorted slot names.
8674:
8675: slots - Reference to hash of hash, where outer hash keys are slot names.
8676:
8677: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
8678:
8679: =back
8680:
8681: Returns:
8682:
8683: =over 4
8684:
8685: sorted - An array of slot names sorted by a specified sort key
8686: (default sort key is start time of the slot).
8687:
8688: =back
8689:
8690: =cut
8691:
8692:
8693: sub sorted_slots {
8694: my ($slotsarr,$slots,$sortkey) = @_;
8695: if ($sortkey eq '') {
8696: $sortkey = 'starttime';
8697: }
8698: my @sorted;
8699: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
8700: @sorted =
8701: sort {
8702: if (ref($slots->{$a}) && ref($slots->{$b})) {
8703: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
8704: }
8705: if (ref($slots->{$a})) { return -1;}
8706: if (ref($slots->{$b})) { return 1;}
8707: return 0;
8708: } @{$slotsarr};
8709: }
8710: return @sorted;
8711: }
8712:
8713: =pod
8714:
8715: =item * get_future_slots()
8716:
8717: Inputs:
8718:
8719: =over 4
8720:
8721: cnum - course number
8722:
8723: cdom - course domain
8724:
8725: now - current UNIX time
8726:
8727: symb - optional symb
8728:
8729: =back
8730:
8731: Returns:
8732:
8733: =over 4
8734:
8735: sorted_reservable - ref to array of student_schedulable slots currently
8736: reservable, ordered by end date of reservation period.
8737:
8738: reservable_now - ref to hash of student_schedulable slots currently
8739: reservable.
8740:
8741: Keys in inner hash are:
8742: (a) symb: either blank or symb to which slot use is restricted.
8743: (b) endreserve: end date of reservation period.
8744:
8745: sorted_future - ref to array of student_schedulable slots reservable in
8746: the future, ordered by start date of reservation period.
8747:
8748: future_reservable - ref to hash of student_schedulable slots reservable
8749: in the future.
8750:
8751: Keys in inner hash are:
8752: (a) symb: either blank or symb to which slot use is restricted.
8753: (b) startreserve: start date of reservation period.
8754:
8755: =back
8756:
8757: =cut
8758:
8759: sub get_future_slots {
8760: my ($cnum,$cdom,$now,$symb) = @_;
8761: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
8762: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
8763: foreach my $slot (keys(%slots)) {
8764: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
8765: if ($symb) {
8766: next if (($slots{$slot}->{'symb'} ne '') &&
8767: ($slots{$slot}->{'symb'} ne $symb));
8768: }
8769: if (($slots{$slot}->{'starttime'} > $now) &&
8770: ($slots{$slot}->{'endtime'} > $now)) {
8771: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
8772: my $userallowed = 0;
8773: if ($slots{$slot}->{'allowedsections'}) {
8774: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
8775: if (!defined($env{'request.role.sec'})
8776: && grep(/^No section assigned$/,@allowed_sec)) {
8777: $userallowed=1;
8778: } else {
8779: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
8780: $userallowed=1;
8781: }
8782: }
8783: unless ($userallowed) {
8784: if (defined($env{'request.course.groups'})) {
8785: my @groups = split(/:/,$env{'request.course.groups'});
8786: foreach my $group (@groups) {
8787: if (grep(/^\Q$group\E$/,@allowed_sec)) {
8788: $userallowed=1;
8789: last;
8790: }
8791: }
8792: }
8793: }
8794: }
8795: if ($slots{$slot}->{'allowedusers'}) {
8796: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
8797: my $user = $env{'user.name'}.':'.$env{'user.domain'};
8798: if (grep(/^\Q$user\E$/,@allowed_users)) {
8799: $userallowed = 1;
8800: }
8801: }
8802: next unless($userallowed);
8803: }
8804: my $startreserve = $slots{$slot}->{'startreserve'};
8805: my $endreserve = $slots{$slot}->{'endreserve'};
8806: my $symb = $slots{$slot}->{'symb'};
8807: if (($startreserve < $now) &&
8808: (!$endreserve || $endreserve > $now)) {
8809: my $lastres = $endreserve;
8810: if (!$lastres) {
8811: $lastres = $slots{$slot}->{'starttime'};
8812: }
8813: $reservable_now{$slot} = {
8814: symb => $symb,
8815: endreserve => $lastres
8816: };
8817: } elsif (($startreserve > $now) &&
8818: (!$endreserve || $endreserve > $startreserve)) {
8819: $future_reservable{$slot} = {
8820: symb => $symb,
8821: startreserve => $startreserve
8822: };
8823: }
8824: }
8825: }
8826: my @unsorted_reservable = keys(%reservable_now);
8827: if (@unsorted_reservable > 0) {
8828: @sorted_reservable =
8829: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
8830: }
8831: my @unsorted_future = keys(%future_reservable);
8832: if (@unsorted_future > 0) {
8833: @sorted_future =
8834: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
8835: }
8836: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
8837: }
8838:
8839: =pod
8840:
8841: =back
8842:
8843: =head1 HTTP Helpers
8844:
8845: =over 4
8846:
8847: =item * &get_unprocessed_cgi($query,$possible_names)
8848:
8849: Modify the %env hash to contain unprocessed CGI form parameters held in
8850: $query. The parameters listed in $possible_names (an array reference),
8851: will be set in $env{'form.name'} if they do not already exist.
8852:
8853: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
8854: $possible_names is an ref to an array of form element names. As an example:
8855: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
8856: will result in $env{'form.uname'} and $env{'form.udom'} being set.
8857:
8858: =cut
8859:
8860: sub get_unprocessed_cgi {
8861: my ($query,$possible_names)= @_;
8862: # $Apache::lonxml::debug=1;
8863: foreach my $pair (split(/&/,$query)) {
8864: my ($name, $value) = split(/=/,$pair);
8865: $name = &unescape($name);
8866: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
8867: $value =~ tr/+/ /;
8868: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
8869: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
8870: }
8871: }
8872: }
8873:
8874: =pod
8875:
8876: =item * &cacheheader()
8877:
8878: returns cache-controlling header code
8879:
8880: =cut
8881:
8882: sub cacheheader {
8883: unless ($env{'request.method'} eq 'GET') { return ''; }
8884: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
8885: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
8886: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
8887: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
8888: return $output;
8889: }
8890:
8891: =pod
8892:
8893: =item * &no_cache($r)
8894:
8895: specifies header code to not have cache
8896:
8897: =cut
8898:
8899: sub no_cache {
8900: my ($r) = @_;
8901: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
8902: $env{'request.method'} ne 'GET') { return ''; }
8903: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
8904: $r->no_cache(1);
8905: $r->header_out("Expires" => $date);
8906: $r->header_out("Pragma" => "no-cache");
8907: }
8908:
8909: sub content_type {
8910: my ($r,$type,$charset) = @_;
8911: if ($r) {
8912: # Note that printout.pl calls this with undef for $r.
8913: &no_cache($r);
8914: }
8915: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
8916: unless ($charset) {
8917: $charset=&Apache::lonlocal::current_encoding;
8918: }
8919: if ($charset) { $type.='; charset='.$charset; }
8920: if ($r) {
8921: $r->content_type($type);
8922: } else {
8923: print("Content-type: $type\n\n");
8924: }
8925: }
8926:
8927: =pod
8928:
8929: =item * &add_to_env($name,$value)
8930:
8931: adds $name to the %env hash with value
8932: $value, if $name already exists, the entry is converted to an array
8933: reference and $value is added to the array.
8934:
8935: =cut
8936:
8937: sub add_to_env {
8938: my ($name,$value)=@_;
8939: if (defined($env{$name})) {
8940: if (ref($env{$name})) {
8941: #already have multiple values
8942: push(@{ $env{$name} },$value);
8943: } else {
8944: #first time seeing multiple values, convert hash entry to an arrayref
8945: my $first=$env{$name};
8946: undef($env{$name});
8947: push(@{ $env{$name} },$first,$value);
8948: }
8949: } else {
8950: $env{$name}=$value;
8951: }
8952: }
8953:
8954: =pod
8955:
8956: =item * &get_env_multiple($name)
8957:
8958: gets $name from the %env hash, it seemlessly handles the cases where multiple
8959: values may be defined and end up as an array ref.
8960:
8961: returns an array of values
8962:
8963: =cut
8964:
8965: sub get_env_multiple {
8966: my ($name) = @_;
8967: my @values;
8968: if (defined($env{$name})) {
8969: # exists is it an array
8970: if (ref($env{$name})) {
8971: @values=@{ $env{$name} };
8972: } else {
8973: $values[0]=$env{$name};
8974: }
8975: }
8976: return(@values);
8977: }
8978:
8979: sub ask_for_embedded_content {
8980: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
8981: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
8982: my $num = 0;
8983: my $numremref = 0;
8984: my $numinvalid = 0;
8985: my $numpathchg = 0;
8986: my $numexisting = 0;
8987: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
8988: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
8989: my $current_path='/';
8990: if ($env{'form.currentpath'}) {
8991: $current_path = $env{'form.currentpath'};
8992: }
8993: if ($actionurl eq '/adm/coursegrp_portfolio') {
8994: $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8995: $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
8996: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
8997: } else {
8998: $udom = $env{'user.domain'};
8999: $uname = $env{'user.name'};
9000: $url = '/userfiles/portfolio';
9001: }
9002: $toplevel = $url.'/';
9003: $url .= $current_path;
9004: $getpropath = 1;
9005: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9006: ($actionurl eq '/adm/imsimport')) {
9007: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9008: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9009: $toplevel = $url;
9010: if ($rest ne '') {
9011: $url .= $rest;
9012: }
9013: } elsif ($actionurl eq '/adm/coursedocs') {
9014: if (ref($args) eq 'HASH') {
9015: $url = $args->{'docs_url'};
9016: $toplevel = $url;
9017: }
9018: }
9019: my $now = time();
9020: foreach my $embed_file (keys(%{$allfiles})) {
9021: my $absolutepath;
9022: if ($embed_file =~ m{^\w+://}) {
9023: $newfiles{$embed_file} = 1;
9024: $mapping{$embed_file} = $embed_file;
9025: } else {
9026: if ($embed_file =~ m{^/}) {
9027: $absolutepath = $embed_file;
9028: $embed_file =~ s{^(/+)}{};
9029: }
9030: if ($embed_file =~ m{/}) {
9031: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
9032: $path = &check_for_traversal($path,$url,$toplevel);
9033: my $item = $fname;
9034: if ($path ne '') {
9035: $item = $path.'/'.$fname;
9036: $subdependencies{$path}{$fname} = 1;
9037: } else {
9038: $dependencies{$item} = 1;
9039: }
9040: if ($absolutepath) {
9041: $mapping{$item} = $absolutepath;
9042: } else {
9043: $mapping{$item} = $embed_file;
9044: }
9045: } else {
9046: $dependencies{$embed_file} = 1;
9047: if ($absolutepath) {
9048: $mapping{$embed_file} = $absolutepath;
9049: } else {
9050: $mapping{$embed_file} = $embed_file;
9051: }
9052: }
9053: }
9054: }
9055: foreach my $path (keys(%subdependencies)) {
9056: my %currsubfile;
9057: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9058: my ($sublistref,$listerror) =
9059: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9060: if (ref($sublistref) eq 'ARRAY') {
9061: foreach my $line (@{$sublistref}) {
9062: my ($file_name,$rest) = split(/\&/,$line,2);
9063: $currsubfile{$file_name} = 1;
9064: }
9065: }
9066: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9067: if (opendir(my $dir,$url.'/'.$path)) {
9068: my @subdir_list = grep(!/^\./,readdir($dir));
9069: map {$currsubfile{$_} = 1;} @subdir_list;
9070: }
9071: }
9072: foreach my $file (keys(%{$subdependencies{$path}})) {
9073: if ($currsubfile{$file}) {
9074: my $item = $path.'/'.$file;
9075: unless ($mapping{$item} eq $item) {
9076: $pathchanges{$item} = 1;
9077: }
9078: $existing{$item} = 1;
9079: $numexisting ++;
9080: } else {
9081: $newfiles{$path.'/'.$file} = 1;
9082: }
9083: }
9084: }
9085: my %currfile;
9086: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9087: my ($dirlistref,$listerror) =
9088: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
9089: if (ref($dirlistref) eq 'ARRAY') {
9090: foreach my $line (@{$dirlistref}) {
9091: my ($file_name,$rest) = split(/\&/,$line,2);
9092: $currfile{$file_name} = 1;
9093: }
9094: }
9095: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9096: if (opendir(my $dir,$url)) {
9097: my @dir_list = grep(!/^\./,readdir($dir));
9098: map {$currfile{$_} = 1;} @dir_list;
9099: }
9100: }
9101: foreach my $file (keys(%dependencies)) {
9102: if ($currfile{$file}) {
9103: unless ($mapping{$file} eq $file) {
9104: $pathchanges{$file} = 1;
9105: }
9106: $existing{$file} = 1;
9107: $numexisting ++;
9108: } else {
9109: $newfiles{$file} = 1;
9110: }
9111: }
9112: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
9113: $upload_output .= &start_data_table_row().
9114: '<td><span class="LC_filename">'.$embed_file.'</span>';
9115: unless ($mapping{$embed_file} eq $embed_file) {
9116: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
9117: }
9118: $upload_output .= '</td><td>';
9119: if ($args->{'ignore_remote_references'}
9120: && $embed_file =~ m{^\w+://}) {
9121: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
9122: $numremref++;
9123: } elsif ($args->{'error_on_invalid_names'}
9124: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
9125:
9126: $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
9127: $numinvalid++;
9128: } else {
9129: $upload_output .= &embedded_file_element('upload_embedded',$num,
9130: $embed_file,\%mapping,
9131: $allfiles,$codebase);
9132: $num++;
9133: }
9134: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
9135: }
9136: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
9137: $upload_output .= &start_data_table_row().
9138: '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
9139: '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
9140: &Apache::loncommon::end_data_table_row()."\n";
9141: }
9142: if ($upload_output) {
9143: $upload_output = &start_data_table().
9144: $upload_output.
9145: &end_data_table()."\n";
9146: }
9147: my $applies = 0;
9148: if ($numremref) {
9149: $applies ++;
9150: }
9151: if ($numinvalid) {
9152: $applies ++;
9153: }
9154: if ($numexisting) {
9155: $applies ++;
9156: }
9157: if ($num) {
9158: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
9159: ' method="post" enctype="multipart/form-data">'."\n".
9160: $state.
9161: '<h3>'.&mt('Upload embedded files').
9162: ':</h3>'.$upload_output.'<br />'."\n".
9163: '<input type ="hidden" name="number_embedded_items" value="'.
9164: $num.'" />'."\n";
9165: if ($actionurl eq '') {
9166: $output .= '<input type="hidden" name="phase" value="three" />';
9167: }
9168: } elsif ($applies) {
9169: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
9170: if ($applies > 1) {
9171: $output .=
9172: &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
9173: if ($numremref) {
9174: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
9175: }
9176: if ($numinvalid) {
9177: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
9178: }
9179: if ($numexisting) {
9180: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
9181: }
9182: $output .= '</ul><br />';
9183: } elsif ($numremref) {
9184: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
9185: } elsif ($numinvalid) {
9186: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
9187: } elsif ($numexisting) {
9188: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
9189: }
9190: $output .= $upload_output.'<br />';
9191: }
9192: my ($pathchange_output,$chgcount);
9193: $chgcount = $num;
9194: if (keys(%pathchanges) > 0) {
9195: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
9196: if ($num) {
9197: $output .= &embedded_file_element('pathchange',$chgcount,
9198: $embed_file,\%mapping,
9199: $allfiles,$codebase);
9200: } else {
9201: $pathchange_output .=
9202: &start_data_table_row().
9203: '<td><input type ="checkbox" name="namechange" value="'.
9204: $chgcount.'" checked="checked" /></td>'.
9205: '<td>'.$mapping{$embed_file}.'</td>'.
9206: '<td>'.$embed_file.
9207: &embedded_file_element('pathchange',$numpathchg,$embed_file,
9208: \%mapping,$allfiles,$codebase).
9209: '</td>'.&end_data_table_row();
9210: }
9211: $numpathchg ++;
9212: $chgcount ++;
9213: }
9214: }
9215: if ($num) {
9216: if ($numpathchg) {
9217: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
9218: $numpathchg.'" />'."\n";
9219: }
9220: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9221: ($actionurl eq '/adm/imsimport')) {
9222: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
9223: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
9224: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
9225: }
9226: $output .= '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
9227: &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
9228: } elsif ($numpathchg) {
9229: my %pathchange = ();
9230: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
9231: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9232: $output .= '<p>'.&mt('or').'</p>';
9233: }
9234: }
9235: return ($output,$num,$numpathchg);
9236: }
9237:
9238: sub embedded_file_element {
9239: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
9240: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
9241: (ref($codebase) eq 'HASH'));
9242: my $output;
9243: if ($context eq 'upload_embedded') {
9244: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
9245: }
9246: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
9247: &escape($embed_file).'" />';
9248: unless (($context eq 'upload_embedded') &&
9249: ($mapping->{$embed_file} eq $embed_file)) {
9250: $output .='
9251: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
9252: }
9253: my $attrib;
9254: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
9255: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
9256: }
9257: $output .=
9258: "\n\t\t".
9259: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
9260: $attrib.'" />';
9261: if (exists($codebase->{$mapping->{$embed_file}})) {
9262: $output .=
9263: "\n\t\t".
9264: '<input name="codebase_'.$num.'" type="hidden" value="'.
9265: &escape($codebase->{$mapping->{$embed_file}}).'" />';
9266: }
9267: return $output;
9268: }
9269:
9270: sub upload_embedded {
9271: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
9272: $current_disk_usage,$hiddenstate,$actionurl) = @_;
9273: my (%pathchange,$output,$modifyform,$footer,$returnflag);
9274: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
9275: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
9276: my $orig_uploaded_filename =
9277: $env{'form.embedded_item_'.$i.'.filename'};
9278: foreach my $type ('orig','ref','attrib','codebase') {
9279: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
9280: $env{'form.embedded_'.$type.'_'.$i} =
9281: &unescape($env{'form.embedded_'.$type.'_'.$i});
9282: }
9283: }
9284: my ($path,$fname) =
9285: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
9286: # no path, whole string is fname
9287: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
9288: $fname = &Apache::lonnet::clean_filename($fname);
9289: # See if there is anything left
9290: next if ($fname eq '');
9291:
9292: # Check if file already exists as a file or directory.
9293: my ($state,$msg);
9294: if ($context eq 'portfolio') {
9295: my $port_path = $dirpath;
9296: if ($group ne '') {
9297: $port_path = "groups/$group/$port_path";
9298: }
9299: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
9300: $fname,$group,'embedded_item_'.$i,
9301: $dir_root,$port_path,$disk_quota,
9302: $current_disk_usage,$uname,$udom);
9303: if ($state eq 'will_exceed_quota'
9304: || $state eq 'file_locked') {
9305: $output .= $msg;
9306: next;
9307: }
9308: } elsif (($context eq 'author') || ($context eq 'testbank')) {
9309: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
9310: if ($state eq 'exists') {
9311: $output .= $msg;
9312: next;
9313: }
9314: }
9315: # Check if extension is valid
9316: if (($fname =~ /\.(\w+)$/) &&
9317: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
9318: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
9319: next;
9320: } elsif (($fname =~ /\.(\w+)$/) &&
9321: (!defined(&Apache::loncommon::fileembstyle($1)))) {
9322: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
9323: next;
9324: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
9325: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
9326: next;
9327: }
9328:
9329: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
9330: if ($context eq 'portfolio') {
9331: my $result;
9332: if ($state eq 'existingfile') {
9333: $result=
9334: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
9335: $dirpath.$env{'form.currentpath'}.$path);
9336: } else {
9337: $result=
9338: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
9339: $dirpath.
9340: $env{'form.currentpath'}.$path);
9341: if ($result !~ m|^/uploaded/|) {
9342: $output .= '<span class="LC_error">'
9343: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
9344: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
9345: .'</span><br />';
9346: next;
9347: } else {
9348: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9349: $path.$fname.'</span>').'<br />';
9350: }
9351: }
9352: } elsif ($context eq 'coursedoc') {
9353: my $result =
9354: &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
9355: $dirpath.'/'.$path);
9356: if ($result !~ m|^/uploaded/|) {
9357: $output .= '<span class="LC_error">'
9358: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
9359: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
9360: .'</span><br />';
9361: next;
9362: } else {
9363: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9364: $path.$fname.'</span>').'<br />';
9365: }
9366: } else {
9367: # Save the file
9368: my $target = $env{'form.embedded_item_'.$i};
9369: my $fullpath = $dir_root.$dirpath.'/'.$path;
9370: my $dest = $fullpath.$fname;
9371: my $url = $url_root.$dirpath.'/'.$path.$fname;
9372: my @parts=split(/\//,"$dirpath/$path");
9373: my $count;
9374: my $filepath = $dir_root;
9375: foreach my $subdir (@parts) {
9376: $filepath .= "/$subdir";
9377: if (!-e $filepath) {
9378: mkdir($filepath,0770);
9379: }
9380: }
9381: my $fh;
9382: if (!open($fh,'>'.$dest)) {
9383: &Apache::lonnet::logthis('Failed to create '.$dest);
9384: $output .= '<span class="LC_error">'.
9385: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
9386: '</span><br />';
9387: } else {
9388: if (!print $fh $env{'form.embedded_item_'.$i}) {
9389: &Apache::lonnet::logthis('Failed to write to '.$dest);
9390: $output .= '<span class="LC_error">'.
9391: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
9392: '</span><br />';
9393: } else {
9394: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
9395: $url.'</span>').'<br />';
9396: unless ($context eq 'testbank') {
9397: $footer .= &mt('View embedded file: [_1]',
9398: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
9399: }
9400: }
9401: close($fh);
9402: }
9403: }
9404: if ($env{'form.embedded_ref_'.$i}) {
9405: $pathchange{$i} = 1;
9406: }
9407: }
9408: if ($output) {
9409: $output = '<p>'.$output.'</p>';
9410: }
9411: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
9412: $returnflag = 'ok';
9413: if (keys(%pathchange) > 0) {
9414: if ($context eq 'portfolio') {
9415: $output .= '<p>'.&mt('or').'</p>';
9416: } elsif ($context eq 'testbank') {
9417: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
9418: $returnflag = 'modify_orightml';
9419: }
9420: }
9421: return ($output.$footer,$returnflag);
9422: }
9423:
9424: sub modify_html_form {
9425: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
9426: my $end = 0;
9427: my $modifyform;
9428: if ($context eq 'upload_embedded') {
9429: return unless (ref($pathchange) eq 'HASH');
9430: if ($env{'form.number_embedded_items'}) {
9431: $end += $env{'form.number_embedded_items'};
9432: }
9433: if ($env{'form.number_pathchange_items'}) {
9434: $end += $env{'form.number_pathchange_items'};
9435: }
9436: if ($end) {
9437: for (my $i=0; $i<$end; $i++) {
9438: if ($i < $env{'form.number_embedded_items'}) {
9439: next unless($pathchange->{$i});
9440: }
9441: $modifyform .=
9442: &start_data_table_row().
9443: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
9444: 'checked="checked" /></td>'.
9445: '<td>'.$env{'form.embedded_ref_'.$i}.
9446: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
9447: &escape($env{'form.embedded_ref_'.$i}).'" />'.
9448: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
9449: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
9450: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
9451: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
9452: '<td>'.$env{'form.embedded_orig_'.$i}.
9453: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
9454: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
9455: &end_data_table_row();
9456: }
9457: }
9458: } else {
9459: $modifyform = $pathchgtable;
9460: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9461: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
9462: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9463: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
9464: }
9465: }
9466: if ($modifyform) {
9467: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
9468: '<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".
9469: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
9470: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
9471: '</ol></p>'."\n".'<p>'.
9472: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
9473: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
9474: &start_data_table()."\n".
9475: &start_data_table_header_row().
9476: '<th>'.&mt('Change?').'</th>'.
9477: '<th>'.&mt('Current reference').'</th>'.
9478: '<th>'.&mt('Required reference').'</th>'.
9479: &end_data_table_header_row()."\n".
9480: $modifyform.
9481: &end_data_table().'<br />'."\n".$hiddenstate.
9482: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
9483: '</form>'."\n";
9484: }
9485: return;
9486: }
9487:
9488: sub modify_html_refs {
9489: my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
9490: my $container;
9491: if ($context eq 'portfolio') {
9492: $container = $env{'form.container'};
9493: } elsif ($context eq 'coursedoc') {
9494: $container = $env{'form.primaryurl'};
9495: } else {
9496: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
9497: }
9498: my (%allfiles,%codebase,$output,$content);
9499: my @changes = &get_env_multiple('form.namechange');
9500: return unless (@changes > 0);
9501: if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
9502: return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
9503: $content = &Apache::lonnet::getfile($container);
9504: return if ($content eq '-1');
9505: } else {
9506: return unless ($container =~ /^\Q$dir_root\E/);
9507: if (open(my $fh,"<$container")) {
9508: $content = join('', <$fh>);
9509: close($fh);
9510: } else {
9511: return;
9512: }
9513: }
9514: my ($count,$codebasecount) = (0,0);
9515: my $mm = new File::MMagic;
9516: my $mime_type = $mm->checktype_contents($content);
9517: if ($mime_type eq 'text/html') {
9518: my $parse_result =
9519: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
9520: \%codebase,\$content);
9521: if ($parse_result eq 'ok') {
9522: foreach my $i (@changes) {
9523: my $orig = &unescape($env{'form.embedded_orig_'.$i});
9524: my $ref = &unescape($env{'form.embedded_ref_'.$i});
9525: if ($allfiles{$ref}) {
9526: my $newname = $orig;
9527: my ($attrib_regexp,$codebase);
9528: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
9529: if ($attrib_regexp =~ /:/) {
9530: $attrib_regexp =~ s/\:/|/g;
9531: }
9532: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
9533: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
9534: $count += $numchg;
9535: }
9536: if ($env{'form.embedded_codebase_'.$i} ne '') {
9537: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
9538: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
9539: $codebasecount ++;
9540: }
9541: }
9542: }
9543: if ($count || $codebasecount) {
9544: my $saveresult;
9545: if ($context eq 'portfolio' || $context eq 'coursedoc') {
9546: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
9547: if ($url eq $container) {
9548: my ($fname) = ($container =~ m{/([^/]+)$});
9549: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9550: $count,'<span class="LC_filename">'.
9551: $fname.'</span>').'</p>';
9552: } else {
9553: $output = '<p class="LC_error">'.
9554: &mt('Error: update failed for: [_1].',
9555: '<span class="LC_filename">'.
9556: $container.'</span>').'</p>';
9557: }
9558: } else {
9559: if (open(my $fh,">$container")) {
9560: print $fh $content;
9561: close($fh);
9562: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
9563: $count,'<span class="LC_filename">'.
9564: $container.'</span>').'</p>';
9565: } else {
9566: $output = '<p class="LC_error">'.
9567: &mt('Error: could not update [_1].',
9568: '<span class="LC_filename">'.
9569: $container.'</span>').'</p>';
9570: }
9571: }
9572: }
9573: } else {
9574: &logthis('Failed to parse '.$container.
9575: ' to modify references: '.$parse_result);
9576: }
9577: }
9578: return $output;
9579: }
9580:
9581: sub check_for_existing {
9582: my ($path,$fname,$element) = @_;
9583: my ($state,$msg);
9584: if (-d $path.'/'.$fname) {
9585: $state = 'exists';
9586: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9587: } elsif (-e $path.'/'.$fname) {
9588: $state = 'exists';
9589: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
9590: }
9591: if ($state eq 'exists') {
9592: $msg = '<span class="LC_error">'.$msg.'</span><br />';
9593: }
9594: return ($state,$msg);
9595: }
9596:
9597: sub check_for_upload {
9598: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
9599: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
9600: my $filesize = length($env{'form.'.$element});
9601: if (!$filesize) {
9602: my $msg = '<span class="LC_error">'.
9603: &mt('Unable to upload [_1]. (size = [_2] bytes)',
9604: '<span class="LC_filename">'.$fname.'</span>',
9605: $filesize).'<br />'.
9606: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
9607: '</span>';
9608: return ('zero_bytes',$msg);
9609: }
9610: $filesize = $filesize/1000; #express in k (1024?)
9611: my $getpropath = 1;
9612: my ($dirlistref,$listerror) =
9613: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
9614: my $found_file = 0;
9615: my $locked_file = 0;
9616: my @lockers;
9617: my $navmap;
9618: if ($env{'request.course.id'}) {
9619: $navmap = Apache::lonnavmaps::navmap->new();
9620: }
9621: if (ref($dirlistref) eq 'ARRAY') {
9622: foreach my $line (@{$dirlistref}) {
9623: my ($file_name,$rest)=split(/\&/,$line,2);
9624: if ($file_name eq $fname){
9625: $file_name = $path.$file_name;
9626: if ($group ne '') {
9627: $file_name = $group.$file_name;
9628: }
9629: $found_file = 1;
9630: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
9631: foreach my $lock (@lockers) {
9632: if (ref($lock) eq 'ARRAY') {
9633: my ($symb,$crsid) = @{$lock};
9634: if ($crsid eq $env{'request.course.id'}) {
9635: if (ref($navmap)) {
9636: my $res = $navmap->getBySymb($symb);
9637: foreach my $part (@{$res->parts()}) {
9638: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
9639: unless (($slot_status == $res->RESERVED) ||
9640: ($slot_status == $res->RESERVED_LOCATION)) {
9641: $locked_file = 1;
9642: }
9643: }
9644: } else {
9645: $locked_file = 1;
9646: }
9647: } else {
9648: $locked_file = 1;
9649: }
9650: }
9651: }
9652: } else {
9653: my @info = split(/\&/,$rest);
9654: my $currsize = $info[6]/1000;
9655: if ($currsize < $filesize) {
9656: my $extra = $filesize - $currsize;
9657: if (($current_disk_usage + $extra) > $disk_quota) {
9658: my $msg = '<span class="LC_error">'.
9659: &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.',
9660: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
9661: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9662: $disk_quota,$current_disk_usage);
9663: return ('will_exceed_quota',$msg);
9664: }
9665: }
9666: }
9667: }
9668: }
9669: }
9670: if (($current_disk_usage + $filesize) > $disk_quota){
9671: my $msg = '<span class="LC_error">'.
9672: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
9673: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
9674: return ('will_exceed_quota',$msg);
9675: } elsif ($found_file) {
9676: if ($locked_file) {
9677: my $msg = '<span class="LC_error">';
9678: $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>');
9679: $msg .= '</span><br />';
9680: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
9681: return ('file_locked',$msg);
9682: } else {
9683: my $msg = '<span class="LC_error">';
9684: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
9685: $msg .= '</span>';
9686: return ('existingfile',$msg);
9687: }
9688: }
9689: }
9690:
9691: sub check_for_traversal {
9692: my ($path,$url,$toplevel) = @_;
9693: my @parts=split(/\//,$path);
9694: my $cleanpath;
9695: my $fullpath = $url;
9696: for (my $i=0;$i<@parts;$i++) {
9697: next if ($parts[$i] eq '.');
9698: if ($parts[$i] eq '..') {
9699: $fullpath =~ s{([^/]+/)$}{};
9700: } else {
9701: $fullpath .= $parts[$i].'/';
9702: }
9703: }
9704: if ($fullpath =~ /^\Q$url\E(.*)$/) {
9705: $cleanpath = $1;
9706: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
9707: my $curr_toprel = $1;
9708: my @parts = split(/\//,$curr_toprel);
9709: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
9710: my @urlparts = split(/\//,$url_toprel);
9711: my $doubledots;
9712: my $startdiff = -1;
9713: for (my $i=0; $i<@urlparts; $i++) {
9714: if ($startdiff == -1) {
9715: unless ($urlparts[$i] eq $parts[$i]) {
9716: $startdiff = $i;
9717: $doubledots .= '../';
9718: }
9719: } else {
9720: $doubledots .= '../';
9721: }
9722: }
9723: if ($startdiff > -1) {
9724: $cleanpath = $doubledots;
9725: for (my $i=$startdiff; $i<@parts; $i++) {
9726: $cleanpath .= $parts[$i].'/';
9727: }
9728: }
9729: }
9730: $cleanpath =~ s{(/)$}{};
9731: return $cleanpath;
9732: }
9733:
9734: sub is_archive_file {
9735: my ($mimetype) = @_;
9736: if (($mimetype eq 'application/octet-stream') ||
9737: ($mimetype eq 'application/x-stuffit') ||
9738: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
9739: return 1;
9740: }
9741: return;
9742: }
9743:
9744: sub decompress_form {
9745: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements) = @_;
9746: my %lt = &Apache::lonlocal::texthash (
9747: this => 'This file is an archive file.',
9748: youm => 'You may wish to extract its contents.',
9749: camt => 'Extraction of contents is recommended for Camtasia zip files.',
9750: perm => 'Permanently remove archive file after extraction of contents?',
9751: extr => 'Extract contents',
9752: yes => 'Yes',
9753: no => 'No',
9754: );
9755: my $output = '<p>'.$lt{'this'}.' '.$lt{'youm'}.'<br />';
9756: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
9757: $output .= $lt{'camt'};
9758: }
9759: $output .= '</p>';
9760: $output .= <<"START";
9761: <div id="uploadfileresult">
9762: <form name="uploaded_decompress" action="$action" method="post">
9763: <input type="hidden" name="archiveurl" value="$archiveurl" />
9764: START
9765: if (ref($hiddenelements) eq 'HASH') {
9766: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
9767: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
9768: }
9769: }
9770: $output .= <<"END";
9771: <span class="LC_nobreak">$lt{'perm'}
9772: <label><input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}</label>
9773: <label><input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label></span><br />
9774: <input type="submit" name="decompress" value="$lt{'extr'}" />
9775: </form>
9776: $noextract
9777: </div>
9778: END
9779: return $output;
9780: }
9781:
9782: sub decompress_uploaded_file {
9783: my ($file,$dir) = @_;
9784: &Apache::lonnet::appenv({'cgi.file' => $file});
9785: &Apache::lonnet::appenv({'cgi.dir' => $dir});
9786: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
9787: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
9788: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
9789: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
9790: my $decompressed = $env{'cgi.decompressed'};
9791: &Apache::lonnet::delenv('cgi.file');
9792: &Apache::lonnet::delenv('cgi.dir');
9793: &Apache::lonnet::delenv('cgi.decompressed');
9794: return ($decompressed,$result);
9795: }
9796:
9797: sub process_decompression {
9798: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
9799: my ($dir,$error,$warning,$output);
9800: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
9801: $error = &mt('File name not a supported archive file type.').
9802: '<br />'.&mt('File name should end with one of: [_1].',
9803: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
9804: } else {
9805: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
9806: if ($docuhome eq 'no_host') {
9807: $error = &mt('Could not determine home server for course.');
9808: } else {
9809: my @ids=&Apache::lonnet::current_machine_ids();
9810: my $currdir = "$dir_root/$destination";
9811: my ($currdirlistref,$currlisterror) =
9812: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
9813: if (grep(/^\Q$docuhome\E$/,@ids)) {
9814: $dir = &LONCAPA::propath($docudom,$docuname).
9815: "$dir_root/$destination";
9816: } else {
9817: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
9818: "$dir_root/$docudom/$docuname/$destination";
9819: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
9820: $error = &mt('Archive file not found.');
9821: }
9822: }
9823: if ($dir eq '') {
9824: $error = &mt('Directory containing archive file unavailable.');
9825: } elsif (!$error) {
9826: my ($decompressed,$display) = &decompress_uploaded_file($file,$dir);
9827: if ($decompressed eq 'ok') {
9828: $output = &mt('Files extracted successfully from archive.').'<br />';
9829: my ($warning,$result,@contents);
9830: my ($newdirlistref,$newlisterror) =
9831: &Apache::lonnet::dirlist($currdir,$docudom,
9832: $docuname,1);
9833: my (%is_dir,%changes,@newitems);
9834: my $dirptr = 16384;
9835: if (ref($currdirlistref) eq 'ARRAY') {
9836: my @curritems;
9837: foreach my $dir_line (@{$currdirlistref}) {
9838: my ($item,$rest)=split(/\&/,$dir_line,2);
9839: unless ($item =~ /\.+$/) {
9840: push(@curritems,$item);
9841: }
9842: }
9843: if (ref($newdirlistref) eq 'ARRAY') {
9844: foreach my $dir_line (@{$newdirlistref}) {
9845: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,4);
9846: unless ($item =~ /^\.+$/) {
9847: if ($dirptr&$testdir) {
9848: $is_dir{$item} = 1;
9849: }
9850: push(@newitems,$item);
9851: }
9852: }
9853: my @diffs = &compare_arrays(\@curritems,\@newitems);
9854: if (@diffs > 0) {
9855: foreach my $item (@diffs) {
9856: $changes{$item} = 1;
9857: }
9858: }
9859: }
9860: } elsif (ref($newdirlistref) eq 'ARRAY') {
9861: foreach my $dir_line (@{$newdirlistref}) {
9862: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
9863: unless ($item =~ /\.+$/) {
9864: push(@newitems,$item);
9865: if ($dirptr&$testdir) {
9866: $is_dir{$item} = 1;
9867: }
9868: $changes{$item} = 1;
9869: }
9870: }
9871: }
9872: if (keys(%changes) > 0) {
9873: foreach my $item (sort(@newitems)) {
9874: if ($changes{$item}) {
9875: push(@contents,$item);
9876: }
9877: }
9878: }
9879: if (@contents > 0) {
9880: my (%children,%parent,%dirorder,%titles);
9881: my $wantform = 1;
9882: my ($count,$datatable) = &get_extracted($docudom,$docuname,
9883: $currdir,\%is_dir,
9884: \%children,\%parent,
9885: \@contents,\%dirorder,
9886: \%titles,$wantform);
9887: if ($datatable ne '') {
9888: $output .= &archive_options_form('decompressed',$datatable,
9889: $count,$hiddenelem);
9890: my $startcount = 4;
9891: $output .= &archive_javascript($startcount,$count,
9892: \%titles,\%children);
9893: }
9894: } else {
9895: $warning = &mt('No new items extracted from archive file.');
9896: }
9897: } else {
9898: $output = $display;
9899: $error = &mt('An error occurred during extraction from the archive file.');
9900: }
9901: }
9902: }
9903: }
9904: if ($error) {
9905: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
9906: $error.'</p>'."\n";
9907: }
9908: if ($warning) {
9909: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
9910: }
9911: return $output;
9912: }
9913:
9914: sub get_extracted {
9915: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
9916: $titles,$wantform) = @_;
9917: my $count = 0;
9918: my $depth = 0;
9919: my $datatable;
9920: my @hierarchy;
9921: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
9922: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
9923: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
9924: foreach my $item (@{$contents}) {
9925: $count ++;
9926: @{$dirorder->{$count}} = @hierarchy;
9927: $titles->{$count} = $item;
9928: &archive_hierarchy($depth,$count,$parent,$children);
9929: if ($wantform) {
9930: $datatable .= &archive_row($is_dir->{$item},$item,
9931: $currdir,$depth,$count);
9932: }
9933: if ($is_dir->{$item}) {
9934: $depth ++;
9935: push(@hierarchy,$count);
9936: $parent->{$depth} = $count;
9937: $datatable .=
9938: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
9939: \$depth,\$count,\@hierarchy,$dirorder,
9940: $children,$parent,$titles,$wantform);
9941: $depth --;
9942: pop(@hierarchy);
9943: }
9944: }
9945: return ($count,$datatable);
9946: }
9947:
9948: sub recurse_extracted_archive {
9949: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
9950: $children,$parent,$titles,$wantform) = @_;
9951: my $result='';
9952: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
9953: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
9954: (ref($dirorder) eq 'HASH')) {
9955: return $result;
9956: }
9957: my $dirptr = 16384;
9958: my ($newdirlistref,$newlisterror) =
9959: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
9960: if (ref($newdirlistref) eq 'ARRAY') {
9961: foreach my $dir_line (@{$newdirlistref}) {
9962: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
9963: unless ($item =~ /^\.+$/) {
9964: $$count ++;
9965: @{$dirorder->{$$count}} = @{$hierarchy};
9966: $titles->{$$count} = $item;
9967: &archive_hierarchy($$depth,$$count,$parent,$children);
9968:
9969: my $is_dir;
9970: if ($dirptr&$testdir) {
9971: $is_dir = 1;
9972: }
9973: if ($wantform) {
9974: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
9975: }
9976: if ($is_dir) {
9977: $$depth ++;
9978: push(@{$hierarchy},$$count);
9979: $parent->{$$depth} = $$count;
9980: $result .=
9981: &recurse_extracted_archive("$currdir/$item",$docudom,
9982: $docuname,$depth,$count,
9983: $hierarchy,$dirorder,$children,
9984: $parent,$titles,$wantform);
9985: $$depth --;
9986: pop(@{$hierarchy});
9987: }
9988: }
9989: }
9990: }
9991: return $result;
9992: }
9993:
9994: sub archive_hierarchy {
9995: my ($depth,$count,$parent,$children) =@_;
9996: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
9997: if (exists($parent->{$depth})) {
9998: $children->{$parent->{$depth}} .= $count.':';
9999: }
10000: }
10001: return;
10002: }
10003:
10004: sub archive_row {
10005: my ($is_dir,$item,$currdir,$depth,$count) = @_;
10006: my ($name) = ($item =~ m{([^/]+)$});
10007: my %choices = &Apache::lonlocal::texthash (
10008: 'display' => 'Add as file',
10009: 'dependency' => 'Include as dependency',
10010: 'discard' => 'Discard',
10011: );
10012: if ($is_dir) {
10013: $choices{'display'} = &mt('Add as folder');
10014: }
10015: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
10016: my $offset = 0;
10017: foreach my $action ('display','dependency','discard') {
10018: $offset ++;
10019: $output .= '<td><span class="LC_nobreak">'.
10020: '<label><input type="radio" name="archive_'.$count.
10021: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
10022: my $text = $choices{$action};
10023: if ($is_dir) {
10024: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
10025: if ($action eq 'display') {
10026: $text = &mt('Add as folder');
10027: }
10028: } else {
10029: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
10030:
10031: }
10032: $output .= ' /> '.$choices{$action}.'</label></span>';
10033: if ($action eq 'dependency') {
10034: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
10035: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
10036: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
10037: '<option value=""></option>'."\n".
10038: '</select>'."\n".
10039: '</div>';
10040: } elsif ($action eq 'display') {
10041: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
10042: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
10043: '</div>';
10044: }
10045: $output .= '</td>';
10046: }
10047: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
10048: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
10049: for (my $i=0; $i<$depth; $i++) {
10050: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
10051: }
10052: if ($is_dir) {
10053: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
10054: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
10055: } else {
10056: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
10057: }
10058: $output .= ' '.$name.'</td>'."\n".
10059: &end_data_table_row();
10060: return $output;
10061: }
10062:
10063: sub archive_options_form {
10064: my ($form,$output,$count,$hiddenelem) = @_;
10065: return '<form name="'.$form.'" method="post" action="">'."\n".
10066: '<input type="hidden" name="phase" value="decompress_cleanup" />'."\n".
10067: '<p>'.
10068: &mt('How should each item be incorporated in the course?').
10069: '</p>'.
10070: '<div class="LC_columnSection"><fieldset>'.
10071: '<legend>'.&mt('Content actions for all').'</legend>'.
10072: '<input type="button" value="'.&mt('Add as folder/file').'" '.
10073: 'onclick="javascript:checkAll(document.'.$form.",'display'".')" />'.
10074: ' <input type="button" value="'.&mt('Include as dependency for a displayed file').'"'.
10075: ' onclick="javascript:checkAll(document.'.$form.",'dependency'".')" />'.
10076: ' <input type="button" value="'.&mt('Discard').'"'.
10077: ' onclick="javascript:checkAll(document.'.$form.",'discard'".')" />'.
10078: '</fieldset></div>'.
10079: &start_data_table()."\n".
10080: $output."\n".
10081: &end_data_table()."\n".
10082: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
10083: $hiddenelem.
10084: '<br /><input type="submit" name="archive_submit" value="'.&mt('Save').'" />'.
10085: '</form>';
10086: }
10087:
10088: sub archive_javascript {
10089: my ($startcount,$numitems,$titles,$children) = @_;
10090: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
10091: my $maintitle = $env{'form.comment'};
10092: my $scripttag = <<START;
10093: <script type="text/javascript">
10094: // <![CDATA[
10095:
10096: function checkAll(form,prefix) {
10097: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
10098: for (var i=0; i < form.elements.length; i++) {
10099: var id = form.elements[i].id;
10100: if ((id != '') && (id != undefined)) {
10101: if (idstr.test(id)) {
10102: if (form.elements[i].type == 'radio') {
10103: form.elements[i].checked = true;
10104: var nostart = i-$startcount;
10105: var offset = nostart%7;
10106: var count = (nostart-offset)/7;
10107: dependencyCheck(form,count,offset);
10108: }
10109: }
10110: }
10111: }
10112: }
10113:
10114: function propagateCheck(form,count) {
10115: if (count > 0) {
10116: var startelement = $startcount + ((count-1) * 7);
10117: for (var j=1; j<6; j++) {
10118: if ((j != 2) && (j != 4)) {
10119: var item = startelement + j;
10120: if (form.elements[item].type == 'radio') {
10121: if (form.elements[item].checked) {
10122: containerCheck(form,count,j);
10123: break;
10124: }
10125: }
10126: }
10127: }
10128: }
10129: }
10130:
10131: numitems = $numitems
10132: var titles = new Array(numitems);
10133: var parents = new Array(numitems);
10134: for (var i=0; i<numitems; i++) {
10135: parents[i] = new Array;
10136: }
10137: var maintitle = '$maintitle';
10138:
10139: START
10140:
10141: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
10142: my @contents = split(/:/,$children->{$container});
10143: for (my $i=0; $i<@contents; $i ++) {
10144: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
10145: }
10146: }
10147:
10148: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
10149: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
10150: }
10151:
10152: $scripttag .= <<END;
10153:
10154: function containerCheck(form,count,offset) {
10155: if (count > 0) {
10156: dependencyCheck(form,count,offset);
10157: var item = (offset+$startcount)+7*(count-1);
10158: form.elements[item].checked = true;
10159: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
10160: if (parents[count].length > 0) {
10161: for (var j=0; j<parents[count].length; j++) {
10162: containerCheck(form,parents[count][j],offset);
10163: }
10164: }
10165: }
10166: }
10167: }
10168:
10169: function dependencyCheck(form,count,offset) {
10170: if (count > 0) {
10171: var chosen = (offset+$startcount)+7*(count-1);
10172: var depitem = $startcount + ((count-1) * 7) + 4;
10173: var currtype = form.elements[depitem].type;
10174: if (form.elements[chosen].value == 'dependency') {
10175: document.getElementById('arc_depon_'+count).style.display='block';
10176: form.elements[depitem].options.length = 0;
10177: form.elements[depitem].options[0] = new Option('Select','',true,true);
10178: for (var i=1; i<count; i++) {
10179: var startelement = $startcount + (i-1) * 7;
10180: for (var j=1; j<6; j++) {
10181: if ((j != 2) && (j!= 4)) {
10182: var item = startelement + j;
10183: if (form.elements[item].type == 'radio') {
10184: if (form.elements[item].checked) {
10185: if (form.elements[item].value == 'display') {
10186: var n = form.elements[depitem].options.length;
10187: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
10188: }
10189: }
10190: }
10191: }
10192: }
10193: }
10194: } else {
10195: document.getElementById('arc_depon_'+count).style.display='none';
10196: form.elements[depitem].options.length = 0;
10197: form.elements[depitem].options[0] = new Option('Select','',true,true);
10198: }
10199: titleCheck(form,count,offset);
10200: }
10201: }
10202:
10203: function propagateSelect(form,count,offset) {
10204: if (count > 0) {
10205: var item = (2+offset+$startcount)+7*(count-1);
10206: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
10207: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10208: if (parents[count].length > 0) {
10209: for (var j=0; j<parents[count].length; j++) {
10210: containerSelect(form,parents[count][j],offset,picked);
10211: }
10212: }
10213: }
10214: }
10215: }
10216:
10217: function containerSelect(form,count,offset,picked) {
10218: if (count > 0) {
10219: var item = (1+offset+$startcount)+7*(count-1);
10220: if (form.elements[item].type == 'radio') {
10221: if (form.elements[item].value == 'dependency') {
10222: if (form.elements[item+1].type == 'select-one') {
10223: for (var i=0; i<form.elements[item+1].options.length; i++) {
10224: if (form.elements[item+1].options[i].value == picked) {
10225: form.elements[item+1].selectedIndex = i;
10226: break;
10227: }
10228: }
10229: }
10230: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
10231: if (parents[count].length > 0) {
10232: for (var j=0; j<parents[count].length; j++) {
10233: containerSelect(form,parents[count][j],offset,picked);
10234: }
10235: }
10236: }
10237: }
10238: }
10239: }
10240: }
10241:
10242: function titleCheck(form,count,offset) {
10243: if (count > 0) {
10244: var chosen = (offset+$startcount)+7*(count-1);
10245: var depitem = $startcount + ((count-1) * 7) + 2;
10246: var currtype = form.elements[depitem].type;
10247: if (form.elements[chosen].value == 'display') {
10248: document.getElementById('arc_title_'+count).style.display='block';
10249: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
10250: document.getElementById('archive_title_'+count).value=maintitle;
10251: }
10252: } else {
10253: document.getElementById('arc_title_'+count).style.display='none';
10254: if (currtype == 'text') {
10255: document.getElementById('archive_title_'+count).value='';
10256: }
10257: }
10258: }
10259: return;
10260: }
10261:
10262: // ]]>
10263: </script>
10264: END
10265: return $scripttag;
10266: }
10267:
10268: sub process_extracted_files {
10269: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
10270: my $numitems = $env{'form.archive_count'};
10271: return unless ($numitems);
10272: my @ids=&Apache::lonnet::current_machine_ids();
10273: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
10274: %folders,%containers,%mapinner);
10275: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10276: if (grep(/^\Q$docuhome\E$/,@ids)) {
10277: $prefix = &LONCAPA::propath($docudom,$docuname);
10278: $pathtocheck = "$dir_root/$destination";
10279: $dir = $dir_root;
10280: $ishome = 1;
10281: } else {
10282: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
10283: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
10284: $dir = "$dir_root/$docudom/$docuname";
10285: }
10286: my $currdir = "$dir_root/$destination";
10287: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
10288: if ($env{'form.folderpath'}) {
10289: my @items = split('&',$env{'form.folderpath'});
10290: $folders{'0'} = $items[-2];
10291: $containers{'0'}='sequence';
10292: } elsif ($env{'form.pagepath'}) {
10293: my @items = split('&',$env{'form.pagepath'});
10294: $folders{'0'} = $items[-2];
10295: $containers{'0'}='page';
10296: }
10297: my @archdirs = &get_env_multiple('form.archive_directory');
10298: if ($numitems) {
10299: for (my $i=1; $i<=$numitems; $i++) {
10300: my $path = $env{'form.archive_content_'.$i};
10301: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
10302: my $item = $1;
10303: $toplevelitems{$item} = $i;
10304: if (grep(/^\Q$i\E$/,@archdirs)) {
10305: $is_dir{$item} = 1;
10306: }
10307: }
10308: }
10309: }
10310: my ($output,%children,%parent,%titles,%dirorder);
10311: if (keys(%toplevelitems) > 0) {
10312: my @contents = sort(keys(%toplevelitems));
10313: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
10314: \%parent,\@contents,\%dirorder,\%titles);
10315: }
10316: my (%referrer,%orphaned,%todelete,%newdest,%newseqid);
10317: if ($numitems) {
10318: for (my $i=1; $i<=$numitems; $i++) {
10319: my $path = $env{'form.archive_content_'.$i};
10320: if ($path =~ /^\Q$pathtocheck\E/) {
10321: if ($env{'form.archive_'.$i} eq 'discard') {
10322: if ($prefix ne '' && $path ne '') {
10323: if (-e $prefix.$path) {
10324: $todelete{$prefix.$path} = 1;
10325: }
10326: }
10327: } elsif ($env{'form.archive_'.$i} eq 'display') {
10328: my ($docstitle,$title,$url,$outer);
10329: ($title) = ($path =~ m{/([^/]+)$});
10330: $docstitle = $env{'form.archive_title_'.$i};
10331: if ($docstitle eq '') {
10332: $docstitle = $title;
10333: }
10334: $outer = 0;
10335: if (ref($dirorder{$i}) eq 'ARRAY') {
10336: if (@{$dirorder{$i}} > 0) {
10337: foreach my $item (reverse(@{$dirorder{$i}})) {
10338: if ($env{'form.archive_'.$item} eq 'display') {
10339: $outer = $item;
10340: last;
10341: }
10342: }
10343: }
10344: }
10345: my ($errtext,$fatal) =
10346: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
10347: '/'.$folders{$outer}.'.'.
10348: $containers{$outer});
10349: next if ($fatal);
10350: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
10351: if ($context eq 'coursedocs') {
10352: $mapinner{$i} = time;
10353: $folders{$i} = 'default_'.$mapinner{$i};
10354: $containers{$i} = 'sequence';
10355: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
10356: $folders{$i}.'.'.$containers{$i};
10357: my $newidx = &LONCAPA::map::getresidx();
10358: $LONCAPA::map::resources[$newidx]=
10359: $docstitle.':'.$url.':false:normal:res';
10360: push(@LONCAPA::map::order,$newidx);
10361: my ($outtext,$errtext) =
10362: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
10363: $docuname.'/'.$folders{$outer}.
10364: '.'.$containers{$outer},1);
10365: $newseqid{$i} = $newidx;
10366: }
10367: } else {
10368: if ($context eq 'coursedocs') {
10369: my $newidx=&LONCAPA::map::getresidx();
10370: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
10371: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
10372: $title;
10373: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
10374: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
10375: }
10376: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
10377: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
10378: }
10379: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
10380: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
10381: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
10382: }
10383: $LONCAPA::map::resources[$newidx]=
10384: $docstitle.':'.$url.':false:normal:res';
10385: push(@LONCAPA::map::order, $newidx);
10386: my ($outtext,$errtext)=
10387: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
10388: $docuname.'/'.$folders{$outer}.
10389: '.'.$containers{$outer},1);
10390: }
10391: }
10392: } elsif ($env{'form.archive_'.$i} eq 'dependency') {
10393: my ($title) = ($path =~ m{/([^/]+)$});
10394: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
10395: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
10396: if (ref($dirorder{$i}) eq 'ARRAY') {
10397: my ($itemidx,$fullpath);
10398: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
10399: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
10400: my $container = $dirorder{$referrer{$i}}->[-1];
10401: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
10402: if ($dirorder{$i}->[$j] eq $container) {
10403: $itemidx = $j;
10404: }
10405: }
10406: }
10407: }
10408: if ($itemidx ne '') {
10409: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
10410: if ($mapinner{$referrer{$i}}) {
10411: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
10412: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
10413: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
10414: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
10415: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
10416: if (!-e $fullpath) {
10417: mkdir($fullpath,0755);
10418: }
10419: }
10420: } else {
10421: last;
10422: }
10423: }
10424: }
10425: } elsif ($newdest{$referrer{$i}}) {
10426: $fullpath = $newdest{$referrer{$i}};
10427: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
10428: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
10429: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
10430: last;
10431: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
10432: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
10433: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
10434: if (!-e $fullpath) {
10435: mkdir($fullpath,0755);
10436: }
10437: }
10438: } else {
10439: last;
10440: }
10441: }
10442: }
10443: if ($fullpath ne '') {
10444: system("mv $prefix$path $fullpath/$title");
10445: }
10446: }
10447: }
10448: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
10449: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
10450: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
10451: }
10452: }
10453: } else {
10454: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
10455: }
10456: }
10457: if (keys(%todelete)) {
10458: foreach my $key (keys(%todelete)) {
10459: unlink($key);
10460: unless ($ishome) {
10461: #FIXME Need to notify homeserver to delete files.
10462: }
10463: }
10464: }
10465: } else {
10466: $warning = &mt('No items found in archive.');
10467: }
10468: if ($error) {
10469: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10470: $error.'</p>'."\n";
10471: }
10472: if ($warning) {
10473: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10474: }
10475: return $output;
10476: }
10477:
10478: =pod
10479:
10480: =item * &get_turnedin_filepath()
10481:
10482: Determines path in a user's portfolio file for storage of files uploaded
10483: to a specific essayresponse or dropbox item.
10484:
10485: Inputs: 3 required + 1 optional.
10486: $symb is symb for resource, $uname and $udom are for current user (required).
10487: $caller is optional (can be "submission", if routine is called when storing
10488: an upoaded file when "Submit Answer" button was pressed).
10489:
10490: Returns array containing $path and $multiresp.
10491: $path is path in portfolio. $multiresp is 1 if this resource contains more
10492: than one file upload item. Callers of routine should append partid as a
10493: subdirectory to $path in cases where $multiresp is 1.
10494:
10495: Called by: homework/essayresponse.pm and homework/structuretags.pm
10496:
10497: =cut
10498:
10499: sub get_turnedin_filepath {
10500: my ($symb,$uname,$udom,$caller) = @_;
10501: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
10502: my $turnindir;
10503: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
10504: $turnindir = $userhash{'turnindir'};
10505: my ($path,$multiresp);
10506: if ($turnindir eq '') {
10507: if ($caller eq 'submission') {
10508: $turnindir = &mt('turned in');
10509: $turnindir =~ s/\W+/_/g;
10510: my %newhash = (
10511: 'turnindir' => $turnindir,
10512: );
10513: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
10514: }
10515: }
10516: if ($turnindir ne '') {
10517: $path = '/'.$turnindir.'/';
10518: my ($multipart,$turnin,@pathitems);
10519: my $navmap = Apache::lonnavmaps::navmap->new();
10520: if (defined($navmap)) {
10521: my $mapres = $navmap->getResourceByUrl($map);
10522: if (ref($mapres)) {
10523: my $pcslist = $mapres->map_hierarchy();
10524: if ($pcslist ne '') {
10525: foreach my $pc (split(/,/,$pcslist)) {
10526: my $res = $navmap->getByMapPc($pc);
10527: if (ref($res)) {
10528: my $title = $res->compTitle();
10529: $title =~ s/\W+/_/g;
10530: if ($title ne '') {
10531: push(@pathitems,$title);
10532: }
10533: }
10534: }
10535: }
10536: my $maptitle = $mapres->compTitle();
10537: $maptitle =~ s/\W+/_/g;
10538: if ($maptitle ne '') {
10539: push(@pathitems,$maptitle);
10540: }
10541: unless ($env{'request.state'} eq 'construct') {
10542: my $res = $navmap->getBySymb($symb);
10543: if (ref($res)) {
10544: my $partlist = $res->parts();
10545: my $totaluploads = 0;
10546: if (ref($partlist) eq 'ARRAY') {
10547: foreach my $part (@{$partlist}) {
10548: my @types = $res->responseType($part);
10549: my @ids = $res->responseIds($part);
10550: for (my $i=0; $i < scalar(@ids); $i++) {
10551: if ($types[$i] eq 'essay') {
10552: my $partid = $part.'_'.$ids[$i];
10553: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
10554: $totaluploads ++;
10555: }
10556: }
10557: }
10558: }
10559: if ($totaluploads > 1) {
10560: $multiresp = 1;
10561: }
10562: }
10563: }
10564: }
10565: } else {
10566: return;
10567: }
10568: } else {
10569: return;
10570: }
10571: my $restitle=&Apache::lonnet::gettitle($symb);
10572: $restitle =~ s/\W+/_/g;
10573: if ($restitle eq '') {
10574: $restitle = ($resurl =~ m{/[^/]+$});
10575: if ($restitle eq '') {
10576: $restitle = time;
10577: }
10578: }
10579: push(@pathitems,$restitle);
10580: $path .= join('/',@pathitems);
10581: }
10582: return ($path,$multiresp);
10583: }
10584:
10585: =pod
10586:
10587: =back
10588:
10589: =head1 CSV Upload/Handling functions
10590:
10591: =over 4
10592:
10593: =item * &upfile_store($r)
10594:
10595: Store uploaded file, $r should be the HTTP Request object,
10596: needs $env{'form.upfile'}
10597: returns $datatoken to be put into hidden field
10598:
10599: =cut
10600:
10601: sub upfile_store {
10602: my $r=shift;
10603: $env{'form.upfile'}=~s/\r/\n/gs;
10604: $env{'form.upfile'}=~s/\f/\n/gs;
10605: $env{'form.upfile'}=~s/\n+/\n/gs;
10606: $env{'form.upfile'}=~s/\n+$//gs;
10607:
10608: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
10609: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
10610: {
10611: my $datafile = $r->dir_config('lonDaemons').
10612: '/tmp/'.$datatoken.'.tmp';
10613: if ( open(my $fh,">$datafile") ) {
10614: print $fh $env{'form.upfile'};
10615: close($fh);
10616: }
10617: }
10618: return $datatoken;
10619: }
10620:
10621: =pod
10622:
10623: =item * &load_tmp_file($r)
10624:
10625: Load uploaded file from tmp, $r should be the HTTP Request object,
10626: needs $env{'form.datatoken'},
10627: sets $env{'form.upfile'} to the contents of the file
10628:
10629: =cut
10630:
10631: sub load_tmp_file {
10632: my $r=shift;
10633: my @studentdata=();
10634: {
10635: my $studentfile = $r->dir_config('lonDaemons').
10636: '/tmp/'.$env{'form.datatoken'}.'.tmp';
10637: if ( open(my $fh,"<$studentfile") ) {
10638: @studentdata=<$fh>;
10639: close($fh);
10640: }
10641: }
10642: $env{'form.upfile'}=join('',@studentdata);
10643: }
10644:
10645: =pod
10646:
10647: =item * &upfile_record_sep()
10648:
10649: Separate uploaded file into records
10650: returns array of records,
10651: needs $env{'form.upfile'} and $env{'form.upfiletype'}
10652:
10653: =cut
10654:
10655: sub upfile_record_sep {
10656: if ($env{'form.upfiletype'} eq 'xml') {
10657: } else {
10658: my @records;
10659: foreach my $line (split(/\n/,$env{'form.upfile'})) {
10660: if ($line=~/^\s*$/) { next; }
10661: push(@records,$line);
10662: }
10663: return @records;
10664: }
10665: }
10666:
10667: =pod
10668:
10669: =item * &record_sep($record)
10670:
10671: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
10672:
10673: =cut
10674:
10675: sub takeleft {
10676: my $index=shift;
10677: return substr('0000'.$index,-4,4);
10678: }
10679:
10680: sub record_sep {
10681: my $record=shift;
10682: my %components=();
10683: if ($env{'form.upfiletype'} eq 'xml') {
10684: } elsif ($env{'form.upfiletype'} eq 'space') {
10685: my $i=0;
10686: foreach my $field (split(/\s+/,$record)) {
10687: $field=~s/^(\"|\')//;
10688: $field=~s/(\"|\')$//;
10689: $components{&takeleft($i)}=$field;
10690: $i++;
10691: }
10692: } elsif ($env{'form.upfiletype'} eq 'tab') {
10693: my $i=0;
10694: foreach my $field (split(/\t/,$record)) {
10695: $field=~s/^(\"|\')//;
10696: $field=~s/(\"|\')$//;
10697: $components{&takeleft($i)}=$field;
10698: $i++;
10699: }
10700: } else {
10701: my $separator=',';
10702: if ($env{'form.upfiletype'} eq 'semisv') {
10703: $separator=';';
10704: }
10705: my $i=0;
10706: # the character we are looking for to indicate the end of a quote or a record
10707: my $looking_for=$separator;
10708: # do not add the characters to the fields
10709: my $ignore=0;
10710: # we just encountered a separator (or the beginning of the record)
10711: my $just_found_separator=1;
10712: # store the field we are working on here
10713: my $field='';
10714: # work our way through all characters in record
10715: foreach my $character ($record=~/(.)/g) {
10716: if ($character eq $looking_for) {
10717: if ($character ne $separator) {
10718: # Found the end of a quote, again looking for separator
10719: $looking_for=$separator;
10720: $ignore=1;
10721: } else {
10722: # Found a separator, store away what we got
10723: $components{&takeleft($i)}=$field;
10724: $i++;
10725: $just_found_separator=1;
10726: $ignore=0;
10727: $field='';
10728: }
10729: next;
10730: }
10731: # single or double quotation marks after a separator indicate beginning of a quote
10732: # we are now looking for the end of the quote and need to ignore separators
10733: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
10734: $looking_for=$character;
10735: next;
10736: }
10737: # ignore would be true after we reached the end of a quote
10738: if ($ignore) { next; }
10739: if (($just_found_separator) && ($character=~/\s/)) { next; }
10740: $field.=$character;
10741: $just_found_separator=0;
10742: }
10743: # catch the very last entry, since we never encountered the separator
10744: $components{&takeleft($i)}=$field;
10745: }
10746: return %components;
10747: }
10748:
10749: ######################################################
10750: ######################################################
10751:
10752: =pod
10753:
10754: =item * &upfile_select_html()
10755:
10756: Return HTML code to select a file from the users machine and specify
10757: the file type.
10758:
10759: =cut
10760:
10761: ######################################################
10762: ######################################################
10763: sub upfile_select_html {
10764: my %Types = (
10765: csv => &mt('CSV (comma separated values, spreadsheet)'),
10766: semisv => &mt('Semicolon separated values'),
10767: space => &mt('Space separated'),
10768: tab => &mt('Tabulator separated'),
10769: # xml => &mt('HTML/XML'),
10770: );
10771: my $Str = '<input type="file" name="upfile" size="50" />'.
10772: '<br />'.&mt('Type').': <select name="upfiletype">';
10773: foreach my $type (sort(keys(%Types))) {
10774: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
10775: }
10776: $Str .= "</select>\n";
10777: return $Str;
10778: }
10779:
10780: sub get_samples {
10781: my ($records,$toget) = @_;
10782: my @samples=({});
10783: my $got=0;
10784: foreach my $rec (@$records) {
10785: my %temp = &record_sep($rec);
10786: if (! grep(/\S/, values(%temp))) { next; }
10787: if (%temp) {
10788: $samples[$got]=\%temp;
10789: $got++;
10790: if ($got == $toget) { last; }
10791: }
10792: }
10793: return \@samples;
10794: }
10795:
10796: ######################################################
10797: ######################################################
10798:
10799: =pod
10800:
10801: =item * &csv_print_samples($r,$records)
10802:
10803: Prints a table of sample values from each column uploaded $r is an
10804: Apache Request ref, $records is an arrayref from
10805: &Apache::loncommon::upfile_record_sep
10806:
10807: =cut
10808:
10809: ######################################################
10810: ######################################################
10811: sub csv_print_samples {
10812: my ($r,$records) = @_;
10813: my $samples = &get_samples($records,5);
10814:
10815: $r->print(&mt('Samples').'<br />'.&start_data_table().
10816: &start_data_table_header_row());
10817: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
10818: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
10819: $r->print(&end_data_table_header_row());
10820: foreach my $hash (@$samples) {
10821: $r->print(&start_data_table_row());
10822: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
10823: $r->print('<td>');
10824: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
10825: $r->print('</td>');
10826: }
10827: $r->print(&end_data_table_row());
10828: }
10829: $r->print(&end_data_table().'<br />'."\n");
10830: }
10831:
10832: ######################################################
10833: ######################################################
10834:
10835: =pod
10836:
10837: =item * &csv_print_select_table($r,$records,$d)
10838:
10839: Prints a table to create associations between values and table columns.
10840:
10841: $r is an Apache Request ref,
10842: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
10843: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
10844:
10845: =cut
10846:
10847: ######################################################
10848: ######################################################
10849: sub csv_print_select_table {
10850: my ($r,$records,$d) = @_;
10851: my $i=0;
10852: my $samples = &get_samples($records,1);
10853: $r->print(&mt('Associate columns with student attributes.')."\n".
10854: &start_data_table().&start_data_table_header_row().
10855: '<th>'.&mt('Attribute').'</th>'.
10856: '<th>'.&mt('Column').'</th>'.
10857: &end_data_table_header_row()."\n");
10858: foreach my $array_ref (@$d) {
10859: my ($value,$display,$defaultcol)=@{ $array_ref };
10860: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
10861:
10862: $r->print('<td><select name="f'.$i.'"'.
10863: ' onchange="javascript:flip(this.form,'.$i.');">');
10864: $r->print('<option value="none"></option>');
10865: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
10866: $r->print('<option value="'.$sample.'"'.
10867: ($sample eq $defaultcol ? ' selected="selected" ' : '').
10868: '>'.&mt('Column [_1]',($sample+1)).'</option>');
10869: }
10870: $r->print('</select></td>'.&end_data_table_row()."\n");
10871: $i++;
10872: }
10873: $r->print(&end_data_table());
10874: $i--;
10875: return $i;
10876: }
10877:
10878: ######################################################
10879: ######################################################
10880:
10881: =pod
10882:
10883: =item * &csv_samples_select_table($r,$records,$d)
10884:
10885: Prints a table of sample values from the upload and can make associate samples to internal names.
10886:
10887: $r is an Apache Request ref,
10888: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
10889: $d is an array of 2 element arrays (internal name, displayed name)
10890:
10891: =cut
10892:
10893: ######################################################
10894: ######################################################
10895: sub csv_samples_select_table {
10896: my ($r,$records,$d) = @_;
10897: my $i=0;
10898: #
10899: my $max_samples = 5;
10900: my $samples = &get_samples($records,$max_samples);
10901: $r->print(&start_data_table().
10902: &start_data_table_header_row().'<th>'.
10903: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
10904: &end_data_table_header_row());
10905:
10906: foreach my $key (sort(keys(%{ $samples->[0] }))) {
10907: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
10908: ' onchange="javascript:flip(this.form,'.$i.');">');
10909: foreach my $option (@$d) {
10910: my ($value,$display,$defaultcol)=@{ $option };
10911: $r->print('<option value="'.$value.'"'.
10912: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
10913: $display.'</option>');
10914: }
10915: $r->print('</select></td><td>');
10916: foreach my $line (0..($max_samples-1)) {
10917: if (defined($samples->[$line]{$key})) {
10918: $r->print($samples->[$line]{$key}."<br />\n");
10919: }
10920: }
10921: $r->print('</td>'.&end_data_table_row());
10922: $i++;
10923: }
10924: $r->print(&end_data_table());
10925: $i--;
10926: return($i);
10927: }
10928:
10929: ######################################################
10930: ######################################################
10931:
10932: =pod
10933:
10934: =item * &clean_excel_name($name)
10935:
10936: Returns a replacement for $name which does not contain any illegal characters.
10937:
10938: =cut
10939:
10940: ######################################################
10941: ######################################################
10942: sub clean_excel_name {
10943: my ($name) = @_;
10944: $name =~ s/[:\*\?\/\\]//g;
10945: if (length($name) > 31) {
10946: $name = substr($name,0,31);
10947: }
10948: return $name;
10949: }
10950:
10951: =pod
10952:
10953: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
10954:
10955: Returns either 1 or undef
10956:
10957: 1 if the part is to be hidden, undef if it is to be shown
10958:
10959: Arguments are:
10960:
10961: $id the id of the part to be checked
10962: $symb, optional the symb of the resource to check
10963: $udom, optional the domain of the user to check for
10964: $uname, optional the username of the user to check for
10965:
10966: =cut
10967:
10968: sub check_if_partid_hidden {
10969: my ($id,$symb,$udom,$uname) = @_;
10970: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
10971: $symb,$udom,$uname);
10972: my $truth=1;
10973: #if the string starts with !, then the list is the list to show not hide
10974: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
10975: my @hiddenlist=split(/,/,$hiddenparts);
10976: foreach my $checkid (@hiddenlist) {
10977: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
10978: }
10979: return !$truth;
10980: }
10981:
10982:
10983: ############################################################
10984: ############################################################
10985:
10986: =pod
10987:
10988: =back
10989:
10990: =head1 cgi-bin script and graphing routines
10991:
10992: =over 4
10993:
10994: =item * &get_cgi_id()
10995:
10996: Inputs: none
10997:
10998: Returns an id which can be used to pass environment variables
10999: to various cgi-bin scripts. These environment variables will
11000: be removed from the users environment after a given time by
11001: the routine &Apache::lonnet::transfer_profile_to_env.
11002:
11003: =cut
11004:
11005: ############################################################
11006: ############################################################
11007: my $uniq=0;
11008: sub get_cgi_id {
11009: $uniq=($uniq+1)%100000;
11010: return (time.'_'.$$.'_'.$uniq);
11011: }
11012:
11013: ############################################################
11014: ############################################################
11015:
11016: =pod
11017:
11018: =item * &DrawBarGraph()
11019:
11020: Facilitates the plotting of data in a (stacked) bar graph.
11021: Puts plot definition data into the users environment in order for
11022: graph.png to plot it. Returns an <img> tag for the plot.
11023: The bars on the plot are labeled '1','2',...,'n'.
11024:
11025: Inputs:
11026:
11027: =over 4
11028:
11029: =item $Title: string, the title of the plot
11030:
11031: =item $xlabel: string, text describing the X-axis of the plot
11032:
11033: =item $ylabel: string, text describing the Y-axis of the plot
11034:
11035: =item $Max: scalar, the maximum Y value to use in the plot
11036: If $Max is < any data point, the graph will not be rendered.
11037:
11038: =item $colors: array ref holding the colors to be used for the data sets when
11039: they are plotted. If undefined, default values will be used.
11040:
11041: =item $labels: array ref holding the labels to use on the x-axis for the bars.
11042:
11043: =item @Values: An array of array references. Each array reference holds data
11044: to be plotted in a stacked bar chart.
11045:
11046: =item If the final element of @Values is a hash reference the key/value
11047: pairs will be added to the graph definition.
11048:
11049: =back
11050:
11051: Returns:
11052:
11053: An <img> tag which references graph.png and the appropriate identifying
11054: information for the plot.
11055:
11056: =cut
11057:
11058: ############################################################
11059: ############################################################
11060: sub DrawBarGraph {
11061: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
11062: #
11063: if (! defined($colors)) {
11064: $colors = ['#33ff00',
11065: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
11066: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
11067: ];
11068: }
11069: my $extra_settings = {};
11070: if (ref($Values[-1]) eq 'HASH') {
11071: $extra_settings = pop(@Values);
11072: }
11073: #
11074: my $identifier = &get_cgi_id();
11075: my $id = 'cgi.'.$identifier;
11076: if (! @Values || ref($Values[0]) ne 'ARRAY') {
11077: return '';
11078: }
11079: #
11080: my @Labels;
11081: if (defined($labels)) {
11082: @Labels = @$labels;
11083: } else {
11084: for (my $i=0;$i<@{$Values[0]};$i++) {
11085: push (@Labels,$i+1);
11086: }
11087: }
11088: #
11089: my $NumBars = scalar(@{$Values[0]});
11090: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
11091: my %ValuesHash;
11092: my $NumSets=1;
11093: foreach my $array (@Values) {
11094: next if (! ref($array));
11095: $ValuesHash{$id.'.data.'.$NumSets++} =
11096: join(',',@$array);
11097: }
11098: #
11099: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
11100: if ($NumBars < 3) {
11101: $width = 120+$NumBars*32;
11102: $xskip = 1;
11103: $bar_width = 30;
11104: } elsif ($NumBars < 5) {
11105: $width = 120+$NumBars*20;
11106: $xskip = 1;
11107: $bar_width = 20;
11108: } elsif ($NumBars < 10) {
11109: $width = 120+$NumBars*15;
11110: $xskip = 1;
11111: $bar_width = 15;
11112: } elsif ($NumBars <= 25) {
11113: $width = 120+$NumBars*11;
11114: $xskip = 5;
11115: $bar_width = 8;
11116: } elsif ($NumBars <= 50) {
11117: $width = 120+$NumBars*8;
11118: $xskip = 5;
11119: $bar_width = 4;
11120: } else {
11121: $width = 120+$NumBars*8;
11122: $xskip = 5;
11123: $bar_width = 4;
11124: }
11125: #
11126: $Max = 1 if ($Max < 1);
11127: if ( int($Max) < $Max ) {
11128: $Max++;
11129: $Max = int($Max);
11130: }
11131: $Title = '' if (! defined($Title));
11132: $xlabel = '' if (! defined($xlabel));
11133: $ylabel = '' if (! defined($ylabel));
11134: $ValuesHash{$id.'.title'} = &escape($Title);
11135: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
11136: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
11137: $ValuesHash{$id.'.y_max_value'} = $Max;
11138: $ValuesHash{$id.'.NumBars'} = $NumBars;
11139: $ValuesHash{$id.'.NumSets'} = $NumSets;
11140: $ValuesHash{$id.'.PlotType'} = 'bar';
11141: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11142: $ValuesHash{$id.'.height'} = $height;
11143: $ValuesHash{$id.'.width'} = $width;
11144: $ValuesHash{$id.'.xskip'} = $xskip;
11145: $ValuesHash{$id.'.bar_width'} = $bar_width;
11146: $ValuesHash{$id.'.labels'} = join(',',@Labels);
11147: #
11148: # Deal with other parameters
11149: while (my ($key,$value) = each(%$extra_settings)) {
11150: $ValuesHash{$id.'.'.$key} = $value;
11151: }
11152: #
11153: &Apache::lonnet::appenv(\%ValuesHash);
11154: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11155: }
11156:
11157: ############################################################
11158: ############################################################
11159:
11160: =pod
11161:
11162: =item * &DrawXYGraph()
11163:
11164: Facilitates the plotting of data in an XY graph.
11165: Puts plot definition data into the users environment in order for
11166: graph.png to plot it. Returns an <img> tag for the plot.
11167:
11168: Inputs:
11169:
11170: =over 4
11171:
11172: =item $Title: string, the title of the plot
11173:
11174: =item $xlabel: string, text describing the X-axis of the plot
11175:
11176: =item $ylabel: string, text describing the Y-axis of the plot
11177:
11178: =item $Max: scalar, the maximum Y value to use in the plot
11179: If $Max is < any data point, the graph will not be rendered.
11180:
11181: =item $colors: Array ref containing the hex color codes for the data to be
11182: plotted in. If undefined, default values will be used.
11183:
11184: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
11185:
11186: =item $Ydata: Array ref containing Array refs.
11187: Each of the contained arrays will be plotted as a separate curve.
11188:
11189: =item %Values: hash indicating or overriding any default values which are
11190: passed to graph.png.
11191: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
11192:
11193: =back
11194:
11195: Returns:
11196:
11197: An <img> tag which references graph.png and the appropriate identifying
11198: information for the plot.
11199:
11200: =cut
11201:
11202: ############################################################
11203: ############################################################
11204: sub DrawXYGraph {
11205: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
11206: #
11207: # Create the identifier for the graph
11208: my $identifier = &get_cgi_id();
11209: my $id = 'cgi.'.$identifier;
11210: #
11211: $Title = '' if (! defined($Title));
11212: $xlabel = '' if (! defined($xlabel));
11213: $ylabel = '' if (! defined($ylabel));
11214: my %ValuesHash =
11215: (
11216: $id.'.title' => &escape($Title),
11217: $id.'.xlabel' => &escape($xlabel),
11218: $id.'.ylabel' => &escape($ylabel),
11219: $id.'.y_max_value'=> $Max,
11220: $id.'.labels' => join(',',@$Xlabels),
11221: $id.'.PlotType' => 'XY',
11222: );
11223: #
11224: if (defined($colors) && ref($colors) eq 'ARRAY') {
11225: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11226: }
11227: #
11228: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
11229: return '';
11230: }
11231: my $NumSets=1;
11232: foreach my $array (@{$Ydata}){
11233: next if (! ref($array));
11234: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
11235: }
11236: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
11237: #
11238: # Deal with other parameters
11239: while (my ($key,$value) = each(%Values)) {
11240: $ValuesHash{$id.'.'.$key} = $value;
11241: }
11242: #
11243: &Apache::lonnet::appenv(\%ValuesHash);
11244: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11245: }
11246:
11247: ############################################################
11248: ############################################################
11249:
11250: =pod
11251:
11252: =item * &DrawXYYGraph()
11253:
11254: Facilitates the plotting of data in an XY graph with two Y axes.
11255: Puts plot definition data into the users environment in order for
11256: graph.png to plot it. Returns an <img> tag for the plot.
11257:
11258: Inputs:
11259:
11260: =over 4
11261:
11262: =item $Title: string, the title of the plot
11263:
11264: =item $xlabel: string, text describing the X-axis of the plot
11265:
11266: =item $ylabel: string, text describing the Y-axis of the plot
11267:
11268: =item $colors: Array ref containing the hex color codes for the data to be
11269: plotted in. If undefined, default values will be used.
11270:
11271: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
11272:
11273: =item $Ydata1: The first data set
11274:
11275: =item $Min1: The minimum value of the left Y-axis
11276:
11277: =item $Max1: The maximum value of the left Y-axis
11278:
11279: =item $Ydata2: The second data set
11280:
11281: =item $Min2: The minimum value of the right Y-axis
11282:
11283: =item $Max2: The maximum value of the left Y-axis
11284:
11285: =item %Values: hash indicating or overriding any default values which are
11286: passed to graph.png.
11287: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
11288:
11289: =back
11290:
11291: Returns:
11292:
11293: An <img> tag which references graph.png and the appropriate identifying
11294: information for the plot.
11295:
11296: =cut
11297:
11298: ############################################################
11299: ############################################################
11300: sub DrawXYYGraph {
11301: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
11302: $Ydata2,$Min2,$Max2,%Values)=@_;
11303: #
11304: # Create the identifier for the graph
11305: my $identifier = &get_cgi_id();
11306: my $id = 'cgi.'.$identifier;
11307: #
11308: $Title = '' if (! defined($Title));
11309: $xlabel = '' if (! defined($xlabel));
11310: $ylabel = '' if (! defined($ylabel));
11311: my %ValuesHash =
11312: (
11313: $id.'.title' => &escape($Title),
11314: $id.'.xlabel' => &escape($xlabel),
11315: $id.'.ylabel' => &escape($ylabel),
11316: $id.'.labels' => join(',',@$Xlabels),
11317: $id.'.PlotType' => 'XY',
11318: $id.'.NumSets' => 2,
11319: $id.'.two_axes' => 1,
11320: $id.'.y1_max_value' => $Max1,
11321: $id.'.y1_min_value' => $Min1,
11322: $id.'.y2_max_value' => $Max2,
11323: $id.'.y2_min_value' => $Min2,
11324: );
11325: #
11326: if (defined($colors) && ref($colors) eq 'ARRAY') {
11327: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
11328: }
11329: #
11330: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
11331: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
11332: return '';
11333: }
11334: my $NumSets=1;
11335: foreach my $array ($Ydata1,$Ydata2){
11336: next if (! ref($array));
11337: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
11338: }
11339: #
11340: # Deal with other parameters
11341: while (my ($key,$value) = each(%Values)) {
11342: $ValuesHash{$id.'.'.$key} = $value;
11343: }
11344: #
11345: &Apache::lonnet::appenv(\%ValuesHash);
11346: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
11347: }
11348:
11349: ############################################################
11350: ############################################################
11351:
11352: =pod
11353:
11354: =back
11355:
11356: =head1 Statistics helper routines?
11357:
11358: Bad place for them but what the hell.
11359:
11360: =over 4
11361:
11362: =item * &chartlink()
11363:
11364: Returns a link to the chart for a specific student.
11365:
11366: Inputs:
11367:
11368: =over 4
11369:
11370: =item $linktext: The text of the link
11371:
11372: =item $sname: The students username
11373:
11374: =item $sdomain: The students domain
11375:
11376: =back
11377:
11378: =back
11379:
11380: =cut
11381:
11382: ############################################################
11383: ############################################################
11384: sub chartlink {
11385: my ($linktext, $sname, $sdomain) = @_;
11386: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
11387: '&SelectedStudent='.&escape($sname.':'.$sdomain).
11388: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
11389: '">'.$linktext.'</a>';
11390: }
11391:
11392: #######################################################
11393: #######################################################
11394:
11395: =pod
11396:
11397: =head1 Course Environment Routines
11398:
11399: =over 4
11400:
11401: =item * &restore_course_settings()
11402:
11403: =item * &store_course_settings()
11404:
11405: Restores/Store indicated form parameters from the course environment.
11406: Will not overwrite existing values of the form parameters.
11407:
11408: Inputs:
11409: a scalar describing the data (e.g. 'chart', 'problem_analysis')
11410:
11411: a hash ref describing the data to be stored. For example:
11412:
11413: %Save_Parameters = ('Status' => 'scalar',
11414: 'chartoutputmode' => 'scalar',
11415: 'chartoutputdata' => 'scalar',
11416: 'Section' => 'array',
11417: 'Group' => 'array',
11418: 'StudentData' => 'array',
11419: 'Maps' => 'array');
11420:
11421: Returns: both routines return nothing
11422:
11423: =back
11424:
11425: =cut
11426:
11427: #######################################################
11428: #######################################################
11429: sub store_course_settings {
11430: return &store_settings($env{'request.course.id'},@_);
11431: }
11432:
11433: sub store_settings {
11434: # save to the environment
11435: # appenv the same items, just to be safe
11436: my $udom = $env{'user.domain'};
11437: my $uname = $env{'user.name'};
11438: my ($context,$prefix,$Settings) = @_;
11439: my %SaveHash;
11440: my %AppHash;
11441: while (my ($setting,$type) = each(%$Settings)) {
11442: my $basename = join('.','internal',$context,$prefix,$setting);
11443: my $envname = 'environment.'.$basename;
11444: if (exists($env{'form.'.$setting})) {
11445: # Save this value away
11446: if ($type eq 'scalar' &&
11447: (! exists($env{$envname}) ||
11448: $env{$envname} ne $env{'form.'.$setting})) {
11449: $SaveHash{$basename} = $env{'form.'.$setting};
11450: $AppHash{$envname} = $env{'form.'.$setting};
11451: } elsif ($type eq 'array') {
11452: my $stored_form;
11453: if (ref($env{'form.'.$setting})) {
11454: $stored_form = join(',',
11455: map {
11456: &escape($_);
11457: } sort(@{$env{'form.'.$setting}}));
11458: } else {
11459: $stored_form =
11460: &escape($env{'form.'.$setting});
11461: }
11462: # Determine if the array contents are the same.
11463: if ($stored_form ne $env{$envname}) {
11464: $SaveHash{$basename} = $stored_form;
11465: $AppHash{$envname} = $stored_form;
11466: }
11467: }
11468: }
11469: }
11470: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
11471: $udom,$uname);
11472: if ($put_result !~ /^(ok|delayed)/) {
11473: &Apache::lonnet::logthis('unable to save form parameters, '.
11474: 'got error:'.$put_result);
11475: }
11476: # Make sure these settings stick around in this session, too
11477: &Apache::lonnet::appenv(\%AppHash);
11478: return;
11479: }
11480:
11481: sub restore_course_settings {
11482: return &restore_settings($env{'request.course.id'},@_);
11483: }
11484:
11485: sub restore_settings {
11486: my ($context,$prefix,$Settings) = @_;
11487: while (my ($setting,$type) = each(%$Settings)) {
11488: next if (exists($env{'form.'.$setting}));
11489: my $envname = 'environment.internal.'.$context.'.'.$prefix.
11490: '.'.$setting;
11491: if (exists($env{$envname})) {
11492: if ($type eq 'scalar') {
11493: $env{'form.'.$setting} = $env{$envname};
11494: } elsif ($type eq 'array') {
11495: $env{'form.'.$setting} = [
11496: map {
11497: &unescape($_);
11498: } split(',',$env{$envname})
11499: ];
11500: }
11501: }
11502: }
11503: }
11504:
11505: #######################################################
11506: #######################################################
11507:
11508: =pod
11509:
11510: =head1 Domain E-mail Routines
11511:
11512: =over 4
11513:
11514: =item * &build_recipient_list()
11515:
11516: Build recipient lists for five types of e-mail:
11517: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
11518: (d) Help requests, (e) Course requests needing approval, generated by
11519: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
11520: loncoursequeueadmin.pm respectively.
11521:
11522: Inputs:
11523: defmail (scalar - email address of default recipient),
11524: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
11525: defdom (domain for which to retrieve configuration settings),
11526: origmail (scalar - email address of recipient from loncapa.conf,
11527: i.e., predates configuration by DC via domainprefs.pm
11528:
11529: Returns: comma separated list of addresses to which to send e-mail.
11530:
11531: =back
11532:
11533: =cut
11534:
11535: ############################################################
11536: ############################################################
11537: sub build_recipient_list {
11538: my ($defmail,$mailing,$defdom,$origmail) = @_;
11539: my @recipients;
11540: my $otheremails;
11541: my %domconfig =
11542: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
11543: if (ref($domconfig{'contacts'}) eq 'HASH') {
11544: if (exists($domconfig{'contacts'}{$mailing})) {
11545: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
11546: my @contacts = ('adminemail','supportemail');
11547: foreach my $item (@contacts) {
11548: if ($domconfig{'contacts'}{$mailing}{$item}) {
11549: my $addr = $domconfig{'contacts'}{$item};
11550: if (!grep(/^\Q$addr\E$/,@recipients)) {
11551: push(@recipients,$addr);
11552: }
11553: }
11554: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
11555: }
11556: }
11557: } elsif ($origmail ne '') {
11558: push(@recipients,$origmail);
11559: }
11560: } elsif ($origmail ne '') {
11561: push(@recipients,$origmail);
11562: }
11563: if (defined($defmail)) {
11564: if ($defmail ne '') {
11565: push(@recipients,$defmail);
11566: }
11567: }
11568: if ($otheremails) {
11569: my @others;
11570: if ($otheremails =~ /,/) {
11571: @others = split(/,/,$otheremails);
11572: } else {
11573: push(@others,$otheremails);
11574: }
11575: foreach my $addr (@others) {
11576: if (!grep(/^\Q$addr\E$/,@recipients)) {
11577: push(@recipients,$addr);
11578: }
11579: }
11580: }
11581: my $recipientlist = join(',',@recipients);
11582: return $recipientlist;
11583: }
11584:
11585: ############################################################
11586: ############################################################
11587:
11588: =pod
11589:
11590: =head1 Course Catalog Routines
11591:
11592: =over 4
11593:
11594: =item * &gather_categories()
11595:
11596: Converts category definitions - keys of categories hash stored in
11597: coursecategories in configuration.db on the primary library server in a
11598: domain - to an array. Also generates javascript and idx hash used to
11599: generate Domain Coordinator interface for editing Course Categories.
11600:
11601: Inputs:
11602:
11603: categories (reference to hash of category definitions).
11604:
11605: cats (reference to array of arrays/hashes which encapsulates hierarchy of
11606: categories and subcategories).
11607:
11608: idx (reference to hash of counters used in Domain Coordinator interface for
11609: editing Course Categories).
11610:
11611: jsarray (reference to array of categories used to create Javascript arrays for
11612: Domain Coordinator interface for editing Course Categories).
11613:
11614: Returns: nothing
11615:
11616: Side effects: populates cats, idx and jsarray.
11617:
11618: =cut
11619:
11620: sub gather_categories {
11621: my ($categories,$cats,$idx,$jsarray) = @_;
11622: my %counters;
11623: my $num = 0;
11624: foreach my $item (keys(%{$categories})) {
11625: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
11626: if ($container eq '' && $depth == 0) {
11627: $cats->[$depth][$categories->{$item}] = $cat;
11628: } else {
11629: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
11630: }
11631: my ($escitem,$tail) = split(/:/,$item,2);
11632: if ($counters{$tail} eq '') {
11633: $counters{$tail} = $num;
11634: $num ++;
11635: }
11636: if (ref($idx) eq 'HASH') {
11637: $idx->{$item} = $counters{$tail};
11638: }
11639: if (ref($jsarray) eq 'ARRAY') {
11640: push(@{$jsarray->[$counters{$tail}]},$item);
11641: }
11642: }
11643: return;
11644: }
11645:
11646: =pod
11647:
11648: =item * &extract_categories()
11649:
11650: Used to generate breadcrumb trails for course categories.
11651:
11652: Inputs:
11653:
11654: categories (reference to hash of category definitions).
11655:
11656: cats (reference to array of arrays/hashes which encapsulates hierarchy of
11657: categories and subcategories).
11658:
11659: trails (reference to array of breacrumb trails for each category).
11660:
11661: allitems (reference to hash - key is category key
11662: (format: escaped(name):escaped(parent category):depth in hierarchy).
11663:
11664: idx (reference to hash of counters used in Domain Coordinator interface for
11665: editing Course Categories).
11666:
11667: jsarray (reference to array of categories used to create Javascript arrays for
11668: Domain Coordinator interface for editing Course Categories).
11669:
11670: subcats (reference to hash of arrays containing all subcategories within each
11671: category, -recursive)
11672:
11673: Returns: nothing
11674:
11675: Side effects: populates trails and allitems hash references.
11676:
11677: =cut
11678:
11679: sub extract_categories {
11680: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
11681: if (ref($categories) eq 'HASH') {
11682: &gather_categories($categories,$cats,$idx,$jsarray);
11683: if (ref($cats->[0]) eq 'ARRAY') {
11684: for (my $i=0; $i<@{$cats->[0]}; $i++) {
11685: my $name = $cats->[0][$i];
11686: my $item = &escape($name).'::0';
11687: my $trailstr;
11688: if ($name eq 'instcode') {
11689: $trailstr = &mt('Official courses (with institutional codes)');
11690: } elsif ($name eq 'communities') {
11691: $trailstr = &mt('Communities');
11692: } else {
11693: $trailstr = $name;
11694: }
11695: if ($allitems->{$item} eq '') {
11696: push(@{$trails},$trailstr);
11697: $allitems->{$item} = scalar(@{$trails})-1;
11698: }
11699: my @parents = ($name);
11700: if (ref($cats->[1]{$name}) eq 'ARRAY') {
11701: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
11702: my $category = $cats->[1]{$name}[$j];
11703: if (ref($subcats) eq 'HASH') {
11704: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
11705: }
11706: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
11707: }
11708: } else {
11709: if (ref($subcats) eq 'HASH') {
11710: $subcats->{$item} = [];
11711: }
11712: }
11713: }
11714: }
11715: }
11716: return;
11717: }
11718:
11719: =pod
11720:
11721: =item *&recurse_categories()
11722:
11723: Recursively used to generate breadcrumb trails for course categories.
11724:
11725: Inputs:
11726:
11727: cats (reference to array of arrays/hashes which encapsulates hierarchy of
11728: categories and subcategories).
11729:
11730: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
11731:
11732: category (current course category, for which breadcrumb trail is being generated).
11733:
11734: trails (reference to array of breadcrumb trails for each category).
11735:
11736: allitems (reference to hash - key is category key
11737: (format: escaped(name):escaped(parent category):depth in hierarchy).
11738:
11739: parents (array containing containers directories for current category,
11740: back to top level).
11741:
11742: Returns: nothing
11743:
11744: Side effects: populates trails and allitems hash references
11745:
11746: =cut
11747:
11748: sub recurse_categories {
11749: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
11750: my $shallower = $depth - 1;
11751: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
11752: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
11753: my $name = $cats->[$depth]{$category}[$k];
11754: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
11755: my $trailstr = join(' -> ',(@{$parents},$category));
11756: if ($allitems->{$item} eq '') {
11757: push(@{$trails},$trailstr);
11758: $allitems->{$item} = scalar(@{$trails})-1;
11759: }
11760: my $deeper = $depth+1;
11761: push(@{$parents},$category);
11762: if (ref($subcats) eq 'HASH') {
11763: my $subcat = &escape($name).':'.$category.':'.$depth;
11764: for (my $j=@{$parents}; $j>=0; $j--) {
11765: my $higher;
11766: if ($j > 0) {
11767: $higher = &escape($parents->[$j]).':'.
11768: &escape($parents->[$j-1]).':'.$j;
11769: } else {
11770: $higher = &escape($parents->[$j]).'::'.$j;
11771: }
11772: push(@{$subcats->{$higher}},$subcat);
11773: }
11774: }
11775: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
11776: $subcats);
11777: pop(@{$parents});
11778: }
11779: } else {
11780: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
11781: my $trailstr = join(' -> ',(@{$parents},$category));
11782: if ($allitems->{$item} eq '') {
11783: push(@{$trails},$trailstr);
11784: $allitems->{$item} = scalar(@{$trails})-1;
11785: }
11786: }
11787: return;
11788: }
11789:
11790: =pod
11791:
11792: =item *&assign_categories_table()
11793:
11794: Create a datatable for display of hierarchical categories in a domain,
11795: with checkboxes to allow a course to be categorized.
11796:
11797: Inputs:
11798:
11799: cathash - reference to hash of categories defined for the domain (from
11800: configuration.db)
11801:
11802: currcat - scalar with an & separated list of categories assigned to a course.
11803:
11804: type - scalar contains course type (Course or Community).
11805:
11806: Returns: $output (markup to be displayed)
11807:
11808: =cut
11809:
11810: sub assign_categories_table {
11811: my ($cathash,$currcat,$type) = @_;
11812: my $output;
11813: if (ref($cathash) eq 'HASH') {
11814: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
11815: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
11816: $maxdepth = scalar(@cats);
11817: if (@cats > 0) {
11818: my $itemcount = 0;
11819: if (ref($cats[0]) eq 'ARRAY') {
11820: my @currcategories;
11821: if ($currcat ne '') {
11822: @currcategories = split('&',$currcat);
11823: }
11824: my $table;
11825: for (my $i=0; $i<@{$cats[0]}; $i++) {
11826: my $parent = $cats[0][$i];
11827: next if ($parent eq 'instcode');
11828: if ($type eq 'Community') {
11829: next unless ($parent eq 'communities');
11830: } else {
11831: next if ($parent eq 'communities');
11832: }
11833: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11834: my $item = &escape($parent).'::0';
11835: my $checked = '';
11836: if (@currcategories > 0) {
11837: if (grep(/^\Q$item\E$/,@currcategories)) {
11838: $checked = ' checked="checked"';
11839: }
11840: }
11841: my $parent_title = $parent;
11842: if ($parent eq 'communities') {
11843: $parent_title = &mt('Communities');
11844: }
11845: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
11846: '<input type="checkbox" name="usecategory" value="'.
11847: $item.'"'.$checked.' />'.$parent_title.'</span>'.
11848: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
11849: my $depth = 1;
11850: push(@path,$parent);
11851: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
11852: pop(@path);
11853: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11854: $itemcount ++;
11855: }
11856: if ($itemcount) {
11857: $output = &Apache::loncommon::start_data_table().
11858: $table.
11859: &Apache::loncommon::end_data_table();
11860: }
11861: }
11862: }
11863: }
11864: return $output;
11865: }
11866:
11867: =pod
11868:
11869: =item *&assign_category_rows()
11870:
11871: Create a datatable row for display of nested categories in a domain,
11872: with checkboxes to allow a course to be categorized,called recursively.
11873:
11874: Inputs:
11875:
11876: itemcount - track row number for alternating colors
11877:
11878: cats - reference to array of arrays/hashes which encapsulates hierarchy of
11879: categories and subcategories.
11880:
11881: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
11882:
11883: parent - parent of current category item
11884:
11885: path - Array containing all categories back up through the hierarchy from the
11886: current category to the top level.
11887:
11888: currcategories - reference to array of current categories assigned to the course
11889:
11890: Returns: $output (markup to be displayed).
11891:
11892: =cut
11893:
11894: sub assign_category_rows {
11895: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
11896: my ($text,$name,$item,$chgstr);
11897: if (ref($cats) eq 'ARRAY') {
11898: my $maxdepth = scalar(@{$cats});
11899: if (ref($cats->[$depth]) eq 'HASH') {
11900: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11901: my $numchildren = @{$cats->[$depth]{$parent}};
11902: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11903: $text .= '<td><table class="LC_datatable">';
11904: for (my $j=0; $j<$numchildren; $j++) {
11905: $name = $cats->[$depth]{$parent}[$j];
11906: $item = &escape($name).':'.&escape($parent).':'.$depth;
11907: my $deeper = $depth+1;
11908: my $checked = '';
11909: if (ref($currcategories) eq 'ARRAY') {
11910: if (@{$currcategories} > 0) {
11911: if (grep(/^\Q$item\E$/,@{$currcategories})) {
11912: $checked = ' checked="checked"';
11913: }
11914: }
11915: }
11916: $text .= '<tr><td><span class="LC_nobreak"><label>'.
11917: '<input type="checkbox" name="usecategory" value="'.
11918: $item.'"'.$checked.' />'.$name.'</label></span>'.
11919: '<input type="hidden" name="catname" value="'.$name.'" />'.
11920: '</td><td>';
11921: if (ref($path) eq 'ARRAY') {
11922: push(@{$path},$name);
11923: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
11924: pop(@{$path});
11925: }
11926: $text .= '</td></tr>';
11927: }
11928: $text .= '</table></td>';
11929: }
11930: }
11931: }
11932: return $text;
11933: }
11934:
11935: ############################################################
11936: ############################################################
11937:
11938:
11939: sub commit_customrole {
11940: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
11941: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
11942: ($start?', '.&mt('starting').' '.localtime($start):'').
11943: ($end?', ending '.localtime($end):'').': <b>'.
11944: &Apache::lonnet::assigncustomrole(
11945: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
11946: '</b><br />';
11947: return $output;
11948: }
11949:
11950: sub commit_standardrole {
11951: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
11952: my ($output,$logmsg,$linefeed);
11953: if ($context eq 'auto') {
11954: $linefeed = "\n";
11955: } else {
11956: $linefeed = "<br />\n";
11957: }
11958: if ($three eq 'st') {
11959: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
11960: $one,$two,$sec,$context);
11961: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
11962: ($result eq 'unknown_course') || ($result eq 'refused')) {
11963: $output = $logmsg.' '.&mt('Error: ').$result."\n";
11964: } else {
11965: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
11966: ($start?', '.&mt('starting').' '.localtime($start):'').
11967: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
11968: if ($context eq 'auto') {
11969: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
11970: } else {
11971: $output .= '<b>'.$result.'</b>'.$linefeed.
11972: &mt('Add to classlist').': <b>ok</b>';
11973: }
11974: $output .= $linefeed;
11975: }
11976: } else {
11977: $output = &mt('Assigning').' '.$three.' in '.$url.
11978: ($start?', '.&mt('starting').' '.localtime($start):'').
11979: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
11980: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
11981: if ($context eq 'auto') {
11982: $output .= $result.$linefeed;
11983: } else {
11984: $output .= '<b>'.$result.'</b>'.$linefeed;
11985: }
11986: }
11987: return $output;
11988: }
11989:
11990: sub commit_studentrole {
11991: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
11992: my ($result,$linefeed,$oldsecurl,$newsecurl);
11993: if ($context eq 'auto') {
11994: $linefeed = "\n";
11995: } else {
11996: $linefeed = '<br />'."\n";
11997: }
11998: if (defined($one) && defined($two)) {
11999: my $cid=$one.'_'.$two;
12000: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
12001: my $secchange = 0;
12002: my $expire_role_result;
12003: my $modify_section_result;
12004: if ($oldsec ne '-1') {
12005: if ($oldsec ne $sec) {
12006: $secchange = 1;
12007: my $now = time;
12008: my $uurl='/'.$cid;
12009: $uurl=~s/\_/\//g;
12010: if ($oldsec) {
12011: $uurl.='/'.$oldsec;
12012: }
12013: $oldsecurl = $uurl;
12014: $expire_role_result =
12015: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
12016: if ($env{'request.course.sec'} ne '') {
12017: if ($expire_role_result eq 'refused') {
12018: my @roles = ('st');
12019: my @statuses = ('previous');
12020: my @roledoms = ($one);
12021: my $withsec = 1;
12022: my %roleshash =
12023: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
12024: \@statuses,\@roles,\@roledoms,$withsec);
12025: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
12026: my ($oldstart,$oldend) =
12027: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
12028: if ($oldend > 0 && $oldend <= $now) {
12029: $expire_role_result = 'ok';
12030: }
12031: }
12032: }
12033: }
12034: $result = $expire_role_result;
12035: }
12036: }
12037: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
12038: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
12039: if ($modify_section_result =~ /^ok/) {
12040: if ($secchange == 1) {
12041: if ($sec eq '') {
12042: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
12043: } else {
12044: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
12045: }
12046: } elsif ($oldsec eq '-1') {
12047: if ($sec eq '') {
12048: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
12049: } else {
12050: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12051: }
12052: } else {
12053: if ($sec eq '') {
12054: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
12055: } else {
12056: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
12057: }
12058: }
12059: } else {
12060: if ($secchange) {
12061: $$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;
12062: } else {
12063: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
12064: }
12065: }
12066: $result = $modify_section_result;
12067: } elsif ($secchange == 1) {
12068: if ($oldsec eq '') {
12069: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
12070: } else {
12071: $$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;
12072: }
12073: if ($expire_role_result eq 'refused') {
12074: my $newsecurl = '/'.$cid;
12075: $newsecurl =~ s/\_/\//g;
12076: if ($sec ne '') {
12077: $newsecurl.='/'.$sec;
12078: }
12079: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
12080: if ($sec eq '') {
12081: $$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;
12082: } else {
12083: $$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;
12084: }
12085: }
12086: }
12087: }
12088: } else {
12089: $$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;
12090: $result = "error: incomplete course id\n";
12091: }
12092: return $result;
12093: }
12094:
12095: ############################################################
12096: ############################################################
12097:
12098: sub check_clone {
12099: my ($args,$linefeed) = @_;
12100: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
12101: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
12102: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
12103: my $clonemsg;
12104: my $can_clone = 0;
12105: my $lctype = lc($args->{'crstype'});
12106: if ($lctype ne 'community') {
12107: $lctype = 'course';
12108: }
12109: if ($clonehome eq 'no_host') {
12110: if ($args->{'crstype'} eq 'Community') {
12111: $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'});
12112: } else {
12113: $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'});
12114: }
12115: } else {
12116: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
12117: if ($args->{'crstype'} eq 'Community') {
12118: if ($clonedesc{'type'} ne 'Community') {
12119: $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'});
12120: return ($can_clone, $clonemsg, $cloneid, $clonehome);
12121: }
12122: }
12123: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
12124: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
12125: $can_clone = 1;
12126: } else {
12127: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
12128: $args->{'clonedomain'},$args->{'clonecourse'});
12129: my @cloners = split(/,/,$clonehash{'cloners'});
12130: if (grep(/^\*$/,@cloners)) {
12131: $can_clone = 1;
12132: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
12133: $can_clone = 1;
12134: } else {
12135: my $ccrole = 'cc';
12136: if ($args->{'crstype'} eq 'Community') {
12137: $ccrole = 'co';
12138: }
12139: my %roleshash =
12140: &Apache::lonnet::get_my_roles($args->{'ccuname'},
12141: $args->{'ccdomain'},
12142: 'userroles',['active'],[$ccrole],
12143: [$args->{'clonedomain'}]);
12144: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
12145: $can_clone = 1;
12146: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
12147: $can_clone = 1;
12148: } else {
12149: if ($args->{'crstype'} eq 'Community') {
12150: $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'});
12151: } else {
12152: $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'});
12153: }
12154: }
12155: }
12156: }
12157: }
12158: return ($can_clone, $clonemsg, $cloneid, $clonehome);
12159: }
12160:
12161: sub construct_course {
12162: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
12163: my $outcome;
12164: my $linefeed = '<br />'."\n";
12165: if ($context eq 'auto') {
12166: $linefeed = "\n";
12167: }
12168:
12169: #
12170: # Are we cloning?
12171: #
12172: my ($can_clone, $clonemsg, $cloneid, $clonehome);
12173: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
12174: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
12175: if ($context ne 'auto') {
12176: if ($clonemsg ne '') {
12177: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
12178: }
12179: }
12180: $outcome .= $clonemsg.$linefeed;
12181:
12182: if (!$can_clone) {
12183: return (0,$outcome);
12184: }
12185: }
12186:
12187: #
12188: # Open course
12189: #
12190: my $crstype = lc($args->{'crstype'});
12191: my %cenv=();
12192: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
12193: $args->{'cdescr'},
12194: $args->{'curl'},
12195: $args->{'course_home'},
12196: $args->{'nonstandard'},
12197: $args->{'crscode'},
12198: $args->{'ccuname'}.':'.
12199: $args->{'ccdomain'},
12200: $args->{'crstype'},
12201: $cnum,$context,$category);
12202:
12203: # Note: The testing routines depend on this being output; see
12204: # Utils::Course. This needs to at least be output as a comment
12205: # if anyone ever decides to not show this, and Utils::Course::new
12206: # will need to be suitably modified.
12207: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
12208: if ($$courseid =~ /^error:/) {
12209: return (0,$outcome);
12210: }
12211:
12212: #
12213: # Check if created correctly
12214: #
12215: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
12216: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
12217: if ($crsuhome eq 'no_host') {
12218: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
12219: return (0,$outcome);
12220: }
12221: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
12222:
12223: #
12224: # Do the cloning
12225: #
12226: if ($can_clone && $cloneid) {
12227: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
12228: if ($context ne 'auto') {
12229: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
12230: }
12231: $outcome .= $clonemsg.$linefeed;
12232: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
12233: # Copy all files
12234: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
12235: # Restore URL
12236: $cenv{'url'}=$oldcenv{'url'};
12237: # Restore title
12238: $cenv{'description'}=$oldcenv{'description'};
12239: # Restore creation date, creator and creation context.
12240: $cenv{'internal.created'}=$oldcenv{'internal.created'};
12241: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
12242: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
12243: # Mark as cloned
12244: $cenv{'clonedfrom'}=$cloneid;
12245: # Need to clone grading mode
12246: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
12247: $cenv{'grading'}=$newenv{'grading'};
12248: # Do not clone these environment entries
12249: &Apache::lonnet::del('environment',
12250: ['default_enrollment_start_date',
12251: 'default_enrollment_end_date',
12252: 'question.email',
12253: 'policy.email',
12254: 'comment.email',
12255: 'pch.users.denied',
12256: 'plc.users.denied',
12257: 'hidefromcat',
12258: 'categories'],
12259: $$crsudom,$$crsunum);
12260: }
12261:
12262: #
12263: # Set environment (will override cloned, if existing)
12264: #
12265: my @sections = ();
12266: my @xlists = ();
12267: if ($args->{'crstype'}) {
12268: $cenv{'type'}=$args->{'crstype'};
12269: }
12270: if ($args->{'crsid'}) {
12271: $cenv{'courseid'}=$args->{'crsid'};
12272: }
12273: if ($args->{'crscode'}) {
12274: $cenv{'internal.coursecode'}=$args->{'crscode'};
12275: }
12276: if ($args->{'crsquota'} ne '') {
12277: $cenv{'internal.coursequota'}=$args->{'crsquota'};
12278: } else {
12279: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
12280: }
12281: if ($args->{'ccuname'}) {
12282: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
12283: ':'.$args->{'ccdomain'};
12284: } else {
12285: $cenv{'internal.courseowner'} = $args->{'curruser'};
12286: }
12287: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
12288: if ($args->{'crssections'}) {
12289: $cenv{'internal.sectionnums'} = '';
12290: if ($args->{'crssections'} =~ m/,/) {
12291: @sections = split/,/,$args->{'crssections'};
12292: } else {
12293: $sections[0] = $args->{'crssections'};
12294: }
12295: if (@sections > 0) {
12296: foreach my $item (@sections) {
12297: my ($sec,$gp) = split/:/,$item;
12298: my $class = $args->{'crscode'}.$sec;
12299: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
12300: $cenv{'internal.sectionnums'} .= $item.',';
12301: unless ($addcheck eq 'ok') {
12302: push @badclasses, $class;
12303: }
12304: }
12305: $cenv{'internal.sectionnums'} =~ s/,$//;
12306: }
12307: }
12308: # do not hide course coordinator from staff listing,
12309: # even if privileged
12310: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12311: # add crosslistings
12312: if ($args->{'crsxlist'}) {
12313: $cenv{'internal.crosslistings'}='';
12314: if ($args->{'crsxlist'} =~ m/,/) {
12315: @xlists = split/,/,$args->{'crsxlist'};
12316: } else {
12317: $xlists[0] = $args->{'crsxlist'};
12318: }
12319: if (@xlists > 0) {
12320: foreach my $item (@xlists) {
12321: my ($xl,$gp) = split/:/,$item;
12322: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
12323: $cenv{'internal.crosslistings'} .= $item.',';
12324: unless ($addcheck eq 'ok') {
12325: push @badclasses, $xl;
12326: }
12327: }
12328: $cenv{'internal.crosslistings'} =~ s/,$//;
12329: }
12330: }
12331: if ($args->{'autoadds'}) {
12332: $cenv{'internal.autoadds'}=$args->{'autoadds'};
12333: }
12334: if ($args->{'autodrops'}) {
12335: $cenv{'internal.autodrops'}=$args->{'autodrops'};
12336: }
12337: # check for notification of enrollment changes
12338: my @notified = ();
12339: if ($args->{'notify_owner'}) {
12340: if ($args->{'ccuname'} ne '') {
12341: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
12342: }
12343: }
12344: if ($args->{'notify_dc'}) {
12345: if ($uname ne '') {
12346: push(@notified,$uname.':'.$udom);
12347: }
12348: }
12349: if (@notified > 0) {
12350: my $notifylist;
12351: if (@notified > 1) {
12352: $notifylist = join(',',@notified);
12353: } else {
12354: $notifylist = $notified[0];
12355: }
12356: $cenv{'internal.notifylist'} = $notifylist;
12357: }
12358: if (@badclasses > 0) {
12359: my %lt=&Apache::lonlocal::texthash(
12360: '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',
12361: 'dnhr' => 'does not have rights to access enrollment in these classes',
12362: 'adby' => 'as determined by the policies of your institution on access to official classlists'
12363: );
12364: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
12365: ' ('.$lt{'adby'}.')';
12366: if ($context eq 'auto') {
12367: $outcome .= $badclass_msg.$linefeed;
12368: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
12369: foreach my $item (@badclasses) {
12370: if ($context eq 'auto') {
12371: $outcome .= " - $item\n";
12372: } else {
12373: $outcome .= "<li>$item</li>\n";
12374: }
12375: }
12376: if ($context eq 'auto') {
12377: $outcome .= $linefeed;
12378: } else {
12379: $outcome .= "</ul><br /><br /></div>\n";
12380: }
12381: }
12382: }
12383: if ($args->{'no_end_date'}) {
12384: $args->{'endaccess'} = 0;
12385: }
12386: $cenv{'internal.autostart'}=$args->{'enrollstart'};
12387: $cenv{'internal.autoend'}=$args->{'enrollend'};
12388: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
12389: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
12390: if ($args->{'showphotos'}) {
12391: $cenv{'internal.showphotos'}=$args->{'showphotos'};
12392: }
12393: $cenv{'internal.authtype'} = $args->{'authtype'};
12394: $cenv{'internal.autharg'} = $args->{'autharg'};
12395: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
12396: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
12397: 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');
12398: if ($context eq 'auto') {
12399: $outcome .= $krb_msg;
12400: } else {
12401: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
12402: }
12403: $outcome .= $linefeed;
12404: }
12405: }
12406: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
12407: if ($args->{'setpolicy'}) {
12408: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12409: }
12410: if ($args->{'setcontent'}) {
12411: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
12412: }
12413: }
12414: if ($args->{'reshome'}) {
12415: $cenv{'reshome'}=$args->{'reshome'}.'/';
12416: $cenv{'reshome'}=~s/\/+$/\//;
12417: }
12418: #
12419: # course has keyed access
12420: #
12421: if ($args->{'setkeys'}) {
12422: $cenv{'keyaccess'}='yes';
12423: }
12424: # if specified, key authority is not course, but user
12425: # only active if keyaccess is yes
12426: if ($args->{'keyauth'}) {
12427: my ($user,$domain) = split(':',$args->{'keyauth'});
12428: $user = &LONCAPA::clean_username($user);
12429: $domain = &LONCAPA::clean_username($domain);
12430: if ($user ne '' && $domain ne '') {
12431: $cenv{'keyauth'}=$user.':'.$domain;
12432: }
12433: }
12434:
12435: if ($args->{'disresdis'}) {
12436: $cenv{'pch.roles.denied'}='st';
12437: }
12438: if ($args->{'disablechat'}) {
12439: $cenv{'plc.roles.denied'}='st';
12440: }
12441:
12442: # Record we've not yet viewed the Course Initialization Helper for this
12443: # course
12444: $cenv{'course.helper.not.run'} = 1;
12445: #
12446: # Use new Randomseed
12447: #
12448: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
12449: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
12450: #
12451: # The encryption code and receipt prefix for this course
12452: #
12453: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
12454: $cenv{'internal.encpref'}=100+int(9*rand(99));
12455: #
12456: # By default, use standard grading
12457: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
12458:
12459: $outcome .= $linefeed.&mt('Setting environment').': '.
12460: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
12461: #
12462: # Open all assignments
12463: #
12464: if ($args->{'openall'}) {
12465: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
12466: my %storecontent = ($storeunder => time,
12467: $storeunder.'.type' => 'date_start');
12468:
12469: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
12470: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
12471: }
12472: #
12473: # Set first page
12474: #
12475: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
12476: || ($cloneid)) {
12477: use LONCAPA::map;
12478: $outcome .= &mt('Setting first resource').': ';
12479:
12480: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
12481: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
12482:
12483: $outcome .= ($fatal?$errtext:'read ok').' - ';
12484: my $title; my $url;
12485: if ($args->{'firstres'} eq 'syl') {
12486: $title=&mt('Syllabus');
12487: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
12488: } else {
12489: $title=&mt('Table of Contents');
12490: $url='/adm/navmaps';
12491: }
12492:
12493: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
12494: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
12495:
12496: if ($errtext) { $fatal=2; }
12497: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
12498: }
12499:
12500: return (1,$outcome);
12501: }
12502:
12503: ############################################################
12504: ############################################################
12505:
12506: #SD
12507: # only Community and Course, or anything else?
12508: sub course_type {
12509: my ($cid) = @_;
12510: if (!defined($cid)) {
12511: $cid = $env{'request.course.id'};
12512: }
12513: if (defined($env{'course.'.$cid.'.type'})) {
12514: return $env{'course.'.$cid.'.type'};
12515: } else {
12516: return 'Course';
12517: }
12518: }
12519:
12520: sub group_term {
12521: my $crstype = &course_type();
12522: my %names = (
12523: 'Course' => 'group',
12524: 'Community' => 'group',
12525: );
12526: return $names{$crstype};
12527: }
12528:
12529: sub course_types {
12530: my @types = ('official','unofficial','community');
12531: my %typename = (
12532: official => 'Official course',
12533: unofficial => 'Unofficial course',
12534: community => 'Community',
12535: );
12536: return (\@types,\%typename);
12537: }
12538:
12539: sub icon {
12540: my ($file)=@_;
12541: my $curfext = lc((split(/\./,$file))[-1]);
12542: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
12543: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
12544: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
12545: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
12546: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
12547: $curfext.".gif") {
12548: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
12549: $curfext.".gif";
12550: }
12551: }
12552: return &lonhttpdurl($iconname);
12553: }
12554:
12555: sub lonhttpdurl {
12556: #
12557: # Had been used for "small fry" static images on separate port 8080.
12558: # Modify here if lightweight http functionality desired again.
12559: # Currently eliminated due to increasing firewall issues.
12560: #
12561: my ($url)=@_;
12562: return $url;
12563: }
12564:
12565: sub connection_aborted {
12566: my ($r)=@_;
12567: $r->print(" ");$r->rflush();
12568: my $c = $r->connection;
12569: return $c->aborted();
12570: }
12571:
12572: # Escapes strings that may have embedded 's that will be put into
12573: # strings as 'strings'.
12574: sub escape_single {
12575: my ($input) = @_;
12576: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
12577: $input =~ s/\'/\\\'/g; # Esacpe the 's....
12578: return $input;
12579: }
12580:
12581: # Same as escape_single, but escape's "'s This
12582: # can be used for "strings"
12583: sub escape_double {
12584: my ($input) = @_;
12585: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
12586: $input =~ s/\"/\\\"/g; # Esacpe the "s....
12587: return $input;
12588: }
12589:
12590: # Escapes the last element of a full URL.
12591: sub escape_url {
12592: my ($url) = @_;
12593: my @urlslices = split(/\//, $url,-1);
12594: my $lastitem = &escape(pop(@urlslices));
12595: return join('/',@urlslices).'/'.$lastitem;
12596: }
12597:
12598: sub compare_arrays {
12599: my ($arrayref1,$arrayref2) = @_;
12600: my (@difference,%count);
12601: @difference = ();
12602: %count = ();
12603: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
12604: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
12605: foreach my $element (keys(%count)) {
12606: if ($count{$element} == 1) {
12607: push(@difference,$element);
12608: }
12609: }
12610: }
12611: return @difference;
12612: }
12613:
12614: # -------------------------------------------------------- Initialize user login
12615: sub init_user_environment {
12616: my ($r, $username, $domain, $authhost, $form, $args) = @_;
12617: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
12618:
12619: my $public=($username eq 'public' && $domain eq 'public');
12620:
12621: # See if old ID present, if so, remove
12622:
12623: my ($filename,$cookie,$userroles);
12624: my $now=time;
12625:
12626: if ($public) {
12627: my $max_public=100;
12628: my $oldest;
12629: my $oldest_time=0;
12630: for(my $next=1;$next<=$max_public;$next++) {
12631: if (-e $lonids."/publicuser_$next.id") {
12632: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
12633: if ($mtime<$oldest_time || !$oldest_time) {
12634: $oldest_time=$mtime;
12635: $oldest=$next;
12636: }
12637: } else {
12638: $cookie="publicuser_$next";
12639: last;
12640: }
12641: }
12642: if (!$cookie) { $cookie="publicuser_$oldest"; }
12643: } else {
12644: # if this isn't a robot, kill any existing non-robot sessions
12645: if (!$args->{'robot'}) {
12646: opendir(DIR,$lonids);
12647: while ($filename=readdir(DIR)) {
12648: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
12649: unlink($lonids.'/'.$filename);
12650: }
12651: }
12652: closedir(DIR);
12653: }
12654: # Give them a new cookie
12655: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
12656: : $now.$$.int(rand(10000)));
12657: $cookie="$username\_$id\_$domain\_$authhost";
12658:
12659: # Initialize roles
12660:
12661: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
12662: }
12663: # ------------------------------------ Check browser type and MathML capability
12664:
12665: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
12666: $clientunicode,$clientos) = &decode_user_agent($r);
12667:
12668: # ------------------------------------------------------------- Get environment
12669:
12670: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
12671: my ($tmp) = keys(%userenv);
12672: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12673: } else {
12674: undef(%userenv);
12675: }
12676: if (($userenv{'interface'}) && (!$form->{'interface'})) {
12677: $form->{'interface'}=$userenv{'interface'};
12678: }
12679: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
12680:
12681: # --------------- Do not trust query string to be put directly into environment
12682: foreach my $option ('interface','localpath','localres') {
12683: $form->{$option}=~s/[\n\r\=]//gs;
12684: }
12685: # --------------------------------------------------------- Write first profile
12686:
12687: {
12688: my %initial_env =
12689: ("user.name" => $username,
12690: "user.domain" => $domain,
12691: "user.home" => $authhost,
12692: "browser.type" => $clientbrowser,
12693: "browser.version" => $clientversion,
12694: "browser.mathml" => $clientmathml,
12695: "browser.unicode" => $clientunicode,
12696: "browser.os" => $clientos,
12697: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
12698: "request.course.fn" => '',
12699: "request.course.uri" => '',
12700: "request.course.sec" => '',
12701: "request.role" => 'cm',
12702: "request.role.adv" => $env{'user.adv'},
12703: "request.host" => $ENV{'REMOTE_ADDR'},);
12704:
12705: if ($form->{'localpath'}) {
12706: $initial_env{"browser.localpath"} = $form->{'localpath'};
12707: $initial_env{"browser.localres"} = $form->{'localres'};
12708: }
12709:
12710: if ($form->{'interface'}) {
12711: $form->{'interface'}=~s/\W//gs;
12712: $initial_env{"browser.interface"} = $form->{'interface'};
12713: $env{'browser.interface'}=$form->{'interface'};
12714: }
12715:
12716: my %is_adv = ( is_adv => $env{'user.adv'} );
12717: my %domdef;
12718: unless ($domain eq 'public') {
12719: %domdef = &Apache::lonnet::get_domain_defaults($domain);
12720: }
12721:
12722: foreach my $tool ('aboutme','blog','portfolio') {
12723: $userenv{'availabletools.'.$tool} =
12724: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
12725: undef,\%userenv,\%domdef,\%is_adv);
12726: }
12727:
12728: foreach my $crstype ('official','unofficial','community') {
12729: $userenv{'canrequest.'.$crstype} =
12730: &Apache::lonnet::usertools_access($username,$domain,$crstype,
12731: 'reload','requestcourses',
12732: \%userenv,\%domdef,\%is_adv);
12733: }
12734:
12735: $env{'user.environment'} = "$lonids/$cookie.id";
12736:
12737: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
12738: &GDBM_WRCREAT(),0640)) {
12739: &_add_to_env(\%disk_env,\%initial_env);
12740: &_add_to_env(\%disk_env,\%userenv,'environment.');
12741: &_add_to_env(\%disk_env,$userroles);
12742: if (ref($args->{'extra_env'})) {
12743: &_add_to_env(\%disk_env,$args->{'extra_env'});
12744: }
12745: untie(%disk_env);
12746: } else {
12747: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
12748: 'Could not create environment storage in lonauth: '.$!.'</span>');
12749: return 'error: '.$!;
12750: }
12751: }
12752: $env{'request.role'}='cm';
12753: $env{'request.role.adv'}=$env{'user.adv'};
12754: $env{'browser.type'}=$clientbrowser;
12755:
12756: return $cookie;
12757:
12758: }
12759:
12760: sub _add_to_env {
12761: my ($idf,$env_data,$prefix) = @_;
12762: if (ref($env_data) eq 'HASH') {
12763: while (my ($key,$value) = each(%$env_data)) {
12764: $idf->{$prefix.$key} = $value;
12765: $env{$prefix.$key} = $value;
12766: }
12767: }
12768: }
12769:
12770: # --- Get the symbolic name of a problem and the url
12771: sub get_symb {
12772: my ($request,$silent) = @_;
12773: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
12774: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
12775: if ($symb eq '') {
12776: if (!$silent) {
12777: $request->print("Unable to handle ambiguous references:$url:.");
12778: return ();
12779: }
12780: }
12781: &Apache::lonenc::check_decrypt(\$symb);
12782: return ($symb);
12783: }
12784:
12785: # --------------------------------------------------------------Get annotation
12786:
12787: sub get_annotation {
12788: my ($symb,$enc) = @_;
12789:
12790: my $key = $symb;
12791: if (!$enc) {
12792: $key =
12793: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
12794: }
12795: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
12796: return $annotation{$key};
12797: }
12798:
12799: sub clean_symb {
12800: my ($symb,$delete_enc) = @_;
12801:
12802: &Apache::lonenc::check_decrypt(\$symb);
12803: my $enc = $env{'request.enc'};
12804: if ($delete_enc) {
12805: delete($env{'request.enc'});
12806: }
12807:
12808: return ($symb,$enc);
12809: }
12810:
12811: sub build_release_hashes {
12812: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
12813: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
12814: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
12815: (ref($randomizetry) eq 'HASH'));
12816: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
12817: my ($item,$name,$value) = split(/:/,$key);
12818: if ($item eq 'parameter') {
12819: if (ref($checkparms->{$name}) eq 'ARRAY') {
12820: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
12821: push(@{$checkparms->{$name}},$value);
12822: }
12823: } else {
12824: push(@{$checkparms->{$name}},$value);
12825: }
12826: } elsif ($item eq 'resourcetag') {
12827: if ($name eq 'responsetype') {
12828: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
12829: }
12830: } elsif ($item eq 'course') {
12831: if ($name eq 'crstype') {
12832: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
12833: }
12834: }
12835: }
12836: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
12837: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
12838: return;
12839: }
12840:
12841: =pod
12842:
12843: =back
12844:
12845: =cut
12846:
12847: 1;
12848: __END__;
12849:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>