1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.61 2013/12/30 01:57:04 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 Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use LONCAPA qw(:DEFAULT :match);
73: use DateTime::TimeZone;
74: use DateTime::Locale::Catalog;
75: use Authen::Captcha;
76: use Captcha::reCAPTCHA;
77:
78: # ---------------------------------------------- Designs
79: use vars qw(%defaultdesign);
80:
81: my $readit;
82:
83:
84: ##
85: ## Global Variables
86: ##
87:
88:
89: # ----------------------------------------------- SSI with retries:
90: #
91:
92: =pod
93:
94: =head1 Server Side include with retries:
95:
96: =over 4
97:
98: =item * &ssi_with_retries(resource,retries form)
99:
100: Performs an ssi with some number of retries. Retries continue either
101: until the result is ok or until the retry count supplied by the
102: caller is exhausted.
103:
104: Inputs:
105:
106: =over 4
107:
108: resource - Identifies the resource to insert.
109:
110: retries - Count of the number of retries allowed.
111:
112: form - Hash that identifies the rendering options.
113:
114: =back
115:
116: Returns:
117:
118: =over 4
119:
120: content - The content of the response. If retries were exhausted this is empty.
121:
122: response - The response from the last attempt (which may or may not have been successful.
123:
124: =back
125:
126: =back
127:
128: =cut
129:
130: sub ssi_with_retries {
131: my ($resource, $retries, %form) = @_;
132:
133:
134: my $ok = 0; # True if we got a good response.
135: my $content;
136: my $response;
137:
138: # Try to get the ssi done. within the retries count:
139:
140: do {
141: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
142: $ok = $response->is_success;
143: if (!$ok) {
144: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
145: }
146: $retries--;
147: } while (!$ok && ($retries > 0));
148:
149: if (!$ok) {
150: $content = ''; # On error return an empty content.
151: }
152: return ($content, $response);
153:
154: }
155:
156:
157:
158: # ----------------------------------------------- Filetypes/Languages/Copyright
159: my %language;
160: my %supported_language;
161: my %latex_language; # For choosing hyphenation in <transl..>
162: my %latex_language_bykey; # for choosing hyphenation from metadata
163: my %cprtag;
164: my %scprtag;
165: my %fe; my %fd; my %fm;
166: my %category_extensions;
167:
168: # ---------------------------------------------- Thesaurus variables
169: #
170: # %Keywords:
171: # A hash used by &keyword to determine if a word is considered a keyword.
172: # $thesaurus_db_file
173: # Scalar containing the full path to the thesaurus database.
174:
175: my %Keywords;
176: my $thesaurus_db_file;
177:
178: #
179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
180: # thesaurus.tab, and filecategories.tab.
181: #
182: BEGIN {
183: # Variable initialization
184: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
185: #
186: unless ($readit) {
187: # ------------------------------------------------------------------- languages
188: {
189: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
190: '/language.tab';
191: if ( open(my $fh,"<$langtabfile") ) {
192: while (my $line = <$fh>) {
193: next if ($line=~/^\#/);
194: chomp($line);
195: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
196: $language{$key}=$val.' - '.$enc;
197: if ($sup) {
198: $supported_language{$key}=$sup;
199: }
200: if ($latex) {
201: $latex_language_bykey{$key} = $latex;
202: $latex_language{$two} = $latex;
203: }
204: }
205: close($fh);
206: }
207: }
208: # ------------------------------------------------------------------ copyrights
209: {
210: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
211: '/copyright.tab';
212: if ( open (my $fh,"<$copyrightfile") ) {
213: while (my $line = <$fh>) {
214: next if ($line=~/^\#/);
215: chomp($line);
216: my ($key,$val)=(split(/\s+/,$line,2));
217: $cprtag{$key}=$val;
218: }
219: close($fh);
220: }
221: }
222: # ----------------------------------------------------------- source copyrights
223: {
224: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
225: '/source_copyright.tab';
226: if ( open (my $fh,"<$sourcecopyrightfile") ) {
227: while (my $line = <$fh>) {
228: next if ($line =~ /^\#/);
229: chomp($line);
230: my ($key,$val)=(split(/\s+/,$line,2));
231: $scprtag{$key}=$val;
232: }
233: close($fh);
234: }
235: }
236:
237: # -------------------------------------------------------------- default domain designs
238: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
239: my $designfile = $designdir.'/default.tab';
240: if ( open (my $fh,"<$designfile") ) {
241: while (my $line = <$fh>) {
242: next if ($line =~ /^\#/);
243: chomp($line);
244: my ($key,$val)=(split(/\=/,$line));
245: if ($val) { $defaultdesign{$key}=$val; }
246: }
247: close($fh);
248: }
249:
250: # ------------------------------------------------------------- file categories
251: {
252: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
253: '/filecategories.tab';
254: if ( open (my $fh,"<$categoryfile") ) {
255: while (my $line = <$fh>) {
256: next if ($line =~ /^\#/);
257: chomp($line);
258: my ($extension,$category)=(split(/\s+/,$line,2));
259: push @{$category_extensions{lc($category)}},$extension;
260: }
261: close($fh);
262: }
263:
264: }
265: # ------------------------------------------------------------------ file types
266: {
267: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
268: '/filetypes.tab';
269: if ( open (my $fh,"<$typesfile") ) {
270: while (my $line = <$fh>) {
271: next if ($line =~ /^\#/);
272: chomp($line);
273: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
274: if ($descr ne '') {
275: $fe{$ending}=lc($emb);
276: $fd{$ending}=$descr;
277: if ($mime ne 'unk') { $fm{$ending}=$mime; }
278: }
279: }
280: close($fh);
281: }
282: }
283: &Apache::lonnet::logthis(
284: "<span style='color:yellow;'>INFO: Read file types</span>");
285: $readit=1;
286: } # end of unless($readit)
287:
288: }
289:
290: ###############################################################
291: ## HTML and Javascript Helper Functions ##
292: ###############################################################
293:
294: =pod
295:
296: =head1 HTML and Javascript Functions
297:
298: =over 4
299:
300: =item * &browser_and_searcher_javascript()
301:
302: X<browsing, javascript>X<searching, javascript>Returns a string
303: containing javascript with two functions, C<openbrowser> and
304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
305: tags.
306:
307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
308:
309: inputs: formname, elementname, only, omit
310:
311: formname and elementname indicate the name of the html form and name of
312: the element that the results of the browsing selection are to be placed in.
313:
314: Specifying 'only' will restrict the browser to displaying only files
315: with the given extension. Can be a comma separated list.
316:
317: Specifying 'omit' will restrict the browser to NOT displaying files
318: with the given extension. Can be a comma separated list.
319:
320: =item * &opensearcher(formname,elementname) [javascript]
321:
322: Inputs: formname, elementname
323:
324: formname and elementname specify the name of the html form and the name
325: of the element the selection from the search results will be placed in.
326:
327: =cut
328:
329: sub browser_and_searcher_javascript {
330: my ($mode)=@_;
331: if (!defined($mode)) { $mode='edit'; }
332: my $resurl=&escape_single(&lastresurl());
333: return <<END;
334: // <!-- BEGIN LON-CAPA Internal
335: var editbrowser = null;
336: function openbrowser(formname,elementname,only,omit,titleelement) {
337: var url = '$resurl/?';
338: if (editbrowser == null) {
339: url += 'launch=1&';
340: }
341: url += 'catalogmode=interactive&';
342: url += 'mode=$mode&';
343: url += 'inhibitmenu=yes&';
344: url += 'form=' + formname + '&';
345: if (only != null) {
346: url += 'only=' + only + '&';
347: } else {
348: url += 'only=&';
349: }
350: if (omit != null) {
351: url += 'omit=' + omit + '&';
352: } else {
353: url += 'omit=&';
354: }
355: if (titleelement != null) {
356: url += 'titleelement=' + titleelement + '&';
357: } else {
358: url += 'titleelement=&';
359: }
360: url += 'element=' + elementname + '';
361: var title = 'Browser';
362: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
363: options += ',width=700,height=600';
364: editbrowser = open(url,title,options,'1');
365: editbrowser.focus();
366: }
367: var editsearcher;
368: function opensearcher(formname,elementname,titleelement) {
369: var url = '/adm/searchcat?';
370: if (editsearcher == null) {
371: url += 'launch=1&';
372: }
373: url += 'catalogmode=interactive&';
374: url += 'mode=$mode&';
375: url += 'form=' + formname + '&';
376: if (titleelement != null) {
377: url += 'titleelement=' + titleelement + '&';
378: } else {
379: url += 'titleelement=&';
380: }
381: url += 'element=' + elementname + '';
382: var title = 'Search';
383: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
384: options += ',width=700,height=600';
385: editsearcher = open(url,title,options,'1');
386: editsearcher.focus();
387: }
388: // END LON-CAPA Internal -->
389: END
390: }
391:
392: sub lastresurl {
393: if ($env{'environment.lastresurl'}) {
394: return $env{'environment.lastresurl'}
395: } else {
396: return '/res';
397: }
398: }
399:
400: sub storeresurl {
401: my $resurl=&Apache::lonnet::clutter(shift);
402: unless ($resurl=~/^\/res/) { return 0; }
403: $resurl=~s/\/$//;
404: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
405: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
406: return 1;
407: }
408:
409: sub studentbrowser_javascript {
410: unless (
411: (($env{'request.course.id'}) &&
412: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
413: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
414: '/'.$env{'request.course.sec'})
415: ))
416: || ($env{'request.role'}=~/^(au|dc|su)/)
417: ) { return ''; }
418: return (<<'ENDSTDBRW');
419: <script type="text/javascript" language="Javascript">
420: // <![CDATA[
421: var stdeditbrowser;
422: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
423: var url = '/adm/pickstudent?';
424: var filter;
425: if (!ignorefilter) {
426: eval('filter=document.'+formname+'.'+uname+'.value;');
427: }
428: if (filter != null) {
429: if (filter != '') {
430: url += 'filter='+filter+'&';
431: }
432: }
433: url += 'form=' + formname + '&unameelement='+uname+
434: '&udomelement='+udom+
435: '&clicker='+clicker;
436: if (roleflag) { url+="&roles=1"; }
437: if (courseadvonly) { url+="&courseadvonly=1"; }
438: var title = 'Student_Browser';
439: var options = 'scrollbars=1,resizable=1,menubar=0';
440: options += ',width=700,height=600';
441: stdeditbrowser = open(url,title,options,'1');
442: stdeditbrowser.focus();
443: }
444: // ]]>
445: </script>
446: ENDSTDBRW
447: }
448:
449: sub resourcebrowser_javascript {
450: unless ($env{'request.course.id'}) { return ''; }
451: return (<<'ENDRESBRW');
452: <script type="text/javascript" language="Javascript">
453: // <![CDATA[
454: var reseditbrowser;
455: function openresbrowser(formname,reslink) {
456: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
457: var title = 'Resource_Browser';
458: var options = 'scrollbars=1,resizable=1,menubar=0';
459: options += ',width=700,height=500';
460: reseditbrowser = open(url,title,options,'1');
461: reseditbrowser.focus();
462: }
463: // ]]>
464: </script>
465: ENDRESBRW
466: }
467:
468: sub selectstudent_link {
469: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
470: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
471: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
472: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
473: if ($env{'request.course.id'}) {
474: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
475: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
476: '/'.$env{'request.course.sec'})) {
477: return '';
478: }
479: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
480: if ($courseadvonly) {
481: $callargs .= ",'',1,1";
482: }
483: return '<span class="LC_nobreak">'.
484: '<a href="javascript:openstdbrowser('.$callargs.');">'.
485: &mt('Select User').'</a></span>';
486: }
487: if ($env{'request.role'}=~/^(au|dc|su)/) {
488: $callargs .= ",'',1";
489: return '<span class="LC_nobreak">'.
490: '<a href="javascript:openstdbrowser('.$callargs.');">'.
491: &mt('Select User').'</a></span>';
492: }
493: return '';
494: }
495:
496: sub selectresource_link {
497: my ($form,$reslink,$arg)=@_;
498:
499: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
500: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
501: unless ($env{'request.course.id'}) { return $arg; }
502: return '<span class="LC_nobreak">'.
503: '<a href="javascript:openresbrowser('.$callargs.');">'.
504: $arg.'</a></span>';
505: }
506:
507:
508:
509: sub authorbrowser_javascript {
510: return <<"ENDAUTHORBRW";
511: <script type="text/javascript" language="JavaScript">
512: // <![CDATA[
513: var stdeditbrowser;
514:
515: function openauthorbrowser(formname,udom) {
516: var url = '/adm/pickauthor?';
517: url += 'form='+formname+'&roledom='+udom;
518: var title = 'Author_Browser';
519: var options = 'scrollbars=1,resizable=1,menubar=0';
520: options += ',width=700,height=600';
521: stdeditbrowser = open(url,title,options,'1');
522: stdeditbrowser.focus();
523: }
524:
525: // ]]>
526: </script>
527: ENDAUTHORBRW
528: }
529:
530: sub coursebrowser_javascript {
531: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
532: $credits_element) = @_;
533: my $wintitle = 'Course_Browser';
534: if ($crstype eq 'Community') {
535: $wintitle = 'Community_Browser';
536: }
537: my $id_functions = &javascript_index_functions();
538: my $output = '
539: <script type="text/javascript" language="JavaScript">
540: // <![CDATA[
541: var stdeditbrowser;'."\n";
542:
543: $output .= <<"ENDSTDBRW";
544: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
545: var url = '/adm/pickcourse?';
546: var formid = getFormIdByName(formname);
547: var domainfilter = getDomainFromSelectbox(formname,udom);
548: if (domainfilter != null) {
549: if (domainfilter != '') {
550: url += 'domainfilter='+domainfilter+'&';
551: }
552: }
553: url += 'form=' + formname + '&cnumelement='+uname+
554: '&cdomelement='+udom+
555: '&cnameelement='+desc;
556: if (extra_element !=null && extra_element != '') {
557: if (formname == 'rolechoice' || formname == 'studentform') {
558: url += '&roleelement='+extra_element;
559: if (domainfilter == null || domainfilter == '') {
560: url += '&domainfilter='+extra_element;
561: }
562: }
563: else {
564: if (formname == 'portform') {
565: url += '&setroles='+extra_element;
566: } else {
567: if (formname == 'rules') {
568: url += '&fixeddom='+extra_element;
569: }
570: }
571: }
572: }
573: if (type != null && type != '') {
574: url += '&type='+type;
575: }
576: if (type_elem != null && type_elem != '') {
577: url += '&typeelement='+type_elem;
578: }
579: if (formname == 'ccrs') {
580: var ownername = document.forms[formid].ccuname.value;
581: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
582: url += '&cloner='+ownername+':'+ownerdom;
583: }
584: if (multflag !=null && multflag != '') {
585: url += '&multiple='+multflag;
586: }
587: var title = '$wintitle';
588: var options = 'scrollbars=1,resizable=1,menubar=0';
589: options += ',width=700,height=600';
590: stdeditbrowser = open(url,title,options,'1');
591: stdeditbrowser.focus();
592: }
593: $id_functions
594: ENDSTDBRW
595: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
596: $output .= &setsec_javascript($sec_element,$formname,$role_element,
597: $credits_element);
598: }
599: $output .= '
600: // ]]>
601: </script>';
602: return $output;
603: }
604:
605: sub javascript_index_functions {
606: return <<"ENDJS";
607:
608: function getFormIdByName(formname) {
609: for (var i=0;i<document.forms.length;i++) {
610: if (document.forms[i].name == formname) {
611: return i;
612: }
613: }
614: return -1;
615: }
616:
617: function getIndexByName(formid,item) {
618: for (var i=0;i<document.forms[formid].elements.length;i++) {
619: if (document.forms[formid].elements[i].name == item) {
620: return i;
621: }
622: }
623: return -1;
624: }
625:
626: function getDomainFromSelectbox(formname,udom) {
627: var userdom;
628: var formid = getFormIdByName(formname);
629: if (formid > -1) {
630: var domid = getIndexByName(formid,udom);
631: if (domid > -1) {
632: if (document.forms[formid].elements[domid].type == 'select-one') {
633: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
634: }
635: if (document.forms[formid].elements[domid].type == 'hidden') {
636: userdom=document.forms[formid].elements[domid].value;
637: }
638: }
639: }
640: return userdom;
641: }
642:
643: ENDJS
644:
645: }
646:
647: sub javascript_array_indexof {
648: return <<ENDJS;
649: <script type="text/javascript" language="JavaScript">
650: // <![CDATA[
651:
652: if (!Array.prototype.indexOf) {
653: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
654: "use strict";
655: if (this === void 0 || this === null) {
656: throw new TypeError();
657: }
658: var t = Object(this);
659: var len = t.length >>> 0;
660: if (len === 0) {
661: return -1;
662: }
663: var n = 0;
664: if (arguments.length > 0) {
665: n = Number(arguments[1]);
666: if (n !== n) { // shortcut for verifying if it's NaN
667: n = 0;
668: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
669: n = (n > 0 || -1) * Math.floor(Math.abs(n));
670: }
671: }
672: if (n >= len) {
673: return -1;
674: }
675: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
676: for (; k < len; k++) {
677: if (k in t && t[k] === searchElement) {
678: return k;
679: }
680: }
681: return -1;
682: }
683: }
684:
685: // ]]>
686: </script>
687:
688: ENDJS
689:
690: }
691:
692: sub userbrowser_javascript {
693: my $id_functions = &javascript_index_functions();
694: return <<"ENDUSERBRW";
695:
696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
697: var url = '/adm/pickuser?';
698: var userdom = getDomainFromSelectbox(formname,udom);
699: if (userdom != null) {
700: if (userdom != '') {
701: url += 'srchdom='+userdom+'&';
702: }
703: }
704: url += 'form=' + formname + '&unameelement='+uname+
705: '&udomelement='+udom+
706: '&ulastelement='+ulast+
707: '&ufirstelement='+ufirst+
708: '&uemailelement='+uemail+
709: '&hideudomelement='+hideudom+
710: '&coursedom='+crsdom;
711: if ((caller != null) && (caller != undefined)) {
712: url += '&caller='+caller;
713: }
714: var title = 'User_Browser';
715: var options = 'scrollbars=1,resizable=1,menubar=0';
716: options += ',width=700,height=600';
717: var stdeditbrowser = open(url,title,options,'1');
718: stdeditbrowser.focus();
719: }
720:
721: function fix_domain (formname,udom,origdom,uname) {
722: var formid = getFormIdByName(formname);
723: if (formid > -1) {
724: var unameid = getIndexByName(formid,uname);
725: var domid = getIndexByName(formid,udom);
726: var hidedomid = getIndexByName(formid,origdom);
727: if (hidedomid > -1) {
728: var fixeddom = document.forms[formid].elements[hidedomid].value;
729: var unameval = document.forms[formid].elements[unameid].value;
730: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
731: if (domid > -1) {
732: var slct = document.forms[formid].elements[domid];
733: if (slct.type == 'select-one') {
734: var i;
735: for (i=0;i<slct.length;i++) {
736: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
737: }
738: }
739: if (slct.type == 'hidden') {
740: slct.value = fixeddom;
741: }
742: }
743: }
744: }
745: }
746: return;
747: }
748:
749: $id_functions
750: ENDUSERBRW
751: }
752:
753: sub setsec_javascript {
754: my ($sec_element,$formname,$role_element,$credits_element) = @_;
755: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
756: $communityrolestr);
757: if ($role_element ne '') {
758: my @allroles = ('st','ta','ep','in','ad');
759: foreach my $crstype ('Course','Community') {
760: if ($crstype eq 'Community') {
761: foreach my $role (@allroles) {
762: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
763: }
764: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
765: } else {
766: foreach my $role (@allroles) {
767: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
768: }
769: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
770: }
771: }
772: $rolestr = '"'.join('","',@allroles).'"';
773: $courserolestr = '"'.join('","',@courserolenames).'"';
774: $communityrolestr = '"'.join('","',@communityrolenames).'"';
775: }
776: my $setsections = qq|
777: function setSect(sectionlist) {
778: var sectionsArray = new Array();
779: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
780: sectionsArray = sectionlist.split(",");
781: }
782: var numSections = sectionsArray.length;
783: document.$formname.$sec_element.length = 0;
784: if (numSections == 0) {
785: document.$formname.$sec_element.multiple=false;
786: document.$formname.$sec_element.size=1;
787: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
788: } else {
789: if (numSections == 1) {
790: document.$formname.$sec_element.multiple=false;
791: document.$formname.$sec_element.size=1;
792: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
793: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
794: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
795: } else {
796: for (var i=0; i<numSections; i++) {
797: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
798: }
799: document.$formname.$sec_element.multiple=true
800: if (numSections < 3) {
801: document.$formname.$sec_element.size=numSections;
802: } else {
803: document.$formname.$sec_element.size=3;
804: }
805: document.$formname.$sec_element.options[0].selected = false
806: }
807: }
808: }
809:
810: function setRole(crstype) {
811: |;
812: if ($role_element eq '') {
813: $setsections .= ' return;
814: }
815: ';
816: } else {
817: $setsections .= qq|
818: var elementLength = document.$formname.$role_element.length;
819: var allroles = Array($rolestr);
820: var courserolenames = Array($courserolestr);
821: var communityrolenames = Array($communityrolestr);
822: if (elementLength != undefined) {
823: if (document.$formname.$role_element.options[5].value == 'cc') {
824: if (crstype == 'Course') {
825: return;
826: } else {
827: allroles[5] = 'co';
828: for (var i=0; i<6; i++) {
829: document.$formname.$role_element.options[i].value = allroles[i];
830: document.$formname.$role_element.options[i].text = communityrolenames[i];
831: }
832: }
833: } else {
834: if (crstype == 'Community') {
835: return;
836: } else {
837: allroles[5] = 'cc';
838: for (var i=0; i<6; i++) {
839: document.$formname.$role_element.options[i].value = allroles[i];
840: document.$formname.$role_element.options[i].text = courserolenames[i];
841: }
842: }
843: }
844: }
845: return;
846: }
847: |;
848: }
849: if ($credits_element) {
850: $setsections .= qq|
851: function setCredits(defaultcredits) {
852: document.$formname.$credits_element.value = defaultcredits;
853: return;
854: }
855: |;
856: }
857: return $setsections;
858: }
859:
860: sub selectcourse_link {
861: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
862: $typeelement) = @_;
863: my $type = $selecttype;
864: my $linktext = &mt('Select Course');
865: if ($selecttype eq 'Community') {
866: $linktext = &mt('Select Community');
867: } elsif ($selecttype eq 'Course/Community') {
868: $linktext = &mt('Select Course/Community');
869: $type = '';
870: } elsif ($selecttype eq 'Select') {
871: $linktext = &mt('Select');
872: $type = '';
873: }
874: return '<span class="LC_nobreak">'
875: ."<a href='"
876: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
877: .'","'.$udomele.'","'.$desc.'","'.$extra_element
878: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
879: ."'>".$linktext.'</a>'
880: .'</span>';
881: }
882:
883: sub selectauthor_link {
884: my ($form,$udom)=@_;
885: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
886: &mt('Select Author').'</a>';
887: }
888:
889: sub selectuser_link {
890: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
891: $coursedom,$linktext,$caller) = @_;
892: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
893: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
894: ');">'.$linktext.'</a>';
895: }
896:
897: sub check_uncheck_jscript {
898: my $jscript = <<"ENDSCRT";
899: function checkAll(field) {
900: if (field.length > 0) {
901: for (i = 0; i < field.length; i++) {
902: if (!field[i].disabled) {
903: field[i].checked = true;
904: }
905: }
906: } else {
907: if (!field.disabled) {
908: field.checked = true;
909: }
910: }
911: }
912:
913: function uncheckAll(field) {
914: if (field.length > 0) {
915: for (i = 0; i < field.length; i++) {
916: field[i].checked = false ;
917: }
918: } else {
919: field.checked = false ;
920: }
921: }
922: ENDSCRT
923: return $jscript;
924: }
925:
926: sub select_timezone {
927: my ($name,$selected,$onchange,$includeempty)=@_;
928: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
929: if ($includeempty) {
930: $output .= '<option value=""';
931: if (($selected eq '') || ($selected eq 'local')) {
932: $output .= ' selected="selected" ';
933: }
934: $output .= '> </option>';
935: }
936: my @timezones = DateTime::TimeZone->all_names;
937: foreach my $tzone (@timezones) {
938: $output.= '<option value="'.$tzone.'"';
939: if ($tzone eq $selected) {
940: $output.=' selected="selected"';
941: }
942: $output.=">$tzone</option>\n";
943: }
944: $output.="</select>";
945: return $output;
946: }
947:
948: sub select_datelocale {
949: my ($name,$selected,$onchange,$includeempty)=@_;
950: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
951: if ($includeempty) {
952: $output .= '<option value=""';
953: if ($selected eq '') {
954: $output .= ' selected="selected" ';
955: }
956: $output .= '> </option>';
957: }
958: my (@possibles,%locale_names);
959: my @locales = DateTime::Locale::Catalog::Locales;
960: foreach my $locale (@locales) {
961: if (ref($locale) eq 'HASH') {
962: my $id = $locale->{'id'};
963: if ($id ne '') {
964: my $en_terr = $locale->{'en_territory'};
965: my $native_terr = $locale->{'native_territory'};
966: my @languages = &Apache::lonlocal::preferred_languages();
967: if (grep(/^en$/,@languages) || !@languages) {
968: if ($en_terr ne '') {
969: $locale_names{$id} = '('.$en_terr.')';
970: } elsif ($native_terr ne '') {
971: $locale_names{$id} = $native_terr;
972: }
973: } else {
974: if ($native_terr ne '') {
975: $locale_names{$id} = $native_terr.' ';
976: } elsif ($en_terr ne '') {
977: $locale_names{$id} = '('.$en_terr.')';
978: }
979: }
980: push (@possibles,$id);
981: }
982: }
983: }
984: foreach my $item (sort(@possibles)) {
985: $output.= '<option value="'.$item.'"';
986: if ($item eq $selected) {
987: $output.=' selected="selected"';
988: }
989: $output.=">$item";
990: if ($locale_names{$item} ne '') {
991: $output.=" $locale_names{$item}</option>\n";
992: }
993: $output.="</option>\n";
994: }
995: $output.="</select>";
996: return $output;
997: }
998:
999: sub select_language {
1000: my ($name,$selected,$includeempty) = @_;
1001: my %langchoices;
1002: if ($includeempty) {
1003: %langchoices = ('' => 'No language preference');
1004: }
1005: foreach my $id (&languageids()) {
1006: my $code = &supportedlanguagecode($id);
1007: if ($code) {
1008: $langchoices{$code} = &plainlanguagedescription($id);
1009: }
1010: }
1011: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1012: return &select_form($selected,$name,\%langchoices);
1013: }
1014:
1015: =pod
1016:
1017: =item * &linked_select_forms(...)
1018:
1019: linked_select_forms returns a string containing a <script></script> block
1020: and html for two <select> menus. The select menus will be linked in that
1021: changing the value of the first menu will result in new values being placed
1022: in the second menu. The values in the select menu will appear in alphabetical
1023: order unless a defined order is provided.
1024:
1025: linked_select_forms takes the following ordered inputs:
1026:
1027: =over 4
1028:
1029: =item * $formname, the name of the <form> tag
1030:
1031: =item * $middletext, the text which appears between the <select> tags
1032:
1033: =item * $firstdefault, the default value for the first menu
1034:
1035: =item * $firstselectname, the name of the first <select> tag
1036:
1037: =item * $secondselectname, the name of the second <select> tag
1038:
1039: =item * $hashref, a reference to a hash containing the data for the menus.
1040:
1041: =item * $menuorder, the order of values in the first menu
1042:
1043: =item * $onchangefirst, additional javascript call to execute for an onchange
1044: event for the first <select> tag
1045:
1046: =item * $onchangesecond, additional javascript call to execute for an onchange
1047: event for the second <select> tag
1048:
1049: =back
1050:
1051: Below is an example of such a hash. Only the 'text', 'default', and
1052: 'select2' keys must appear as stated. keys(%menu) are the possible
1053: values for the first select menu. The text that coincides with the
1054: first menu value is given in $menu{$choice1}->{'text'}. The values
1055: and text for the second menu are given in the hash pointed to by
1056: $menu{$choice1}->{'select2'}.
1057:
1058: my %menu = ( A1 => { text =>"Choice A1" ,
1059: default => "B3",
1060: select2 => {
1061: B1 => "Choice B1",
1062: B2 => "Choice B2",
1063: B3 => "Choice B3",
1064: B4 => "Choice B4"
1065: },
1066: order => ['B4','B3','B1','B2'],
1067: },
1068: A2 => { text =>"Choice A2" ,
1069: default => "C2",
1070: select2 => {
1071: C1 => "Choice C1",
1072: C2 => "Choice C2",
1073: C3 => "Choice C3"
1074: },
1075: order => ['C2','C1','C3'],
1076: },
1077: A3 => { text =>"Choice A3" ,
1078: default => "D6",
1079: select2 => {
1080: D1 => "Choice D1",
1081: D2 => "Choice D2",
1082: D3 => "Choice D3",
1083: D4 => "Choice D4",
1084: D5 => "Choice D5",
1085: D6 => "Choice D6",
1086: D7 => "Choice D7"
1087: },
1088: order => ['D4','D3','D2','D1','D7','D6','D5'],
1089: }
1090: );
1091:
1092: =cut
1093:
1094: sub linked_select_forms {
1095: my ($formname,
1096: $middletext,
1097: $firstdefault,
1098: $firstselectname,
1099: $secondselectname,
1100: $hashref,
1101: $menuorder,
1102: $onchangefirst,
1103: $onchangesecond
1104: ) = @_;
1105: my $second = "document.$formname.$secondselectname";
1106: my $first = "document.$formname.$firstselectname";
1107: # output the javascript to do the changing
1108: my $result = '';
1109: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1110: $result.="// <![CDATA[\n";
1111: $result.="var select2data = new Object();\n";
1112: $" = '","';
1113: my $debug = '';
1114: foreach my $s1 (sort(keys(%$hashref))) {
1115: $result.="select2data.d_$s1 = new Object();\n";
1116: $result.="select2data.d_$s1.def = new String('".
1117: $hashref->{$s1}->{'default'}."');\n";
1118: $result.="select2data.d_$s1.values = new Array(";
1119: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1120: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1121: @s2values = @{$hashref->{$s1}->{'order'}};
1122: }
1123: $result.="\"@s2values\");\n";
1124: $result.="select2data.d_$s1.texts = new Array(";
1125: my @s2texts;
1126: foreach my $value (@s2values) {
1127: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1128: }
1129: $result.="\"@s2texts\");\n";
1130: }
1131: $"=' ';
1132: $result.= <<"END";
1133:
1134: function select1_changed() {
1135: // Determine new choice
1136: var newvalue = "d_" + $first.value;
1137: // update select2
1138: var values = select2data[newvalue].values;
1139: var texts = select2data[newvalue].texts;
1140: var select2def = select2data[newvalue].def;
1141: var i;
1142: // out with the old
1143: for (i = 0; i < $second.options.length; i++) {
1144: $second.options[i] = null;
1145: }
1146: // in with the nuclear
1147: for (i=0;i<values.length; i++) {
1148: $second.options[i] = new Option(values[i]);
1149: $second.options[i].value = values[i];
1150: $second.options[i].text = texts[i];
1151: if (values[i] == select2def) {
1152: $second.options[i].selected = true;
1153: }
1154: }
1155: }
1156: // ]]>
1157: </script>
1158: END
1159: # output the initial values for the selection lists
1160: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1161: my @order = sort(keys(%{$hashref}));
1162: if (ref($menuorder) eq 'ARRAY') {
1163: @order = @{$menuorder};
1164: }
1165: foreach my $value (@order) {
1166: $result.=" <option value=\"$value\" ";
1167: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1168: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1169: }
1170: $result .= "</select>\n";
1171: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1172: $result .= $middletext;
1173: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1174: if ($onchangesecond) {
1175: $result .= ' onchange="'.$onchangesecond.'"';
1176: }
1177: $result .= ">\n";
1178: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1179:
1180: my @secondorder = sort(keys(%select2));
1181: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1182: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1183: }
1184: foreach my $value (@secondorder) {
1185: $result.=" <option value=\"$value\" ";
1186: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1187: $result.=">".&mt($select2{$value})."</option>\n";
1188: }
1189: $result .= "</select>\n";
1190: # return $debug;
1191: return $result;
1192: } # end of sub linked_select_forms {
1193:
1194: =pod
1195:
1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1197:
1198: Returns a string corresponding to an HTML link to the given help
1199: $topic, where $topic corresponds to the name of a .tex file in
1200: /home/httpd/html/adm/help/tex, with underscores replaced by
1201: spaces.
1202:
1203: $text will optionally be linked to the same topic, allowing you to
1204: link text in addition to the graphic. If you do not want to link
1205: text, but wish to specify one of the later parameters, pass an
1206: empty string.
1207:
1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
1209: the link will not open a new window. If false, the link will open
1210: a new window using Javascript. (Default is false.)
1211:
1212: $width and $height are optional numerical parameters that will
1213: override the width and height of the popped up window, which may
1214: be useful for certain help topics with big pictures included.
1215:
1216: $imgid is the id of the img tag used for the help icon. This may be
1217: used in a javascript call to switch the image src. See
1218: lonhtmlcommon::htmlareaselectactive() for an example.
1219:
1220: =cut
1221:
1222: sub help_open_topic {
1223: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1224: $text = "" if (not defined $text);
1225: $stayOnPage = 0 if (not defined $stayOnPage);
1226: $width = 500 if (not defined $width);
1227: $height = 400 if (not defined $height);
1228: my $filename = $topic;
1229: $filename =~ s/ /_/g;
1230:
1231: my $template = "";
1232: my $link;
1233:
1234: $topic=~s/\W/\_/g;
1235:
1236: if (!$stayOnPage) {
1237: if ($env{'browser.mobile'}) {
1238: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1239: } else {
1240: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1241: }
1242: } elsif ($stayOnPage eq 'popup') {
1243: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1244: } else {
1245: $link = "/adm/help/${filename}.hlp";
1246: }
1247:
1248: # Add the text
1249: if ($text ne "") {
1250: $template.='<span class="LC_help_open_topic">'
1251: .'<a target="_top" href="'.$link.'">'
1252: .$text.'</a>';
1253: }
1254:
1255: # (Always) Add the graphic
1256: my $title = &mt('Online Help');
1257: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1258: if ($imgid ne '') {
1259: $imgid = ' id="'.$imgid.'"';
1260: }
1261: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1262: .'<img src="'.$helpicon.'" border="0"'
1263: .' alt="'.&mt('Help: [_1]',$topic).'"'
1264: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1265: .' /></a>';
1266: if ($text ne "") {
1267: $template.='</span>';
1268: }
1269: return $template;
1270:
1271: }
1272:
1273: # This is a quicky function for Latex cheatsheet editing, since it
1274: # appears in at least four places
1275: sub helpLatexCheatsheet {
1276: my ($topic,$text,$not_author,$stayOnPage) = @_;
1277: my $out;
1278: my $addOther = '';
1279: if ($topic) {
1280: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1281: }
1282: $out = '<span>' # Start cheatsheet
1283: .$addOther
1284: .'<span>'
1285: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1286: .'</span> <span>'
1287: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1288: .'</span>';
1289: unless ($not_author) {
1290: $out .= ' <span>'
1291: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1292: .'</span>';
1293: }
1294: $out .= '</span>'; # End cheatsheet
1295: return $out;
1296: }
1297:
1298: sub general_help {
1299: my $helptopic='Student_Intro';
1300: if ($env{'request.role'}=~/^(ca|au)/) {
1301: $helptopic='Authoring_Intro';
1302: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1303: $helptopic='Course_Coordination_Intro';
1304: } elsif ($env{'request.role'}=~/^dc/) {
1305: $helptopic='Domain_Coordination_Intro';
1306: }
1307: return $helptopic;
1308: }
1309:
1310: sub update_help_link {
1311: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1312: my $origurl = $ENV{'REQUEST_URI'};
1313: $origurl=~s|^/~|/priv/|;
1314: my $timestamp = time;
1315: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1316: $$datum = &escape($$datum);
1317: }
1318:
1319: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1320: my $output .= <<"ENDOUTPUT";
1321: <script type="text/javascript">
1322: // <![CDATA[
1323: banner_link = '$banner_link';
1324: // ]]>
1325: </script>
1326: ENDOUTPUT
1327: return $output;
1328: }
1329:
1330: # now just updates the help link and generates a blue icon
1331: sub help_open_menu {
1332: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1333: = @_;
1334: $stayOnPage = 1;
1335: my $output;
1336: if ($component_help) {
1337: if (!$text) {
1338: $output=&help_open_topic($component_help,undef,$stayOnPage,
1339: $width,$height);
1340: } else {
1341: my $help_text;
1342: $help_text=&unescape($topic);
1343: $output='<table><tr><td>'.
1344: &help_open_topic($component_help,$help_text,$stayOnPage,
1345: $width,$height).'</td></tr></table>';
1346: }
1347: }
1348: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1349: return $output.$banner_link;
1350: }
1351:
1352: sub top_nav_help {
1353: my ($text) = @_;
1354: $text = &mt($text);
1355: my $stay_on_page;
1356: unless ($env{'environment.remote'} eq 'on') {
1357: $stay_on_page = 1;
1358: }
1359: my ($link,$banner_link);
1360: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1361: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1362: : "javascript:helpMenu('open')";
1363: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1364: }
1365: my $title = &mt('Get help');
1366: if ($link) {
1367: return <<"END";
1368: $banner_link
1369: <a href="$link" title="$title">$text</a>
1370: END
1371: } else {
1372: return ' '.$text.' ';
1373: }
1374: }
1375:
1376: sub help_menu_js {
1377: my ($httphost) = @_;
1378: my $stayOnPage = 1;
1379: my $width = 620;
1380: my $height = 600;
1381: my $helptopic=&general_help();
1382: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1383: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1384: my $start_page =
1385: &Apache::loncommon::start_page('Help Menu', undef,
1386: {'frameset' => 1,
1387: 'js_ready' => 1,
1388: 'use_absolute' => $httphost,
1389: 'add_entries' => {
1390: 'border' => '0',
1391: 'rows' => "110,*",},});
1392: my $end_page =
1393: &Apache::loncommon::end_page({'frameset' => 1,
1394: 'js_ready' => 1,});
1395:
1396: my $template .= <<"ENDTEMPLATE";
1397: <script type="text/javascript">
1398: // <![CDATA[
1399: // <!-- BEGIN LON-CAPA Internal
1400: var banner_link = '';
1401: function helpMenu(target) {
1402: var caller = this;
1403: if (target == 'open') {
1404: var newWindow = null;
1405: try {
1406: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1407: }
1408: catch(error) {
1409: writeHelp(caller);
1410: return;
1411: }
1412: if (newWindow) {
1413: caller = newWindow;
1414: }
1415: }
1416: writeHelp(caller);
1417: return;
1418: }
1419: function writeHelp(caller) {
1420: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1421: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1422: caller.document.close();
1423: caller.focus();
1424: }
1425: // END LON-CAPA Internal -->
1426: // ]]>
1427: </script>
1428: ENDTEMPLATE
1429: return $template;
1430: }
1431:
1432: sub help_open_bug {
1433: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1434: unless ($env{'user.adv'}) { return ''; }
1435: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1436: $text = "" if (not defined $text);
1437: $stayOnPage=1;
1438: $width = 600 if (not defined $width);
1439: $height = 600 if (not defined $height);
1440:
1441: $topic=~s/\W+/\+/g;
1442: my $link='';
1443: my $template='';
1444: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1445: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1446: if (!$stayOnPage)
1447: {
1448: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1449: }
1450: else
1451: {
1452: $link = $url;
1453: }
1454: # Add the text
1455: if ($text ne "")
1456: {
1457: $template .=
1458: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1459: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1460: }
1461:
1462: # Add the graphic
1463: my $title = &mt('Report a Bug');
1464: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1465: $template .= <<"ENDTEMPLATE";
1466: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1467: ENDTEMPLATE
1468: if ($text ne '') { $template.='</td></tr></table>' };
1469: return $template;
1470:
1471: }
1472:
1473: sub help_open_faq {
1474: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1475: unless ($env{'user.adv'}) { return ''; }
1476: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1477: $text = "" if (not defined $text);
1478: $stayOnPage=1;
1479: $width = 350 if (not defined $width);
1480: $height = 400 if (not defined $height);
1481:
1482: $topic=~s/\W+/\+/g;
1483: my $link='';
1484: my $template='';
1485: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1486: if (!$stayOnPage)
1487: {
1488: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1489: }
1490: else
1491: {
1492: $link = $url;
1493: }
1494:
1495: # Add the text
1496: if ($text ne "")
1497: {
1498: $template .=
1499: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1500: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1501: }
1502:
1503: # Add the graphic
1504: my $title = &mt('View the FAQ');
1505: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1506: $template .= <<"ENDTEMPLATE";
1507: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1508: ENDTEMPLATE
1509: if ($text ne '') { $template.='</td></tr></table>' };
1510: return $template;
1511:
1512: }
1513:
1514: ###############################################################
1515: ###############################################################
1516:
1517: =pod
1518:
1519: =item * &change_content_javascript():
1520:
1521: This and the next function allow you to create small sections of an
1522: otherwise static HTML page that you can update on the fly with
1523: Javascript, even in Netscape 4.
1524:
1525: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1526: must be written to the HTML page once. It will prove the Javascript
1527: function "change(name, content)". Calling the change function with the
1528: name of the section
1529: you want to update, matching the name passed to C<changable_area>, and
1530: the new content you want to put in there, will put the content into
1531: that area.
1532:
1533: B<Note>: Netscape 4 only reserves enough space for the changable area
1534: to contain room for the original contents. You need to "make space"
1535: for whatever changes you wish to make, and be B<sure> to check your
1536: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1537: it's adequate for updating a one-line status display, but little more.
1538: This script will set the space to 100% width, so you only need to
1539: worry about height in Netscape 4.
1540:
1541: Modern browsers are much less limiting, and if you can commit to the
1542: user not using Netscape 4, this feature may be used freely with
1543: pretty much any HTML.
1544:
1545: =cut
1546:
1547: sub change_content_javascript {
1548: # If we're on Netscape 4, we need to use Layer-based code
1549: if ($env{'browser.type'} eq 'netscape' &&
1550: $env{'browser.version'} =~ /^4\./) {
1551: return (<<NETSCAPE4);
1552: function change(name, content) {
1553: doc = document.layers[name+"___escape"].layers[0].document;
1554: doc.open();
1555: doc.write(content);
1556: doc.close();
1557: }
1558: NETSCAPE4
1559: } else {
1560: # Otherwise, we need to use semi-standards-compliant code
1561: # (technically, "innerHTML" isn't standard but the equivalent
1562: # is really scary, and every useful browser supports it
1563: return (<<DOMBASED);
1564: function change(name, content) {
1565: element = document.getElementById(name);
1566: element.innerHTML = content;
1567: }
1568: DOMBASED
1569: }
1570: }
1571:
1572: =pod
1573:
1574: =item * &changable_area($name,$origContent):
1575:
1576: This provides a "changable area" that can be modified on the fly via
1577: the Javascript code provided in C<change_content_javascript>. $name is
1578: the name you will use to reference the area later; do not repeat the
1579: same name on a given HTML page more then once. $origContent is what
1580: the area will originally contain, which can be left blank.
1581:
1582: =cut
1583:
1584: sub changable_area {
1585: my ($name, $origContent) = @_;
1586:
1587: if ($env{'browser.type'} eq 'netscape' &&
1588: $env{'browser.version'} =~ /^4\./) {
1589: # If this is netscape 4, we need to use the Layer tag
1590: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1591: } else {
1592: return "<span id='$name'>$origContent</span>";
1593: }
1594: }
1595:
1596: =pod
1597:
1598: =item * &viewport_geometry_js
1599:
1600: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1601:
1602: =cut
1603:
1604:
1605: sub viewport_geometry_js {
1606: return <<"GEOMETRY";
1607: var Geometry = {};
1608: function init_geometry() {
1609: if (Geometry.init) { return };
1610: Geometry.init=1;
1611: if (window.innerHeight) {
1612: Geometry.getViewportHeight = function() { return window.innerHeight; };
1613: Geometry.getViewportWidth = function() { return window.innerWidth; };
1614: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1615: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1616: }
1617: else if (document.documentElement && document.documentElement.clientHeight) {
1618: Geometry.getViewportHeight =
1619: function() { return document.documentElement.clientHeight; };
1620: Geometry.getViewportWidth =
1621: function() { return document.documentElement.clientWidth; };
1622:
1623: Geometry.getHorizontalScroll =
1624: function() { return document.documentElement.scrollLeft; };
1625: Geometry.getVerticalScroll =
1626: function() { return document.documentElement.scrollTop; };
1627: }
1628: else if (document.body.clientHeight) {
1629: Geometry.getViewportHeight =
1630: function() { return document.body.clientHeight; };
1631: Geometry.getViewportWidth =
1632: function() { return document.body.clientWidth; };
1633: Geometry.getHorizontalScroll =
1634: function() { return document.body.scrollLeft; };
1635: Geometry.getVerticalScroll =
1636: function() { return document.body.scrollTop; };
1637: }
1638: }
1639:
1640: GEOMETRY
1641: }
1642:
1643: =pod
1644:
1645: =item * &viewport_size_js()
1646:
1647: 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.
1648:
1649: =cut
1650:
1651: sub viewport_size_js {
1652: my $geometry = &viewport_geometry_js();
1653: return <<"DIMS";
1654:
1655: $geometry
1656:
1657: function getViewportDims(width,height) {
1658: init_geometry();
1659: width.value = Geometry.getViewportWidth();
1660: height.value = Geometry.getViewportHeight();
1661: return;
1662: }
1663:
1664: DIMS
1665: }
1666:
1667: =pod
1668:
1669: =item * &resize_textarea_js()
1670:
1671: emits the needed javascript to resize a textarea to be as big as possible
1672:
1673: creates a function resize_textrea that takes two IDs first should be
1674: the id of the element to resize, second should be the id of a div that
1675: surrounds everything that comes after the textarea, this routine needs
1676: to be attached to the <body> for the onload and onresize events.
1677:
1678: =back
1679:
1680: =cut
1681:
1682: sub resize_textarea_js {
1683: my $geometry = &viewport_geometry_js();
1684: return <<"RESIZE";
1685: <script type="text/javascript">
1686: // <![CDATA[
1687: $geometry
1688:
1689: function getX(element) {
1690: var x = 0;
1691: while (element) {
1692: x += element.offsetLeft;
1693: element = element.offsetParent;
1694: }
1695: return x;
1696: }
1697: function getY(element) {
1698: var y = 0;
1699: while (element) {
1700: y += element.offsetTop;
1701: element = element.offsetParent;
1702: }
1703: return y;
1704: }
1705:
1706:
1707: function resize_textarea(textarea_id,bottom_id) {
1708: init_geometry();
1709: var textarea = document.getElementById(textarea_id);
1710: //alert(textarea);
1711:
1712: var textarea_top = getY(textarea);
1713: var textarea_height = textarea.offsetHeight;
1714: var bottom = document.getElementById(bottom_id);
1715: var bottom_top = getY(bottom);
1716: var bottom_height = bottom.offsetHeight;
1717: var window_height = Geometry.getViewportHeight();
1718: var fudge = 23;
1719: var new_height = window_height-fudge-textarea_top-bottom_height;
1720: if (new_height < 300) {
1721: new_height = 300;
1722: }
1723: textarea.style.height=new_height+'px';
1724: }
1725: // ]]>
1726: </script>
1727: RESIZE
1728:
1729: }
1730:
1731: =pod
1732:
1733: =head1 Excel and CSV file utility routines
1734:
1735: =cut
1736:
1737: ###############################################################
1738: ###############################################################
1739:
1740: =pod
1741:
1742: =over 4
1743:
1744: =item * &csv_translate($text)
1745:
1746: Translate $text to allow it to be output as a 'comma separated values'
1747: format.
1748:
1749: =cut
1750:
1751: ###############################################################
1752: ###############################################################
1753: sub csv_translate {
1754: my $text = shift;
1755: $text =~ s/\"/\"\"/g;
1756: $text =~ s/\n/ /g;
1757: return $text;
1758: }
1759:
1760: ###############################################################
1761: ###############################################################
1762:
1763: =pod
1764:
1765: =item * &define_excel_formats()
1766:
1767: Define some commonly used Excel cell formats.
1768:
1769: Currently supported formats:
1770:
1771: =over 4
1772:
1773: =item header
1774:
1775: =item bold
1776:
1777: =item h1
1778:
1779: =item h2
1780:
1781: =item h3
1782:
1783: =item h4
1784:
1785: =item i
1786:
1787: =item date
1788:
1789: =back
1790:
1791: Inputs: $workbook
1792:
1793: Returns: $format, a hash reference.
1794:
1795:
1796: =cut
1797:
1798: ###############################################################
1799: ###############################################################
1800: sub define_excel_formats {
1801: my ($workbook) = @_;
1802: my $format;
1803: $format->{'header'} = $workbook->add_format(bold => 1,
1804: bottom => 1,
1805: align => 'center');
1806: $format->{'bold'} = $workbook->add_format(bold=>1);
1807: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1808: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1809: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1810: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1811: $format->{'i'} = $workbook->add_format(italic=>1);
1812: $format->{'date'} = $workbook->add_format(num_format=>
1813: 'mm/dd/yyyy hh:mm:ss');
1814: return $format;
1815: }
1816:
1817: ###############################################################
1818: ###############################################################
1819:
1820: =pod
1821:
1822: =item * &create_workbook()
1823:
1824: Create an Excel worksheet. If it fails, output message on the
1825: request object and return undefs.
1826:
1827: Inputs: Apache request object
1828:
1829: Returns (undef) on failure,
1830: Excel worksheet object, scalar with filename, and formats
1831: from &Apache::loncommon::define_excel_formats on success
1832:
1833: =cut
1834:
1835: ###############################################################
1836: ###############################################################
1837: sub create_workbook {
1838: my ($r) = @_;
1839: #
1840: # Create the excel spreadsheet
1841: my $filename = '/prtspool/'.
1842: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1843: time.'_'.rand(1000000000).'.xls';
1844: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1845: if (! defined($workbook)) {
1846: $r->log_error("Error creating excel spreadsheet $filename: $!");
1847: $r->print(
1848: '<p class="LC_error">'
1849: .&mt('Problems occurred in creating the new Excel file.')
1850: .' '.&mt('This error has been logged.')
1851: .' '.&mt('Please alert your LON-CAPA administrator.')
1852: .'</p>'
1853: );
1854: return (undef);
1855: }
1856: #
1857: $workbook->set_tempdir(LONCAPA::tempdir());
1858: #
1859: my $format = &Apache::loncommon::define_excel_formats($workbook);
1860: return ($workbook,$filename,$format);
1861: }
1862:
1863: ###############################################################
1864: ###############################################################
1865:
1866: =pod
1867:
1868: =item * &create_text_file()
1869:
1870: Create a file to write to and eventually make available to the user.
1871: If file creation fails, outputs an error message on the request object and
1872: return undefs.
1873:
1874: Inputs: Apache request object, and file suffix
1875:
1876: Returns (undef) on failure,
1877: Filehandle and filename on success.
1878:
1879: =cut
1880:
1881: ###############################################################
1882: ###############################################################
1883: sub create_text_file {
1884: my ($r,$suffix) = @_;
1885: if (! defined($suffix)) { $suffix = 'txt'; };
1886: my $fh;
1887: my $filename = '/prtspool/'.
1888: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1889: time.'_'.rand(1000000000).'.'.$suffix;
1890: $fh = Apache::File->new('>/home/httpd'.$filename);
1891: if (! defined($fh)) {
1892: $r->log_error("Couldn't open $filename for output $!");
1893: $r->print(
1894: '<p class="LC_error">'
1895: .&mt('Problems occurred in creating the output file.')
1896: .' '.&mt('This error has been logged.')
1897: .' '.&mt('Please alert your LON-CAPA administrator.')
1898: .'</p>'
1899: );
1900: }
1901: return ($fh,$filename)
1902: }
1903:
1904:
1905: =pod
1906:
1907: =back
1908:
1909: =cut
1910:
1911: ###############################################################
1912: ## Home server <option> list generating code ##
1913: ###############################################################
1914:
1915: # ------------------------------------------
1916:
1917: sub domain_select {
1918: my ($name,$value,$multiple)=@_;
1919: my %domains=map {
1920: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1921: } &Apache::lonnet::all_domains();
1922: if ($multiple) {
1923: $domains{''}=&mt('Any domain');
1924: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1925: return &multiple_select_form($name,$value,4,\%domains);
1926: } else {
1927: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1928: return &select_form($name,$value,\%domains);
1929: }
1930: }
1931:
1932: #-------------------------------------------
1933:
1934: =pod
1935:
1936: =head1 Routines for form select boxes
1937:
1938: =over 4
1939:
1940: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1941:
1942: Returns a string containing a <select> element int multiple mode
1943:
1944:
1945: Args:
1946: $name - name of the <select> element
1947: $value - scalar or array ref of values that should already be selected
1948: $size - number of rows long the select element is
1949: $hash - the elements should be 'option' => 'shown text'
1950: (shown text should already have been &mt())
1951: $order - (optional) array ref of the order to show the elements in
1952:
1953: =cut
1954:
1955: #-------------------------------------------
1956: sub multiple_select_form {
1957: my ($name,$value,$size,$hash,$order)=@_;
1958: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1959: my $output='';
1960: if (! defined($size)) {
1961: $size = 4;
1962: if (scalar(keys(%$hash))<4) {
1963: $size = scalar(keys(%$hash));
1964: }
1965: }
1966: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1967: my @order;
1968: if (ref($order) eq 'ARRAY') {
1969: @order = @{$order};
1970: } else {
1971: @order = sort(keys(%$hash));
1972: }
1973: if (exists($$hash{'select_form_order'})) {
1974: @order = @{$$hash{'select_form_order'}};
1975: }
1976:
1977: foreach my $key (@order) {
1978: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1979: $output.='selected="selected" ' if ($selected{$key});
1980: $output.='>'.$hash->{$key}."</option>\n";
1981: }
1982: $output.="</select>\n";
1983: return $output;
1984: }
1985:
1986: #-------------------------------------------
1987:
1988: =pod
1989:
1990: =item * &select_form($defdom,$name,$hashref,$onchange)
1991:
1992: Returns a string containing a <select name='$name' size='1'> form to
1993: allow a user to select options from a ref to a hash containing:
1994: option_name => displayed text. An optional $onchange can include
1995: a javascript onchange item, e.g., onchange="this.form.submit();"
1996:
1997: See lonrights.pm for an example invocation and use.
1998:
1999: =cut
2000:
2001: #-------------------------------------------
2002: sub select_form {
2003: my ($def,$name,$hashref,$onchange) = @_;
2004: return unless (ref($hashref) eq 'HASH');
2005: if ($onchange) {
2006: $onchange = ' onchange="'.$onchange.'"';
2007: }
2008: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2009: my @keys;
2010: if (exists($hashref->{'select_form_order'})) {
2011: @keys=@{$hashref->{'select_form_order'}};
2012: } else {
2013: @keys=sort(keys(%{$hashref}));
2014: }
2015: foreach my $key (@keys) {
2016: $selectform.=
2017: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2018: ($key eq $def ? 'selected="selected" ' : '').
2019: ">".$hashref->{$key}."</option>\n";
2020: }
2021: $selectform.="</select>";
2022: return $selectform;
2023: }
2024:
2025: # For display filters
2026:
2027: sub display_filter {
2028: my ($context) = @_;
2029: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2030: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2031: my $phraseinput = 'hidden';
2032: my $includeinput = 'hidden';
2033: my ($checked,$includetypestext);
2034: if ($env{'form.displayfilter'} eq 'containing') {
2035: $phraseinput = 'text';
2036: if ($context eq 'parmslog') {
2037: $includeinput = 'checkbox';
2038: if ($env{'form.includetypes'}) {
2039: $checked = ' checked="checked"';
2040: }
2041: $includetypestext = &mt('Include parameter types');
2042: }
2043: } else {
2044: $includetypestext = ' ';
2045: }
2046: my ($additional,$secondid,$thirdid);
2047: if ($context eq 'parmslog') {
2048: $additional =
2049: '<label><input type="'.$includeinput.'" name="includetypes"'.
2050: $checked.' name="includetypes" value="1" id="includetypes" />'.
2051: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2052: '</label>';
2053: $secondid = 'includetypes';
2054: $thirdid = 'includetypestext';
2055: }
2056: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2057: '$secondid','$thirdid')";
2058: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2059: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2060: (&mt('all'),10,20,50,100,1000,10000))).
2061: '</label></span> <span class="LC_nobreak">'.
2062: &mt('Filter: [_1]',
2063: &select_form($env{'form.displayfilter'},
2064: 'displayfilter',
2065: {'currentfolder' => 'Current folder/page',
2066: 'containing' => 'Containing phrase',
2067: 'none' => 'None'},$onchange)).' '.
2068: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2069: &HTML::Entities::encode($env{'form.containingphrase'}).
2070: '" />'.$additional;
2071: }
2072:
2073: sub display_filter_js {
2074: my $includetext = &mt('Include parameter types');
2075: return <<"ENDJS";
2076:
2077: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2078: var firstType = 'hidden';
2079: if (setter.options[setter.selectedIndex].value == 'containing') {
2080: firstType = 'text';
2081: }
2082: firstObject = document.getElementById(firstid);
2083: if (typeof(firstObject) == 'object') {
2084: if (firstObject.type != firstType) {
2085: changeInputType(firstObject,firstType);
2086: }
2087: }
2088: if (context == 'parmslog') {
2089: var secondType = 'hidden';
2090: if (firstType == 'text') {
2091: secondType = 'checkbox';
2092: }
2093: secondObject = document.getElementById(secondid);
2094: if (typeof(secondObject) == 'object') {
2095: if (secondObject.type != secondType) {
2096: changeInputType(secondObject,secondType);
2097: }
2098: }
2099: var textItem = document.getElementById(thirdid);
2100: var currtext = textItem.innerHTML;
2101: var newtext;
2102: if (firstType == 'text') {
2103: newtext = '$includetext';
2104: } else {
2105: newtext = ' ';
2106: }
2107: if (currtext != newtext) {
2108: textItem.innerHTML = newtext;
2109: }
2110: }
2111: return;
2112: }
2113:
2114: function changeInputType(oldObject,newType) {
2115: var newObject = document.createElement('input');
2116: newObject.type = newType;
2117: if (oldObject.size) {
2118: newObject.size = oldObject.size;
2119: }
2120: if (oldObject.value) {
2121: newObject.value = oldObject.value;
2122: }
2123: if (oldObject.name) {
2124: newObject.name = oldObject.name;
2125: }
2126: if (oldObject.id) {
2127: newObject.id = oldObject.id;
2128: }
2129: oldObject.parentNode.replaceChild(newObject,oldObject);
2130: return;
2131: }
2132:
2133: ENDJS
2134: }
2135:
2136: sub gradeleveldescription {
2137: my $gradelevel=shift;
2138: my %gradelevels=(0 => 'Not specified',
2139: 1 => 'Grade 1',
2140: 2 => 'Grade 2',
2141: 3 => 'Grade 3',
2142: 4 => 'Grade 4',
2143: 5 => 'Grade 5',
2144: 6 => 'Grade 6',
2145: 7 => 'Grade 7',
2146: 8 => 'Grade 8',
2147: 9 => 'Grade 9',
2148: 10 => 'Grade 10',
2149: 11 => 'Grade 11',
2150: 12 => 'Grade 12',
2151: 13 => 'Grade 13',
2152: 14 => '100 Level',
2153: 15 => '200 Level',
2154: 16 => '300 Level',
2155: 17 => '400 Level',
2156: 18 => 'Graduate Level');
2157: return &mt($gradelevels{$gradelevel});
2158: }
2159:
2160: sub select_level_form {
2161: my ($deflevel,$name)=@_;
2162: unless ($deflevel) { $deflevel=0; }
2163: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2164: for (my $i=0; $i<=18; $i++) {
2165: $selectform.="<option value=\"$i\" ".
2166: ($i==$deflevel ? 'selected="selected" ' : '').
2167: ">".&gradeleveldescription($i)."</option>\n";
2168: }
2169: $selectform.="</select>";
2170: return $selectform;
2171: }
2172:
2173: #-------------------------------------------
2174:
2175: =pod
2176:
2177: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
2178:
2179: Returns a string containing a <select name='$name' size='1'> form to
2180: allow a user to select the domain to preform an operation in.
2181: See loncreateuser.pm for an example invocation and use.
2182:
2183: If the $includeempty flag is set, it also includes an empty choice ("no domain
2184: selected");
2185:
2186: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2187:
2188: 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.
2189:
2190: The optional $incdoms is a reference to an array of domains which will be the only available options.
2191:
2192: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2193:
2194: =cut
2195:
2196: #-------------------------------------------
2197: sub select_dom_form {
2198: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
2199: if ($onchange) {
2200: $onchange = ' onchange="'.$onchange.'"';
2201: }
2202: my (@domains,%exclude);
2203: if (ref($incdoms) eq 'ARRAY') {
2204: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2205: } else {
2206: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2207: }
2208: if ($includeempty) { @domains=('',@domains); }
2209: if (ref($excdoms) eq 'ARRAY') {
2210: map { $exclude{$_} = 1; } @{$excdoms};
2211: }
2212: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2213: foreach my $dom (@domains) {
2214: next if ($exclude{$dom});
2215: $selectdomain.="<option value=\"$dom\" ".
2216: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2217: if ($showdomdesc) {
2218: if ($dom ne '') {
2219: my $domdesc = &Apache::lonnet::domain($dom,'description');
2220: if ($domdesc ne '') {
2221: $selectdomain .= ' ('.$domdesc.')';
2222: }
2223: }
2224: }
2225: $selectdomain .= "</option>\n";
2226: }
2227: $selectdomain.="</select>";
2228: return $selectdomain;
2229: }
2230:
2231: #-------------------------------------------
2232:
2233: =pod
2234:
2235: =item * &home_server_form_item($domain,$name,$defaultflag)
2236:
2237: input: 4 arguments (two required, two optional) -
2238: $domain - domain of new user
2239: $name - name of form element
2240: $default - Value of 'default' causes a default item to be first
2241: option, and selected by default.
2242: $hide - Value of 'hide' causes hiding of the name of the server,
2243: if 1 server found, or default, if 0 found.
2244: output: returns 2 items:
2245: (a) form element which contains either:
2246: (i) <select name="$name">
2247: <option value="$hostid1">$hostid $servers{$hostid}</option>
2248: <option value="$hostid2">$hostid $servers{$hostid}</option>
2249: </select>
2250: form item if there are multiple library servers in $domain, or
2251: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2252: if there is only one library server in $domain.
2253:
2254: (b) number of library servers found.
2255:
2256: See loncreateuser.pm for example of use.
2257:
2258: =cut
2259:
2260: #-------------------------------------------
2261: sub home_server_form_item {
2262: my ($domain,$name,$default,$hide) = @_;
2263: my %servers = &Apache::lonnet::get_servers($domain,'library');
2264: my $result;
2265: my $numlib = keys(%servers);
2266: if ($numlib > 1) {
2267: $result .= '<select name="'.$name.'" />'."\n";
2268: if ($default) {
2269: $result .= '<option value="default" selected="selected">'.&mt('default').
2270: '</option>'."\n";
2271: }
2272: foreach my $hostid (sort(keys(%servers))) {
2273: $result.= '<option value="'.$hostid.'">'.
2274: $hostid.' '.$servers{$hostid}."</option>\n";
2275: }
2276: $result .= '</select>'."\n";
2277: } elsif ($numlib == 1) {
2278: my $hostid;
2279: foreach my $item (keys(%servers)) {
2280: $hostid = $item;
2281: }
2282: $result .= '<input type="hidden" name="'.$name.'" value="'.
2283: $hostid.'" />';
2284: if (!$hide) {
2285: $result .= $hostid.' '.$servers{$hostid};
2286: }
2287: $result .= "\n";
2288: } elsif ($default) {
2289: $result .= '<input type="hidden" name="'.$name.
2290: '" value="default" />';
2291: if (!$hide) {
2292: $result .= &mt('default');
2293: }
2294: $result .= "\n";
2295: }
2296: return ($result,$numlib);
2297: }
2298:
2299: =pod
2300:
2301: =back
2302:
2303: =cut
2304:
2305: ###############################################################
2306: ## Decoding User Agent ##
2307: ###############################################################
2308:
2309: =pod
2310:
2311: =head1 Decoding the User Agent
2312:
2313: =over 4
2314:
2315: =item * &decode_user_agent()
2316:
2317: Inputs: $r
2318:
2319: Outputs:
2320:
2321: =over 4
2322:
2323: =item * $httpbrowser
2324:
2325: =item * $clientbrowser
2326:
2327: =item * $clientversion
2328:
2329: =item * $clientmathml
2330:
2331: =item * $clientunicode
2332:
2333: =item * $clientos
2334:
2335: =item * $clientmobile
2336:
2337: =item * $clientinfo
2338:
2339: =back
2340:
2341: =back
2342:
2343: =cut
2344:
2345: ###############################################################
2346: ###############################################################
2347: sub decode_user_agent {
2348: my ($r)=@_;
2349: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2350: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2351: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2352: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2353: my $clientbrowser='unknown';
2354: my $clientversion='0';
2355: my $clientmathml='';
2356: my $clientunicode='0';
2357: my $clientmobile=0;
2358: for (my $i=0;$i<=$#browsertype;$i++) {
2359: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2360: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2361: $clientbrowser=$bname;
2362: $httpbrowser=~/$vreg/i;
2363: $clientversion=$1;
2364: $clientmathml=($clientversion>=$minv);
2365: $clientunicode=($clientversion>=$univ);
2366: }
2367: }
2368: my $clientos='unknown';
2369: my $clientinfo;
2370: if (($httpbrowser=~/linux/i) ||
2371: ($httpbrowser=~/unix/i) ||
2372: ($httpbrowser=~/ux/i) ||
2373: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2374: if (($httpbrowser=~/vax/i) ||
2375: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2376: if ($httpbrowser=~/next/i) { $clientos='next'; }
2377: if (($httpbrowser=~/mac/i) ||
2378: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2379: if ($httpbrowser=~/win/i) { $clientos='win'; }
2380: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2381: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2382: $clientmobile=lc($1);
2383: }
2384: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2385: $clientinfo = 'firefox-'.$1;
2386: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2387: $clientinfo = 'chromeframe-'.$1;
2388: }
2389: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2390: $clientunicode,$clientos,$clientmobile,$clientinfo);
2391: }
2392:
2393: ###############################################################
2394: ## Authentication changing form generation subroutines ##
2395: ###############################################################
2396: ##
2397: ## All of the authform_xxxxxxx subroutines take their inputs in a
2398: ## hash, and have reasonable default values.
2399: ##
2400: ## formname = the name given in the <form> tag.
2401: #-------------------------------------------
2402:
2403: =pod
2404:
2405: =head1 Authentication Routines
2406:
2407: =over 4
2408:
2409: =item * &authform_xxxxxx()
2410:
2411: The authform_xxxxxx subroutines provide javascript and html forms which
2412: handle some of the conveniences required for authentication forms.
2413: This is not an optimal method, but it works.
2414:
2415: =over 4
2416:
2417: =item * authform_header
2418:
2419: =item * authform_authorwarning
2420:
2421: =item * authform_nochange
2422:
2423: =item * authform_kerberos
2424:
2425: =item * authform_internal
2426:
2427: =item * authform_filesystem
2428:
2429: =back
2430:
2431: See loncreateuser.pm for invocation and use examples.
2432:
2433: =cut
2434:
2435: #-------------------------------------------
2436: sub authform_header{
2437: my %in = (
2438: formname => 'cu',
2439: kerb_def_dom => '',
2440: @_,
2441: );
2442: $in{'formname'} = 'document.' . $in{'formname'};
2443: my $result='';
2444:
2445: #---------------------------------------------- Code for upper case translation
2446: my $Javascript_toUpperCase;
2447: unless ($in{kerb_def_dom}) {
2448: $Javascript_toUpperCase =<<"END";
2449: switch (choice) {
2450: case 'krb': currentform.elements[choicearg].value =
2451: currentform.elements[choicearg].value.toUpperCase();
2452: break;
2453: default:
2454: }
2455: END
2456: } else {
2457: $Javascript_toUpperCase = "";
2458: }
2459:
2460: my $radioval = "'nochange'";
2461: if (defined($in{'curr_authtype'})) {
2462: if ($in{'curr_authtype'} ne '') {
2463: $radioval = "'".$in{'curr_authtype'}."arg'";
2464: }
2465: }
2466: my $argfield = 'null';
2467: if (defined($in{'mode'})) {
2468: if ($in{'mode'} eq 'modifycourse') {
2469: if (defined($in{'curr_autharg'})) {
2470: if ($in{'curr_autharg'} ne '') {
2471: $argfield = "'$in{'curr_autharg'}'";
2472: }
2473: }
2474: }
2475: }
2476:
2477: $result.=<<"END";
2478: var current = new Object();
2479: current.radiovalue = $radioval;
2480: current.argfield = $argfield;
2481:
2482: function changed_radio(choice,currentform) {
2483: var choicearg = choice + 'arg';
2484: // If a radio button in changed, we need to change the argfield
2485: if (current.radiovalue != choice) {
2486: current.radiovalue = choice;
2487: if (current.argfield != null) {
2488: currentform.elements[current.argfield].value = '';
2489: }
2490: if (choice == 'nochange') {
2491: current.argfield = null;
2492: } else {
2493: current.argfield = choicearg;
2494: switch(choice) {
2495: case 'krb':
2496: currentform.elements[current.argfield].value =
2497: "$in{'kerb_def_dom'}";
2498: break;
2499: default:
2500: break;
2501: }
2502: }
2503: }
2504: return;
2505: }
2506:
2507: function changed_text(choice,currentform) {
2508: var choicearg = choice + 'arg';
2509: if (currentform.elements[choicearg].value !='') {
2510: $Javascript_toUpperCase
2511: // clear old field
2512: if ((current.argfield != choicearg) && (current.argfield != null)) {
2513: currentform.elements[current.argfield].value = '';
2514: }
2515: current.argfield = choicearg;
2516: }
2517: set_auth_radio_buttons(choice,currentform);
2518: return;
2519: }
2520:
2521: function set_auth_radio_buttons(newvalue,currentform) {
2522: var numauthchoices = currentform.login.length;
2523: if (typeof numauthchoices == "undefined") {
2524: return;
2525: }
2526: var i=0;
2527: while (i < numauthchoices) {
2528: if (currentform.login[i].value == newvalue) { break; }
2529: i++;
2530: }
2531: if (i == numauthchoices) {
2532: return;
2533: }
2534: current.radiovalue = newvalue;
2535: currentform.login[i].checked = true;
2536: return;
2537: }
2538: END
2539: return $result;
2540: }
2541:
2542: sub authform_authorwarning {
2543: my $result='';
2544: $result='<i>'.
2545: &mt('As a general rule, only authors or co-authors should be '.
2546: 'filesystem authenticated '.
2547: '(which allows access to the server filesystem).')."</i>\n";
2548: return $result;
2549: }
2550:
2551: sub authform_nochange {
2552: my %in = (
2553: formname => 'document.cu',
2554: kerb_def_dom => 'MSU.EDU',
2555: @_,
2556: );
2557: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2558: my $result;
2559: if (!$authnum) {
2560: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2561: } else {
2562: $result = '<label>'.&mt('[_1] Do not change login data',
2563: '<input type="radio" name="login" value="nochange" '.
2564: 'checked="checked" onclick="'.
2565: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2566: '</label>';
2567: }
2568: return $result;
2569: }
2570:
2571: sub authform_kerberos {
2572: my %in = (
2573: formname => 'document.cu',
2574: kerb_def_dom => 'MSU.EDU',
2575: kerb_def_auth => 'krb4',
2576: @_,
2577: );
2578: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2579: $autharg,$jscall);
2580: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2581: if ($in{'kerb_def_auth'} eq 'krb5') {
2582: $check5 = ' checked="checked"';
2583: } else {
2584: $check4 = ' checked="checked"';
2585: }
2586: $krbarg = $in{'kerb_def_dom'};
2587: if (defined($in{'curr_authtype'})) {
2588: if ($in{'curr_authtype'} eq 'krb') {
2589: $krbcheck = ' checked="checked"';
2590: if (defined($in{'mode'})) {
2591: if ($in{'mode'} eq 'modifyuser') {
2592: $krbcheck = '';
2593: }
2594: }
2595: if (defined($in{'curr_kerb_ver'})) {
2596: if ($in{'curr_krb_ver'} eq '5') {
2597: $check5 = ' checked="checked"';
2598: $check4 = '';
2599: } else {
2600: $check4 = ' checked="checked"';
2601: $check5 = '';
2602: }
2603: }
2604: if (defined($in{'curr_autharg'})) {
2605: $krbarg = $in{'curr_autharg'};
2606: }
2607: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2608: if (defined($in{'curr_autharg'})) {
2609: $result =
2610: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2611: $in{'curr_autharg'},$krbver);
2612: } else {
2613: $result =
2614: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2615: }
2616: return $result;
2617: }
2618: }
2619: } else {
2620: if ($authnum == 1) {
2621: $authtype = '<input type="hidden" name="login" value="krb" />';
2622: }
2623: }
2624: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2625: return;
2626: } elsif ($authtype eq '') {
2627: if (defined($in{'mode'})) {
2628: if ($in{'mode'} eq 'modifycourse') {
2629: if ($authnum == 1) {
2630: $authtype = '<input type="radio" name="login" value="krb" />';
2631: }
2632: }
2633: }
2634: }
2635: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2636: if ($authtype eq '') {
2637: $authtype = '<input type="radio" name="login" value="krb" '.
2638: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2639: $krbcheck.' />';
2640: }
2641: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2642: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2643: $in{'curr_authtype'} eq 'krb5') ||
2644: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2645: $in{'curr_authtype'} eq 'krb4')) {
2646: $result .= &mt
2647: ('[_1] Kerberos authenticated with domain [_2] '.
2648: '[_3] Version 4 [_4] Version 5 [_5]',
2649: '<label>'.$authtype,
2650: '</label><input type="text" size="10" name="krbarg" '.
2651: 'value="'.$krbarg.'" '.
2652: 'onchange="'.$jscall.'" />',
2653: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2654: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2655: '</label>');
2656: } elsif ($can_assign{'krb4'}) {
2657: $result .= &mt
2658: ('[_1] Kerberos authenticated with domain [_2] '.
2659: '[_3] Version 4 [_4]',
2660: '<label>'.$authtype,
2661: '</label><input type="text" size="10" name="krbarg" '.
2662: 'value="'.$krbarg.'" '.
2663: 'onchange="'.$jscall.'" />',
2664: '<label><input type="hidden" name="krbver" value="4" />',
2665: '</label>');
2666: } elsif ($can_assign{'krb5'}) {
2667: $result .= &mt
2668: ('[_1] Kerberos authenticated with domain [_2] '.
2669: '[_3] Version 5 [_4]',
2670: '<label>'.$authtype,
2671: '</label><input type="text" size="10" name="krbarg" '.
2672: 'value="'.$krbarg.'" '.
2673: 'onchange="'.$jscall.'" />',
2674: '<label><input type="hidden" name="krbver" value="5" />',
2675: '</label>');
2676: }
2677: return $result;
2678: }
2679:
2680: sub authform_internal {
2681: my %in = (
2682: formname => 'document.cu',
2683: kerb_def_dom => 'MSU.EDU',
2684: @_,
2685: );
2686: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2687: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2688: if (defined($in{'curr_authtype'})) {
2689: if ($in{'curr_authtype'} eq 'int') {
2690: if ($can_assign{'int'}) {
2691: $intcheck = 'checked="checked" ';
2692: if (defined($in{'mode'})) {
2693: if ($in{'mode'} eq 'modifyuser') {
2694: $intcheck = '';
2695: }
2696: }
2697: if (defined($in{'curr_autharg'})) {
2698: $intarg = $in{'curr_autharg'};
2699: }
2700: } else {
2701: $result = &mt('Currently internally authenticated.');
2702: return $result;
2703: }
2704: }
2705: } else {
2706: if ($authnum == 1) {
2707: $authtype = '<input type="hidden" name="login" value="int" />';
2708: }
2709: }
2710: if (!$can_assign{'int'}) {
2711: return;
2712: } elsif ($authtype eq '') {
2713: if (defined($in{'mode'})) {
2714: if ($in{'mode'} eq 'modifycourse') {
2715: if ($authnum == 1) {
2716: $authtype = '<input type="radio" name="login" value="int" />';
2717: }
2718: }
2719: }
2720: }
2721: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2722: if ($authtype eq '') {
2723: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2724: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2725: }
2726: $autharg = '<input type="password" size="10" name="intarg" value="'.
2727: $intarg.'" onchange="'.$jscall.'" />';
2728: $result = &mt
2729: ('[_1] Internally authenticated (with initial password [_2])',
2730: '<label>'.$authtype,'</label>'.$autharg);
2731: $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>';
2732: return $result;
2733: }
2734:
2735: sub authform_local {
2736: my %in = (
2737: formname => 'document.cu',
2738: kerb_def_dom => 'MSU.EDU',
2739: @_,
2740: );
2741: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2742: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2743: if (defined($in{'curr_authtype'})) {
2744: if ($in{'curr_authtype'} eq 'loc') {
2745: if ($can_assign{'loc'}) {
2746: $loccheck = 'checked="checked" ';
2747: if (defined($in{'mode'})) {
2748: if ($in{'mode'} eq 'modifyuser') {
2749: $loccheck = '';
2750: }
2751: }
2752: if (defined($in{'curr_autharg'})) {
2753: $locarg = $in{'curr_autharg'};
2754: }
2755: } else {
2756: $result = &mt('Currently using local (institutional) authentication.');
2757: return $result;
2758: }
2759: }
2760: } else {
2761: if ($authnum == 1) {
2762: $authtype = '<input type="hidden" name="login" value="loc" />';
2763: }
2764: }
2765: if (!$can_assign{'loc'}) {
2766: return;
2767: } elsif ($authtype eq '') {
2768: if (defined($in{'mode'})) {
2769: if ($in{'mode'} eq 'modifycourse') {
2770: if ($authnum == 1) {
2771: $authtype = '<input type="radio" name="login" value="loc" />';
2772: }
2773: }
2774: }
2775: }
2776: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2777: if ($authtype eq '') {
2778: $authtype = '<input type="radio" name="login" value="loc" '.
2779: $loccheck.' onchange="'.$jscall.'" onclick="'.
2780: $jscall.'" />';
2781: }
2782: $autharg = '<input type="text" size="10" name="locarg" value="'.
2783: $locarg.'" onchange="'.$jscall.'" />';
2784: $result = &mt('[_1] Local Authentication with argument [_2]',
2785: '<label>'.$authtype,'</label>'.$autharg);
2786: return $result;
2787: }
2788:
2789: sub authform_filesystem {
2790: my %in = (
2791: formname => 'document.cu',
2792: kerb_def_dom => 'MSU.EDU',
2793: @_,
2794: );
2795: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2796: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2797: if (defined($in{'curr_authtype'})) {
2798: if ($in{'curr_authtype'} eq 'fsys') {
2799: if ($can_assign{'fsys'}) {
2800: $fsyscheck = 'checked="checked" ';
2801: if (defined($in{'mode'})) {
2802: if ($in{'mode'} eq 'modifyuser') {
2803: $fsyscheck = '';
2804: }
2805: }
2806: } else {
2807: $result = &mt('Currently Filesystem Authenticated.');
2808: return $result;
2809: }
2810: }
2811: } else {
2812: if ($authnum == 1) {
2813: $authtype = '<input type="hidden" name="login" value="fsys" />';
2814: }
2815: }
2816: if (!$can_assign{'fsys'}) {
2817: return;
2818: } elsif ($authtype eq '') {
2819: if (defined($in{'mode'})) {
2820: if ($in{'mode'} eq 'modifycourse') {
2821: if ($authnum == 1) {
2822: $authtype = '<input type="radio" name="login" value="fsys" />';
2823: }
2824: }
2825: }
2826: }
2827: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2828: if ($authtype eq '') {
2829: $authtype = '<input type="radio" name="login" value="fsys" '.
2830: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2831: $jscall.'" />';
2832: }
2833: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2834: ' onchange="'.$jscall.'" />';
2835: $result = &mt
2836: ('[_1] Filesystem Authenticated (with initial password [_2])',
2837: '<label><input type="radio" name="login" value="fsys" '.
2838: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2839: '</label><input type="password" size="10" name="fsysarg" value="" '.
2840: 'onchange="'.$jscall.'" />');
2841: return $result;
2842: }
2843:
2844: sub get_assignable_auth {
2845: my ($dom) = @_;
2846: if ($dom eq '') {
2847: $dom = $env{'request.role.domain'};
2848: }
2849: my %can_assign = (
2850: krb4 => 1,
2851: krb5 => 1,
2852: int => 1,
2853: loc => 1,
2854: );
2855: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2856: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2857: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2858: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2859: my $context;
2860: if ($env{'request.role'} =~ /^au/) {
2861: $context = 'author';
2862: } elsif ($env{'request.role'} =~ /^dc/) {
2863: $context = 'domain';
2864: } elsif ($env{'request.course.id'}) {
2865: $context = 'course';
2866: }
2867: if ($context) {
2868: if (ref($authhash->{$context}) eq 'HASH') {
2869: %can_assign = %{$authhash->{$context}};
2870: }
2871: }
2872: }
2873: }
2874: my $authnum = 0;
2875: foreach my $key (keys(%can_assign)) {
2876: if ($can_assign{$key}) {
2877: $authnum ++;
2878: }
2879: }
2880: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2881: $authnum --;
2882: }
2883: return ($authnum,%can_assign);
2884: }
2885:
2886: ###############################################################
2887: ## Get Kerberos Defaults for Domain ##
2888: ###############################################################
2889: ##
2890: ## Returns default kerberos version and an associated argument
2891: ## as listed in file domain.tab. If not listed, provides
2892: ## appropriate default domain and kerberos version.
2893: ##
2894: #-------------------------------------------
2895:
2896: =pod
2897:
2898: =item * &get_kerberos_defaults()
2899:
2900: get_kerberos_defaults($target_domain) returns the default kerberos
2901: version and domain. If not found, it defaults to version 4 and the
2902: domain of the server.
2903:
2904: =over 4
2905:
2906: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2907:
2908: =back
2909:
2910: =back
2911:
2912: =cut
2913:
2914: #-------------------------------------------
2915: sub get_kerberos_defaults {
2916: my $domain=shift;
2917: my ($krbdef,$krbdefdom);
2918: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2919: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2920: $krbdef = $domdefaults{'auth_def'};
2921: $krbdefdom = $domdefaults{'auth_arg_def'};
2922: } else {
2923: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2924: my $krbdefdom=$1;
2925: $krbdefdom=~tr/a-z/A-Z/;
2926: $krbdef = "krb4";
2927: }
2928: return ($krbdef,$krbdefdom);
2929: }
2930:
2931:
2932: ###############################################################
2933: ## Thesaurus Functions ##
2934: ###############################################################
2935:
2936: =pod
2937:
2938: =head1 Thesaurus Functions
2939:
2940: =over 4
2941:
2942: =item * &initialize_keywords()
2943:
2944: Initializes the package variable %Keywords if it is empty. Uses the
2945: package variable $thesaurus_db_file.
2946:
2947: =cut
2948:
2949: ###################################################
2950:
2951: sub initialize_keywords {
2952: return 1 if (scalar keys(%Keywords));
2953: # If we are here, %Keywords is empty, so fill it up
2954: # Make sure the file we need exists...
2955: if (! -e $thesaurus_db_file) {
2956: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2957: " failed because it does not exist");
2958: return 0;
2959: }
2960: # Set up the hash as a database
2961: my %thesaurus_db;
2962: if (! tie(%thesaurus_db,'GDBM_File',
2963: $thesaurus_db_file,&GDBM_READER(),0640)){
2964: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2965: $thesaurus_db_file);
2966: return 0;
2967: }
2968: # Get the average number of appearances of a word.
2969: my $avecount = $thesaurus_db{'average.count'};
2970: # Put keywords (those that appear > average) into %Keywords
2971: while (my ($word,$data)=each (%thesaurus_db)) {
2972: my ($count,undef) = split /:/,$data;
2973: $Keywords{$word}++ if ($count > $avecount);
2974: }
2975: untie %thesaurus_db;
2976: # Remove special values from %Keywords.
2977: foreach my $value ('total.count','average.count') {
2978: delete($Keywords{$value}) if (exists($Keywords{$value}));
2979: }
2980: return 1;
2981: }
2982:
2983: ###################################################
2984:
2985: =pod
2986:
2987: =item * &keyword($word)
2988:
2989: Returns true if $word is a keyword. A keyword is a word that appears more
2990: than the average number of times in the thesaurus database. Calls
2991: &initialize_keywords
2992:
2993: =cut
2994:
2995: ###################################################
2996:
2997: sub keyword {
2998: return if (!&initialize_keywords());
2999: my $word=lc(shift());
3000: $word=~s/\W//g;
3001: return exists($Keywords{$word});
3002: }
3003:
3004: ###############################################################
3005:
3006: =pod
3007:
3008: =item * &get_related_words()
3009:
3010: Look up a word in the thesaurus. Takes a scalar argument and returns
3011: an array of words. If the keyword is not in the thesaurus, an empty array
3012: will be returned. The order of the words returned is determined by the
3013: database which holds them.
3014:
3015: Uses global $thesaurus_db_file.
3016:
3017:
3018: =cut
3019:
3020: ###############################################################
3021: sub get_related_words {
3022: my $keyword = shift;
3023: my %thesaurus_db;
3024: if (! -e $thesaurus_db_file) {
3025: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3026: "failed because the file does not exist");
3027: return ();
3028: }
3029: if (! tie(%thesaurus_db,'GDBM_File',
3030: $thesaurus_db_file,&GDBM_READER(),0640)){
3031: return ();
3032: }
3033: my @Words=();
3034: my $count=0;
3035: if (exists($thesaurus_db{$keyword})) {
3036: # The first element is the number of times
3037: # the word appears. We do not need it now.
3038: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3039: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3040: my $threshold=$mostfrequentcount/10;
3041: foreach my $possibleword (@RelatedWords) {
3042: my ($word,$wordcount)=split(/\,/,$possibleword);
3043: if ($wordcount>$threshold) {
3044: push(@Words,$word);
3045: $count++;
3046: if ($count>10) { last; }
3047: }
3048: }
3049: }
3050: untie %thesaurus_db;
3051: return @Words;
3052: }
3053:
3054: =pod
3055:
3056: =back
3057:
3058: =cut
3059:
3060: # -------------------------------------------------------------- Plaintext name
3061: =pod
3062:
3063: =head1 User Name Functions
3064:
3065: =over 4
3066:
3067: =item * &plainname($uname,$udom,$first)
3068:
3069: Takes a users logon name and returns it as a string in
3070: "first middle last generation" form
3071: if $first is set to 'lastname' then it returns it as
3072: 'lastname generation, firstname middlename' if their is a lastname
3073:
3074: =cut
3075:
3076:
3077: ###############################################################
3078: sub plainname {
3079: my ($uname,$udom,$first)=@_;
3080: return if (!defined($uname) || !defined($udom));
3081: my %names=&getnames($uname,$udom);
3082: my $name=&Apache::lonnet::format_name($names{'firstname'},
3083: $names{'middlename'},
3084: $names{'lastname'},
3085: $names{'generation'},$first);
3086: $name=~s/^\s+//;
3087: $name=~s/\s+$//;
3088: $name=~s/\s+/ /g;
3089: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3090: return $name;
3091: }
3092:
3093: # -------------------------------------------------------------------- Nickname
3094: =pod
3095:
3096: =item * &nickname($uname,$udom)
3097:
3098: Gets a users name and returns it as a string as
3099:
3100: ""nickname""
3101:
3102: if the user has a nickname or
3103:
3104: "first middle last generation"
3105:
3106: if the user does not
3107:
3108: =cut
3109:
3110: sub nickname {
3111: my ($uname,$udom)=@_;
3112: return if (!defined($uname) || !defined($udom));
3113: my %names=&getnames($uname,$udom);
3114: my $name=$names{'nickname'};
3115: if ($name) {
3116: $name='"'.$name.'"';
3117: } else {
3118: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3119: $names{'lastname'}.' '.$names{'generation'};
3120: $name=~s/\s+$//;
3121: $name=~s/\s+/ /g;
3122: }
3123: return $name;
3124: }
3125:
3126: sub getnames {
3127: my ($uname,$udom)=@_;
3128: return if (!defined($uname) || !defined($udom));
3129: if ($udom eq 'public' && $uname eq 'public') {
3130: return ('lastname' => &mt('Public'));
3131: }
3132: my $id=$uname.':'.$udom;
3133: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3134: if ($cached) {
3135: return %{$names};
3136: } else {
3137: my %loadnames=&Apache::lonnet::get('environment',
3138: ['firstname','middlename','lastname','generation','nickname'],
3139: $udom,$uname);
3140: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3141: return %loadnames;
3142: }
3143: }
3144:
3145: # -------------------------------------------------------------------- getemails
3146:
3147: =pod
3148:
3149: =item * &getemails($uname,$udom)
3150:
3151: Gets a user's email information and returns it as a hash with keys:
3152: notification, critnotification, permanentemail
3153:
3154: For notification and critnotification, values are comma-separated lists
3155: of e-mail addresses; for permanentemail, value is a single e-mail address.
3156:
3157:
3158: =cut
3159:
3160:
3161: sub getemails {
3162: my ($uname,$udom)=@_;
3163: if ($udom eq 'public' && $uname eq 'public') {
3164: return;
3165: }
3166: if (!$udom) { $udom=$env{'user.domain'}; }
3167: if (!$uname) { $uname=$env{'user.name'}; }
3168: my $id=$uname.':'.$udom;
3169: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3170: if ($cached) {
3171: return %{$names};
3172: } else {
3173: my %loadnames=&Apache::lonnet::get('environment',
3174: ['notification','critnotification',
3175: 'permanentemail'],
3176: $udom,$uname);
3177: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3178: return %loadnames;
3179: }
3180: }
3181:
3182: sub flush_email_cache {
3183: my ($uname,$udom)=@_;
3184: if (!$udom) { $udom =$env{'user.domain'}; }
3185: if (!$uname) { $uname=$env{'user.name'}; }
3186: return if ($udom eq 'public' && $uname eq 'public');
3187: my $id=$uname.':'.$udom;
3188: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3189: }
3190:
3191: # -------------------------------------------------------------------- getlangs
3192:
3193: =pod
3194:
3195: =item * &getlangs($uname,$udom)
3196:
3197: Gets a user's language preference and returns it as a hash with key:
3198: language.
3199:
3200: =cut
3201:
3202:
3203: sub getlangs {
3204: my ($uname,$udom) = @_;
3205: if (!$udom) { $udom =$env{'user.domain'}; }
3206: if (!$uname) { $uname=$env{'user.name'}; }
3207: my $id=$uname.':'.$udom;
3208: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3209: if ($cached) {
3210: return %{$langs};
3211: } else {
3212: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3213: $udom,$uname);
3214: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3215: return %loadlangs;
3216: }
3217: }
3218:
3219: sub flush_langs_cache {
3220: my ($uname,$udom)=@_;
3221: if (!$udom) { $udom =$env{'user.domain'}; }
3222: if (!$uname) { $uname=$env{'user.name'}; }
3223: return if ($udom eq 'public' && $uname eq 'public');
3224: my $id=$uname.':'.$udom;
3225: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3226: }
3227:
3228: # ------------------------------------------------------------------ Screenname
3229:
3230: =pod
3231:
3232: =item * &screenname($uname,$udom)
3233:
3234: Gets a users screenname and returns it as a string
3235:
3236: =cut
3237:
3238: sub screenname {
3239: my ($uname,$udom)=@_;
3240: if ($uname eq $env{'user.name'} &&
3241: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3242: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3243: return $names{'screenname'};
3244: }
3245:
3246:
3247: # ------------------------------------------------------------- Confirm Wrapper
3248: =pod
3249:
3250: =item * &confirmwrapper($message)
3251:
3252: Wrap messages about completion of operation in box
3253:
3254: =cut
3255:
3256: sub confirmwrapper {
3257: my ($message)=@_;
3258: if ($message) {
3259: return "\n".'<div class="LC_confirm_box">'."\n"
3260: .$message."\n"
3261: .'</div>'."\n";
3262: } else {
3263: return $message;
3264: }
3265: }
3266:
3267: # ------------------------------------------------------------- Message Wrapper
3268:
3269: sub messagewrapper {
3270: my ($link,$username,$domain,$subject,$text)=@_;
3271: return
3272: '<a href="/adm/email?compose=individual&'.
3273: 'recname='.$username.'&recdom='.$domain.
3274: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3275: 'title="'.&mt('Send message').'">'.$link.'</a>';
3276: }
3277:
3278: # --------------------------------------------------------------- Notes Wrapper
3279:
3280: sub noteswrapper {
3281: my ($link,$un,$do)=@_;
3282: return
3283: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3284: }
3285:
3286: # ------------------------------------------------------------- Aboutme Wrapper
3287:
3288: sub aboutmewrapper {
3289: my ($link,$username,$domain,$target,$class)=@_;
3290: if (!defined($username) && !defined($domain)) {
3291: return;
3292: }
3293: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3294: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3295: }
3296:
3297: # ------------------------------------------------------------ Syllabus Wrapper
3298:
3299: sub syllabuswrapper {
3300: my ($linktext,$coursedir,$domain)=@_;
3301: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3302: }
3303:
3304: # -----------------------------------------------------------------------------
3305:
3306: sub track_student_link {
3307: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3308: my $link ="/adm/trackstudent?";
3309: my $title = 'View recent activity';
3310: if (defined($sname) && $sname !~ /^\s*$/ &&
3311: defined($sdom) && $sdom !~ /^\s*$/) {
3312: $link .= "selected_student=$sname:$sdom";
3313: $title .= ' of this student';
3314: }
3315: if (defined($target) && $target !~ /^\s*$/) {
3316: $target = qq{target="$target"};
3317: } else {
3318: $target = '';
3319: }
3320: if ($start) { $link.='&start='.$start; }
3321: if ($only_body) { $link .= '&only_body=1'; }
3322: $title = &mt($title);
3323: $linktext = &mt($linktext);
3324: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3325: &help_open_topic('View_recent_activity');
3326: }
3327:
3328: sub slot_reservations_link {
3329: my ($linktext,$sname,$sdom,$target) = @_;
3330: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3331: my $title = 'View slot reservation history';
3332: if (defined($sname) && $sname !~ /^\s*$/ &&
3333: defined($sdom) && $sdom !~ /^\s*$/) {
3334: $link .= "&uname=$sname&udom=$sdom";
3335: $title .= ' of this student';
3336: }
3337: if (defined($target) && $target !~ /^\s*$/) {
3338: $target = qq{target="$target"};
3339: } else {
3340: $target = '';
3341: }
3342: $title = &mt($title);
3343: $linktext = &mt($linktext);
3344: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3345: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3346:
3347: }
3348:
3349: # ===================================================== Display a student photo
3350:
3351:
3352: sub student_image_tag {
3353: my ($domain,$user)=@_;
3354: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3355: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3356: return '<img src="'.$imgsrc.'" align="right" />';
3357: } else {
3358: return '';
3359: }
3360: }
3361:
3362: =pod
3363:
3364: =back
3365:
3366: =head1 Access .tab File Data
3367:
3368: =over 4
3369:
3370: =item * &languageids()
3371:
3372: returns list of all language ids
3373:
3374: =cut
3375:
3376: sub languageids {
3377: return sort(keys(%language));
3378: }
3379:
3380: =pod
3381:
3382: =item * &languagedescription()
3383:
3384: returns description of a specified language id
3385:
3386: =cut
3387:
3388: sub languagedescription {
3389: my $code=shift;
3390: return ($supported_language{$code}?'* ':'').
3391: $language{$code}.
3392: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3393: }
3394:
3395: =pod
3396:
3397: =item * &plainlanguagedescription
3398:
3399: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3400: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3401:
3402: =cut
3403:
3404: sub plainlanguagedescription {
3405: my $code=shift;
3406: return $language{$code};
3407: }
3408:
3409: =pod
3410:
3411: =item * &supportedlanguagecode
3412:
3413: Returns the supported language code (e.g. sptutf maps to pt) given a language
3414: code.
3415:
3416: =cut
3417:
3418: sub supportedlanguagecode {
3419: my $code=shift;
3420: return $supported_language{$code};
3421: }
3422:
3423: =pod
3424:
3425: =item * &latexlanguage()
3426:
3427: Given a language key code returns the correspondnig language to use
3428: to select the correct hyphenation on LaTeX printouts. This is undef if there
3429: is no supported hyphenation for the language code.
3430:
3431: =cut
3432:
3433: sub latexlanguage {
3434: my $code = shift;
3435: return $latex_language{$code};
3436: }
3437:
3438: =pod
3439:
3440: =item * &latexhyphenation()
3441:
3442: Same as above but what's supplied is the language as it might be stored
3443: in the metadata.
3444:
3445: =cut
3446:
3447: sub latexhyphenation {
3448: my $key = shift;
3449: return $latex_language_bykey{$key};
3450: }
3451:
3452: =pod
3453:
3454: =item * ©rightids()
3455:
3456: returns list of all copyrights
3457:
3458: =cut
3459:
3460: sub copyrightids {
3461: return sort(keys(%cprtag));
3462: }
3463:
3464: =pod
3465:
3466: =item * ©rightdescription()
3467:
3468: returns description of a specified copyright id
3469:
3470: =cut
3471:
3472: sub copyrightdescription {
3473: return &mt($cprtag{shift(@_)});
3474: }
3475:
3476: =pod
3477:
3478: =item * &source_copyrightids()
3479:
3480: returns list of all source copyrights
3481:
3482: =cut
3483:
3484: sub source_copyrightids {
3485: return sort(keys(%scprtag));
3486: }
3487:
3488: =pod
3489:
3490: =item * &source_copyrightdescription()
3491:
3492: returns description of a specified source copyright id
3493:
3494: =cut
3495:
3496: sub source_copyrightdescription {
3497: return &mt($scprtag{shift(@_)});
3498: }
3499:
3500: =pod
3501:
3502: =item * &filecategories()
3503:
3504: returns list of all file categories
3505:
3506: =cut
3507:
3508: sub filecategories {
3509: return sort(keys(%category_extensions));
3510: }
3511:
3512: =pod
3513:
3514: =item * &filecategorytypes()
3515:
3516: returns list of file types belonging to a given file
3517: category
3518:
3519: =cut
3520:
3521: sub filecategorytypes {
3522: my ($cat) = @_;
3523: return @{$category_extensions{lc($cat)}};
3524: }
3525:
3526: =pod
3527:
3528: =item * &fileembstyle()
3529:
3530: returns embedding style for a specified file type
3531:
3532: =cut
3533:
3534: sub fileembstyle {
3535: return $fe{lc(shift(@_))};
3536: }
3537:
3538: sub filemimetype {
3539: return $fm{lc(shift(@_))};
3540: }
3541:
3542:
3543: sub filecategoryselect {
3544: my ($name,$value)=@_;
3545: return &select_form($value,$name,
3546: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3547: }
3548:
3549: =pod
3550:
3551: =item * &filedescription()
3552:
3553: returns description for a specified file type
3554:
3555: =cut
3556:
3557: sub filedescription {
3558: my $file_description = $fd{lc(shift())};
3559: $file_description =~ s:([\[\]]):~$1:g;
3560: return &mt($file_description);
3561: }
3562:
3563: =pod
3564:
3565: =item * &filedescriptionex()
3566:
3567: returns description for a specified file type with
3568: extra formatting
3569:
3570: =cut
3571:
3572: sub filedescriptionex {
3573: my $ex=shift;
3574: my $file_description = $fd{lc($ex)};
3575: $file_description =~ s:([\[\]]):~$1:g;
3576: return '.'.$ex.' '.&mt($file_description);
3577: }
3578:
3579: # End of .tab access
3580: =pod
3581:
3582: =back
3583:
3584: =cut
3585:
3586: # ------------------------------------------------------------------ File Types
3587: sub fileextensions {
3588: return sort(keys(%fe));
3589: }
3590:
3591: # ----------------------------------------------------------- Display Languages
3592: # returns a hash with all desired display languages
3593: #
3594:
3595: sub display_languages {
3596: my %languages=();
3597: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3598: $languages{$lang}=1;
3599: }
3600: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3601: if ($env{'form.displaylanguage'}) {
3602: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3603: $languages{$lang}=1;
3604: }
3605: }
3606: return %languages;
3607: }
3608:
3609: sub languages {
3610: my ($possible_langs) = @_;
3611: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3612: if (!ref($possible_langs)) {
3613: if( wantarray ) {
3614: return @preferred_langs;
3615: } else {
3616: return $preferred_langs[0];
3617: }
3618: }
3619: my %possibilities = map { $_ => 1 } (@$possible_langs);
3620: my @preferred_possibilities;
3621: foreach my $preferred_lang (@preferred_langs) {
3622: if (exists($possibilities{$preferred_lang})) {
3623: push(@preferred_possibilities, $preferred_lang);
3624: }
3625: }
3626: if( wantarray ) {
3627: return @preferred_possibilities;
3628: }
3629: return $preferred_possibilities[0];
3630: }
3631:
3632: sub user_lang {
3633: my ($touname,$toudom,$fromcid) = @_;
3634: my @userlangs;
3635: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3636: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3637: $env{'course.'.$fromcid.'.languages'}));
3638: } else {
3639: my %langhash = &getlangs($touname,$toudom);
3640: if ($langhash{'languages'} ne '') {
3641: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3642: } else {
3643: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3644: if ($domdefs{'lang_def'} ne '') {
3645: @userlangs = ($domdefs{'lang_def'});
3646: }
3647: }
3648: }
3649: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3650: my $user_lh = Apache::localize->get_handle(@languages);
3651: return $user_lh;
3652: }
3653:
3654:
3655: ###############################################################
3656: ## Student Answer Attempts ##
3657: ###############################################################
3658:
3659: =pod
3660:
3661: =head1 Alternate Problem Views
3662:
3663: =over 4
3664:
3665: =item * &get_previous_attempt($symb, $username, $domain, $course,
3666: $getattempt, $regexp, $gradesub)
3667:
3668: Return string with previous attempt on problem. Arguments:
3669:
3670: =over 4
3671:
3672: =item * $symb: Problem, including path
3673:
3674: =item * $username: username of the desired student
3675:
3676: =item * $domain: domain of the desired student
3677:
3678: =item * $course: Course ID
3679:
3680: =item * $getattempt: Leave blank for all attempts, otherwise put
3681: something
3682:
3683: =item * $regexp: if string matches this regexp, the string will be
3684: sent to $gradesub
3685:
3686: =item * $gradesub: routine that processes the string if it matches $regexp
3687:
3688: =back
3689:
3690: The output string is a table containing all desired attempts, if any.
3691:
3692: =cut
3693:
3694: sub get_previous_attempt {
3695: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3696: my $prevattempts='';
3697: no strict 'refs';
3698: if ($symb) {
3699: my (%returnhash)=
3700: &Apache::lonnet::restore($symb,$course,$domain,$username);
3701: if ($returnhash{'version'}) {
3702: my %lasthash=();
3703: my $version;
3704: for ($version=1;$version<=$returnhash{'version'};$version++) {
3705: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3706: $lasthash{$key}=$returnhash{$version.':'.$key};
3707: }
3708: }
3709: $prevattempts=&start_data_table().&start_data_table_header_row();
3710: $prevattempts.='<th>'.&mt('History').'</th>';
3711: my (%typeparts,%lasthidden);
3712: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3713: foreach my $key (sort(keys(%lasthash))) {
3714: my ($ign,@parts) = split(/\./,$key);
3715: if ($#parts > 0) {
3716: my $data=$parts[-1];
3717: next if ($data eq 'foilorder');
3718: pop(@parts);
3719: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3720: if ($data eq 'type') {
3721: unless ($showsurv) {
3722: my $id = join(',',@parts);
3723: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3724: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3725: $lasthidden{$ign.'.'.$id} = 1;
3726: }
3727: }
3728: }
3729: } else {
3730: if ($#parts == 0) {
3731: $prevattempts.='<th>'.$parts[0].'</th>';
3732: } else {
3733: $prevattempts.='<th>'.$ign.'</th>';
3734: }
3735: }
3736: }
3737: $prevattempts.=&end_data_table_header_row();
3738: if ($getattempt eq '') {
3739: for ($version=1;$version<=$returnhash{'version'};$version++) {
3740: my @hidden;
3741: if (%typeparts) {
3742: foreach my $id (keys(%typeparts)) {
3743: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3744: push(@hidden,$id);
3745: }
3746: }
3747: }
3748: $prevattempts.=&start_data_table_row().
3749: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3750: if (@hidden) {
3751: foreach my $key (sort(keys(%lasthash))) {
3752: next if ($key =~ /\.foilorder$/);
3753: my $hide;
3754: foreach my $id (@hidden) {
3755: if ($key =~ /^\Q$id\E/) {
3756: $hide = 1;
3757: last;
3758: }
3759: }
3760: if ($hide) {
3761: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3762: if (($data eq 'award') || ($data eq 'awarddetail')) {
3763: my $value = &format_previous_attempt_value($key,
3764: $returnhash{$version.':'.$key});
3765: $prevattempts.='<td>'.$value.' </td>';
3766: } else {
3767: $prevattempts.='<td> </td>';
3768: }
3769: } else {
3770: if ($key =~ /\./) {
3771: my $value = &format_previous_attempt_value($key,
3772: $returnhash{$version.':'.$key});
3773: $prevattempts.='<td>'.$value.' </td>';
3774: } else {
3775: $prevattempts.='<td> </td>';
3776: }
3777: }
3778: }
3779: } else {
3780: foreach my $key (sort(keys(%lasthash))) {
3781: next if ($key =~ /\.foilorder$/);
3782: my $value = &format_previous_attempt_value($key,
3783: $returnhash{$version.':'.$key});
3784: $prevattempts.='<td>'.$value.' </td>';
3785: }
3786: }
3787: $prevattempts.=&end_data_table_row();
3788: }
3789: }
3790: my @currhidden = keys(%lasthidden);
3791: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3792: foreach my $key (sort(keys(%lasthash))) {
3793: next if ($key =~ /\.foilorder$/);
3794: if (%typeparts) {
3795: my $hidden;
3796: foreach my $id (@currhidden) {
3797: if ($key =~ /^\Q$id\E/) {
3798: $hidden = 1;
3799: last;
3800: }
3801: }
3802: if ($hidden) {
3803: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3804: if (($data eq 'award') || ($data eq 'awarddetail')) {
3805: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3806: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3807: $value = &$gradesub($value);
3808: }
3809: $prevattempts.='<td>'.$value.' </td>';
3810: } else {
3811: $prevattempts.='<td> </td>';
3812: }
3813: } else {
3814: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3815: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3816: $value = &$gradesub($value);
3817: }
3818: $prevattempts.='<td>'.$value.' </td>';
3819: }
3820: } else {
3821: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3822: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3823: $value = &$gradesub($value);
3824: }
3825: $prevattempts.='<td>'.$value.' </td>';
3826: }
3827: }
3828: $prevattempts.= &end_data_table_row().&end_data_table();
3829: } else {
3830: $prevattempts=
3831: &start_data_table().&start_data_table_row().
3832: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3833: &end_data_table_row().&end_data_table();
3834: }
3835: } else {
3836: $prevattempts=
3837: &start_data_table().&start_data_table_row().
3838: '<td>'.&mt('No data.').'</td>'.
3839: &end_data_table_row().&end_data_table();
3840: }
3841: }
3842:
3843: sub format_previous_attempt_value {
3844: my ($key,$value) = @_;
3845: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3846: $value = &Apache::lonlocal::locallocaltime($value);
3847: } elsif (ref($value) eq 'ARRAY') {
3848: $value = '('.join(', ', @{ $value }).')';
3849: } elsif ($key =~ /answerstring$/) {
3850: my %answers = &Apache::lonnet::str2hash($value);
3851: my @anskeys = sort(keys(%answers));
3852: if (@anskeys == 1) {
3853: my $answer = $answers{$anskeys[0]};
3854: if ($answer =~ m{\0}) {
3855: $answer =~ s{\0}{,}g;
3856: }
3857: my $tag_internal_answer_name = 'INTERNAL';
3858: if ($anskeys[0] eq $tag_internal_answer_name) {
3859: $value = $answer;
3860: } else {
3861: $value = $anskeys[0].'='.$answer;
3862: }
3863: } else {
3864: foreach my $ans (@anskeys) {
3865: my $answer = $answers{$ans};
3866: if ($answer =~ m{\0}) {
3867: $answer =~ s{\0}{,}g;
3868: }
3869: $value .= $ans.'='.$answer.'<br />';;
3870: }
3871: }
3872: } else {
3873: $value = &unescape($value);
3874: }
3875: return $value;
3876: }
3877:
3878:
3879: sub relative_to_absolute {
3880: my ($url,$output)=@_;
3881: my $parser=HTML::TokeParser->new(\$output);
3882: my $token;
3883: my $thisdir=$url;
3884: my @rlinks=();
3885: while ($token=$parser->get_token) {
3886: if ($token->[0] eq 'S') {
3887: if ($token->[1] eq 'a') {
3888: if ($token->[2]->{'href'}) {
3889: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3890: }
3891: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3892: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3893: } elsif ($token->[1] eq 'base') {
3894: $thisdir=$token->[2]->{'href'};
3895: }
3896: }
3897: }
3898: $thisdir=~s-/[^/]*$--;
3899: foreach my $link (@rlinks) {
3900: unless (($link=~/^https?\:\/\//i) ||
3901: ($link=~/^\//) ||
3902: ($link=~/^javascript:/i) ||
3903: ($link=~/^mailto:/i) ||
3904: ($link=~/^\#/)) {
3905: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3906: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3907: }
3908: }
3909: # -------------------------------------------------- Deal with Applet codebases
3910: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3911: return $output;
3912: }
3913:
3914: =pod
3915:
3916: =item * &get_student_view()
3917:
3918: show a snapshot of what student was looking at
3919:
3920: =cut
3921:
3922: sub get_student_view {
3923: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3924: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3925: my (%form);
3926: my @elements=('symb','courseid','domain','username');
3927: foreach my $element (@elements) {
3928: $form{'grade_'.$element}=eval '$'.$element #'
3929: }
3930: if (defined($moreenv)) {
3931: %form=(%form,%{$moreenv});
3932: }
3933: if (defined($target)) { $form{'grade_target'} = $target; }
3934: $feedurl=&Apache::lonnet::clutter($feedurl);
3935: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3936: $userview=~s/\<body[^\>]*\>//gi;
3937: $userview=~s/\<\/body\>//gi;
3938: $userview=~s/\<html\>//gi;
3939: $userview=~s/\<\/html\>//gi;
3940: $userview=~s/\<head\>//gi;
3941: $userview=~s/\<\/head\>//gi;
3942: $userview=~s/action\s*\=/would_be_action\=/gi;
3943: $userview=&relative_to_absolute($feedurl,$userview);
3944: if (wantarray) {
3945: return ($userview,$response);
3946: } else {
3947: return $userview;
3948: }
3949: }
3950:
3951: sub get_student_view_with_retries {
3952: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3953:
3954: my $ok = 0; # True if we got a good response.
3955: my $content;
3956: my $response;
3957:
3958: # Try to get the student_view done. within the retries count:
3959:
3960: do {
3961: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3962: $ok = $response->is_success;
3963: if (!$ok) {
3964: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3965: }
3966: $retries--;
3967: } while (!$ok && ($retries > 0));
3968:
3969: if (!$ok) {
3970: $content = ''; # On error return an empty content.
3971: }
3972: if (wantarray) {
3973: return ($content, $response);
3974: } else {
3975: return $content;
3976: }
3977: }
3978:
3979: =pod
3980:
3981: =item * &get_student_answers()
3982:
3983: show a snapshot of how student was answering problem
3984:
3985: =cut
3986:
3987: sub get_student_answers {
3988: my ($symb,$username,$domain,$courseid,%form) = @_;
3989: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3990: my (%moreenv);
3991: my @elements=('symb','courseid','domain','username');
3992: foreach my $element (@elements) {
3993: $moreenv{'grade_'.$element}=eval '$'.$element #'
3994: }
3995: $moreenv{'grade_target'}='answer';
3996: %moreenv=(%form,%moreenv);
3997: $feedurl = &Apache::lonnet::clutter($feedurl);
3998: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3999: return $userview;
4000: }
4001:
4002: =pod
4003:
4004: =item * &submlink()
4005:
4006: Inputs: $text $uname $udom $symb $target
4007:
4008: Returns: A link to grades.pm such as to see the SUBM view of a student
4009:
4010: =cut
4011:
4012: ###############################################
4013: sub submlink {
4014: my ($text,$uname,$udom,$symb,$target)=@_;
4015: if (!($uname && $udom)) {
4016: (my $cursymb, my $courseid,$udom,$uname)=
4017: &Apache::lonnet::whichuser($symb);
4018: if (!$symb) { $symb=$cursymb; }
4019: }
4020: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4021: $symb=&escape($symb);
4022: if ($target) { $target=" target=\"$target\""; }
4023: return
4024: '<a href="/adm/grades?command=submission'.
4025: '&symb='.$symb.
4026: '&student='.$uname.
4027: '&userdom='.$udom.'"'.
4028: $target.'>'.$text.'</a>';
4029: }
4030: ##############################################
4031:
4032: =pod
4033:
4034: =item * &pgrdlink()
4035:
4036: Inputs: $text $uname $udom $symb $target
4037:
4038: Returns: A link to grades.pm such as to see the PGRD view of a student
4039:
4040: =cut
4041:
4042: ###############################################
4043: sub pgrdlink {
4044: my $link=&submlink(@_);
4045: $link=~s/(&command=submission)/$1&showgrading=yes/;
4046: return $link;
4047: }
4048: ##############################################
4049:
4050: =pod
4051:
4052: =item * &pprmlink()
4053:
4054: Inputs: $text $uname $udom $symb $target
4055:
4056: Returns: A link to parmset.pm such as to see the PPRM view of a
4057: student and a specific resource
4058:
4059: =cut
4060:
4061: ###############################################
4062: sub pprmlink {
4063: my ($text,$uname,$udom,$symb,$target)=@_;
4064: if (!($uname && $udom)) {
4065: (my $cursymb, my $courseid,$udom,$uname)=
4066: &Apache::lonnet::whichuser($symb);
4067: if (!$symb) { $symb=$cursymb; }
4068: }
4069: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4070: $symb=&escape($symb);
4071: if ($target) { $target="target=\"$target\""; }
4072: return '<a href="/adm/parmset?command=set&'.
4073: 'symb='.$symb.'&uname='.$uname.
4074: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4075: }
4076: ##############################################
4077:
4078: =pod
4079:
4080: =back
4081:
4082: =cut
4083:
4084: ###############################################
4085:
4086:
4087: sub timehash {
4088: my ($thistime) = @_;
4089: my $timezone = &Apache::lonlocal::gettimezone();
4090: my $dt = DateTime->from_epoch(epoch => $thistime)
4091: ->set_time_zone($timezone);
4092: my $wday = $dt->day_of_week();
4093: if ($wday == 7) { $wday = 0; }
4094: return ( 'second' => $dt->second(),
4095: 'minute' => $dt->minute(),
4096: 'hour' => $dt->hour(),
4097: 'day' => $dt->day_of_month(),
4098: 'month' => $dt->month(),
4099: 'year' => $dt->year(),
4100: 'weekday' => $wday,
4101: 'dayyear' => $dt->day_of_year(),
4102: 'dlsav' => $dt->is_dst() );
4103: }
4104:
4105: sub utc_string {
4106: my ($date)=@_;
4107: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4108: }
4109:
4110: sub maketime {
4111: my %th=@_;
4112: my ($epoch_time,$timezone,$dt);
4113: $timezone = &Apache::lonlocal::gettimezone();
4114: eval {
4115: $dt = DateTime->new( year => $th{'year'},
4116: month => $th{'month'},
4117: day => $th{'day'},
4118: hour => $th{'hour'},
4119: minute => $th{'minute'},
4120: second => $th{'second'},
4121: time_zone => $timezone,
4122: );
4123: };
4124: if (!$@) {
4125: $epoch_time = $dt->epoch;
4126: if ($epoch_time) {
4127: return $epoch_time;
4128: }
4129: }
4130: return POSIX::mktime(
4131: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4132: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4133: }
4134:
4135: #########################################
4136:
4137: sub findallcourses {
4138: my ($roles,$uname,$udom) = @_;
4139: my %roles;
4140: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4141: my %courses;
4142: my $now=time;
4143: if (!defined($uname)) {
4144: $uname = $env{'user.name'};
4145: }
4146: if (!defined($udom)) {
4147: $udom = $env{'user.domain'};
4148: }
4149: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4150: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4151: if (!%roles) {
4152: %roles = (
4153: cc => 1,
4154: co => 1,
4155: in => 1,
4156: ep => 1,
4157: ta => 1,
4158: cr => 1,
4159: st => 1,
4160: );
4161: }
4162: foreach my $entry (keys(%roleshash)) {
4163: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4164: if ($trole =~ /^cr/) {
4165: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4166: } else {
4167: next if (!exists($roles{$trole}));
4168: }
4169: if ($tend) {
4170: next if ($tend < $now);
4171: }
4172: if ($tstart) {
4173: next if ($tstart > $now);
4174: }
4175: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4176: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4177: my $value = $trole.'/'.$cdom.'/';
4178: if ($secpart eq '') {
4179: ($cnum,$role) = split(/_/,$cnumpart);
4180: $sec = 'none';
4181: $value .= $cnum.'/';
4182: } else {
4183: $cnum = $cnumpart;
4184: ($sec,$role) = split(/_/,$secpart);
4185: $value .= $cnum.'/'.$sec;
4186: }
4187: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4188: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4189: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4190: }
4191: } else {
4192: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4193: }
4194: }
4195: } else {
4196: foreach my $key (keys(%env)) {
4197: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4198: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4199: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4200: next if ($role eq 'ca' || $role eq 'aa');
4201: next if (%roles && !exists($roles{$role}));
4202: my ($starttime,$endtime)=split(/\./,$env{$key});
4203: my $active=1;
4204: if ($starttime) {
4205: if ($now<$starttime) { $active=0; }
4206: }
4207: if ($endtime) {
4208: if ($now>$endtime) { $active=0; }
4209: }
4210: if ($active) {
4211: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4212: if ($sec eq '') {
4213: $sec = 'none';
4214: } else {
4215: $value .= $sec;
4216: }
4217: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4218: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4219: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4220: }
4221: } else {
4222: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4223: }
4224: }
4225: }
4226: }
4227: }
4228: return %courses;
4229: }
4230:
4231: ###############################################
4232:
4233: sub blockcheck {
4234: my ($setters,$activity,$uname,$udom,$url) = @_;
4235:
4236: if (!defined($udom)) {
4237: $udom = $env{'user.domain'};
4238: }
4239: if (!defined($uname)) {
4240: $uname = $env{'user.name'};
4241: }
4242:
4243: # If uname and udom are for a course, check for blocks in the course.
4244:
4245: if (&Apache::lonnet::is_course($udom,$uname)) {
4246: my ($startblock,$endblock,$triggerblock) =
4247: &get_blocks($setters,$activity,$udom,$uname,$url);
4248: return ($startblock,$endblock,$triggerblock);
4249: }
4250:
4251: my $startblock = 0;
4252: my $endblock = 0;
4253: my $triggerblock = '';
4254: my %live_courses = &findallcourses(undef,$uname,$udom);
4255:
4256: # If uname is for a user, and activity is course-specific, i.e.,
4257: # boards, chat or groups, check for blocking in current course only.
4258:
4259: if (($activity eq 'boards' || $activity eq 'chat' ||
4260: $activity eq 'groups') && ($env{'request.course.id'})) {
4261: foreach my $key (keys(%live_courses)) {
4262: if ($key ne $env{'request.course.id'}) {
4263: delete($live_courses{$key});
4264: }
4265: }
4266: }
4267:
4268: my $otheruser = 0;
4269: my %own_courses;
4270: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4271: # Resource belongs to user other than current user.
4272: $otheruser = 1;
4273: # Gather courses for current user
4274: %own_courses =
4275: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4276: }
4277:
4278: # Gather active course roles - course coordinator, instructor,
4279: # exam proctor, ta, student, or custom role.
4280:
4281: foreach my $course (keys(%live_courses)) {
4282: my ($cdom,$cnum);
4283: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4284: $cdom = $env{'course.'.$course.'.domain'};
4285: $cnum = $env{'course.'.$course.'.num'};
4286: } else {
4287: ($cdom,$cnum) = split(/_/,$course);
4288: }
4289: my $no_ownblock = 0;
4290: my $no_userblock = 0;
4291: if ($otheruser && $activity ne 'com') {
4292: # Check if current user has 'evb' priv for this
4293: if (defined($own_courses{$course})) {
4294: foreach my $sec (keys(%{$own_courses{$course}})) {
4295: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4296: if ($sec ne 'none') {
4297: $checkrole .= '/'.$sec;
4298: }
4299: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4300: $no_ownblock = 1;
4301: last;
4302: }
4303: }
4304: }
4305: # if they have 'evb' priv and are currently not playing student
4306: next if (($no_ownblock) &&
4307: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4308: }
4309: foreach my $sec (keys(%{$live_courses{$course}})) {
4310: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4311: if ($sec ne 'none') {
4312: $checkrole .= '/'.$sec;
4313: }
4314: if ($otheruser) {
4315: # Resource belongs to user other than current user.
4316: # Assemble privs for that user, and check for 'evb' priv.
4317: my (%allroles,%userroles);
4318: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4319: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4320: my ($trole,$tdom,$tnum,$tsec);
4321: if ($entry =~ /^cr/) {
4322: ($trole,$tdom,$tnum,$tsec) =
4323: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4324: } else {
4325: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4326: }
4327: my ($spec,$area,$trest);
4328: $area = '/'.$tdom.'/'.$tnum;
4329: $trest = $tnum;
4330: if ($tsec ne '') {
4331: $area .= '/'.$tsec;
4332: $trest .= '/'.$tsec;
4333: }
4334: $spec = $trole.'.'.$area;
4335: if ($trole =~ /^cr/) {
4336: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4337: $tdom,$spec,$trest,$area);
4338: } else {
4339: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4340: $tdom,$spec,$trest,$area);
4341: }
4342: }
4343: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4344: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4345: if ($1) {
4346: $no_userblock = 1;
4347: last;
4348: }
4349: }
4350: }
4351: } else {
4352: # Resource belongs to current user
4353: # Check for 'evb' priv via lonnet::allowed().
4354: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4355: $no_ownblock = 1;
4356: last;
4357: }
4358: }
4359: }
4360: # if they have the evb priv and are currently not playing student
4361: next if (($no_ownblock) &&
4362: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4363: next if ($no_userblock);
4364:
4365: # Retrieve blocking times and identity of locker for course
4366: # of specified user, unless user has 'evb' privilege.
4367:
4368: my ($start,$end,$trigger) =
4369: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4370: if (($start != 0) &&
4371: (($startblock == 0) || ($startblock > $start))) {
4372: $startblock = $start;
4373: if ($trigger ne '') {
4374: $triggerblock = $trigger;
4375: }
4376: }
4377: if (($end != 0) &&
4378: (($endblock == 0) || ($endblock < $end))) {
4379: $endblock = $end;
4380: if ($trigger ne '') {
4381: $triggerblock = $trigger;
4382: }
4383: }
4384: }
4385: return ($startblock,$endblock,$triggerblock);
4386: }
4387:
4388: sub get_blocks {
4389: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4390: my $startblock = 0;
4391: my $endblock = 0;
4392: my $triggerblock = '';
4393: my $course = $cdom.'_'.$cnum;
4394: $setters->{$course} = {};
4395: $setters->{$course}{'staff'} = [];
4396: $setters->{$course}{'times'} = [];
4397: $setters->{$course}{'triggers'} = [];
4398: my (@blockers,%triggered);
4399: my $now = time;
4400: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4401: if ($activity eq 'docs') {
4402: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4403: foreach my $block (@blockers) {
4404: if ($block =~ /^firstaccess____(.+)$/) {
4405: my $item = $1;
4406: my $type = 'map';
4407: my $timersymb = $item;
4408: if ($item eq 'course') {
4409: $type = 'course';
4410: } elsif ($item =~ /___\d+___/) {
4411: $type = 'resource';
4412: } else {
4413: $timersymb = &Apache::lonnet::symbread($item);
4414: }
4415: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4416: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4417: $triggered{$block} = {
4418: start => $start,
4419: end => $end,
4420: type => $type,
4421: };
4422: }
4423: }
4424: } else {
4425: foreach my $block (keys(%commblocks)) {
4426: if ($block =~ m/^(\d+)____(\d+)$/) {
4427: my ($start,$end) = ($1,$2);
4428: if ($start <= time && $end >= time) {
4429: if (ref($commblocks{$block}) eq 'HASH') {
4430: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4431: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4432: unless(grep(/^\Q$block\E$/,@blockers)) {
4433: push(@blockers,$block);
4434: }
4435: }
4436: }
4437: }
4438: }
4439: } elsif ($block =~ /^firstaccess____(.+)$/) {
4440: my $item = $1;
4441: my $timersymb = $item;
4442: my $type = 'map';
4443: if ($item eq 'course') {
4444: $type = 'course';
4445: } elsif ($item =~ /___\d+___/) {
4446: $type = 'resource';
4447: } else {
4448: $timersymb = &Apache::lonnet::symbread($item);
4449: }
4450: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4451: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4452: if ($start && $end) {
4453: if (($start <= time) && ($end >= time)) {
4454: unless (grep(/^\Q$block\E$/,@blockers)) {
4455: push(@blockers,$block);
4456: $triggered{$block} = {
4457: start => $start,
4458: end => $end,
4459: type => $type,
4460: };
4461: }
4462: }
4463: }
4464: }
4465: }
4466: }
4467: foreach my $blocker (@blockers) {
4468: my ($staff_name,$staff_dom,$title,$blocks) =
4469: &parse_block_record($commblocks{$blocker});
4470: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4471: my ($start,$end,$triggertype);
4472: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4473: ($start,$end) = ($1,$2);
4474: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4475: $start = $triggered{$blocker}{'start'};
4476: $end = $triggered{$blocker}{'end'};
4477: $triggertype = $triggered{$blocker}{'type'};
4478: }
4479: if ($start) {
4480: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4481: if ($triggertype) {
4482: push(@{$$setters{$course}{'triggers'}},$triggertype);
4483: } else {
4484: push(@{$$setters{$course}{'triggers'}},0);
4485: }
4486: if ( ($startblock == 0) || ($startblock > $start) ) {
4487: $startblock = $start;
4488: if ($triggertype) {
4489: $triggerblock = $blocker;
4490: }
4491: }
4492: if ( ($endblock == 0) || ($endblock < $end) ) {
4493: $endblock = $end;
4494: if ($triggertype) {
4495: $triggerblock = $blocker;
4496: }
4497: }
4498: }
4499: }
4500: return ($startblock,$endblock,$triggerblock);
4501: }
4502:
4503: sub parse_block_record {
4504: my ($record) = @_;
4505: my ($setuname,$setudom,$title,$blocks);
4506: if (ref($record) eq 'HASH') {
4507: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4508: $title = &unescape($record->{'event'});
4509: $blocks = $record->{'blocks'};
4510: } else {
4511: my @data = split(/:/,$record,3);
4512: if (scalar(@data) eq 2) {
4513: $title = $data[1];
4514: ($setuname,$setudom) = split(/@/,$data[0]);
4515: } else {
4516: ($setuname,$setudom,$title) = @data;
4517: }
4518: $blocks = { 'com' => 'on' };
4519: }
4520: return ($setuname,$setudom,$title,$blocks);
4521: }
4522:
4523: sub blocking_status {
4524: my ($activity,$uname,$udom,$url) = @_;
4525: my %setters;
4526:
4527: # check for active blocking
4528: my ($startblock,$endblock,$triggerblock) =
4529: &blockcheck(\%setters,$activity,$uname,$udom,$url);
4530: my $blocked = 0;
4531: if ($startblock && $endblock) {
4532: $blocked = 1;
4533: }
4534:
4535: # caller just wants to know whether a block is active
4536: if (!wantarray) { return $blocked; }
4537:
4538: # build a link to a popup window containing the details
4539: my $querystring = "?activity=$activity";
4540: # $uname and $udom decide whose portfolio the user is trying to look at
4541: if ($activity eq 'port') {
4542: $querystring .= "&udom=$udom" if $udom;
4543: $querystring .= "&uname=$uname" if $uname;
4544: } elsif ($activity eq 'docs') {
4545: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4546: }
4547:
4548: my $output .= <<'END_MYBLOCK';
4549: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4550: var options = "width=" + w + ",height=" + h + ",";
4551: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4552: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4553: var newWin = window.open(url, wdwName, options);
4554: newWin.focus();
4555: }
4556: END_MYBLOCK
4557:
4558: $output = Apache::lonhtmlcommon::scripttag($output);
4559:
4560: my $popupUrl = "/adm/blockingstatus/$querystring";
4561: my $text = &mt('Communication Blocked');
4562: if ($activity eq 'docs') {
4563: $text = &mt('Content Access Blocked');
4564: } elsif ($activity eq 'printout') {
4565: $text = &mt('Printing Blocked');
4566: }
4567: $output .= <<"END_BLOCK";
4568: <div class='LC_comblock'>
4569: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4570: title='$text'>
4571: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4572: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4573: title='$text'>$text</a>
4574: </div>
4575:
4576: END_BLOCK
4577:
4578: return ($blocked, $output);
4579: }
4580:
4581: ###############################################
4582:
4583: sub check_ip_acc {
4584: my ($acc)=@_;
4585: &Apache::lonxml::debug("acc is $acc");
4586: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4587: return 1;
4588: }
4589: my $allowed=0;
4590: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4591:
4592: my $name;
4593: foreach my $pattern (split(',',$acc)) {
4594: $pattern =~ s/^\s*//;
4595: $pattern =~ s/\s*$//;
4596: if ($pattern =~ /\*$/) {
4597: #35.8.*
4598: $pattern=~s/\*//;
4599: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4600: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4601: #35.8.3.[34-56]
4602: my $low=$2;
4603: my $high=$3;
4604: $pattern=$1;
4605: if ($ip =~ /^\Q$pattern\E/) {
4606: my $last=(split(/\./,$ip))[3];
4607: if ($last <=$high && $last >=$low) { $allowed=1; }
4608: }
4609: } elsif ($pattern =~ /^\*/) {
4610: #*.msu.edu
4611: $pattern=~s/\*//;
4612: if (!defined($name)) {
4613: use Socket;
4614: my $netaddr=inet_aton($ip);
4615: ($name)=gethostbyaddr($netaddr,AF_INET);
4616: }
4617: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4618: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4619: #127.0.0.1
4620: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4621: } else {
4622: #some.name.com
4623: if (!defined($name)) {
4624: use Socket;
4625: my $netaddr=inet_aton($ip);
4626: ($name)=gethostbyaddr($netaddr,AF_INET);
4627: }
4628: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4629: }
4630: if ($allowed) { last; }
4631: }
4632: return $allowed;
4633: }
4634:
4635: ###############################################
4636:
4637: =pod
4638:
4639: =head1 Domain Template Functions
4640:
4641: =over 4
4642:
4643: =item * &determinedomain()
4644:
4645: Inputs: $domain (usually will be undef)
4646:
4647: Returns: Determines which domain should be used for designs
4648:
4649: =cut
4650:
4651: ###############################################
4652: sub determinedomain {
4653: my $domain=shift;
4654: if (! $domain) {
4655: # Determine domain if we have not been given one
4656: $domain = &Apache::lonnet::default_login_domain();
4657: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4658: if ($env{'request.role.domain'}) {
4659: $domain=$env{'request.role.domain'};
4660: }
4661: }
4662: return $domain;
4663: }
4664: ###############################################
4665:
4666: sub devalidate_domconfig_cache {
4667: my ($udom)=@_;
4668: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4669: }
4670:
4671: # ---------------------- Get domain configuration for a domain
4672: sub get_domainconf {
4673: my ($udom) = @_;
4674: my $cachetime=1800;
4675: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4676: if (defined($cached)) { return %{$result}; }
4677:
4678: my %domconfig = &Apache::lonnet::get_dom('configuration',
4679: ['login','rolecolors','autoenroll'],$udom);
4680: my (%designhash,%legacy);
4681: if (keys(%domconfig) > 0) {
4682: if (ref($domconfig{'login'}) eq 'HASH') {
4683: if (keys(%{$domconfig{'login'}})) {
4684: foreach my $key (keys(%{$domconfig{'login'}})) {
4685: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4686: if ($key eq 'loginvia') {
4687: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4688: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4689: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4690: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4691: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4692: $designhash{$udom.'.login.loginvia'} = $server;
4693: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4694:
4695: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4696: } else {
4697: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4698: }
4699: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4700: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4701: }
4702: }
4703: }
4704: }
4705: }
4706: } else {
4707: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4708: $designhash{$udom.'.login.'.$key.'_'.$img} =
4709: $domconfig{'login'}{$key}{$img};
4710: }
4711: }
4712: } else {
4713: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4714: }
4715: }
4716: } else {
4717: $legacy{'login'} = 1;
4718: }
4719: } else {
4720: $legacy{'login'} = 1;
4721: }
4722: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4723: if (keys(%{$domconfig{'rolecolors'}})) {
4724: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4725: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4726: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4727: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4728: }
4729: }
4730: }
4731: } else {
4732: $legacy{'rolecolors'} = 1;
4733: }
4734: } else {
4735: $legacy{'rolecolors'} = 1;
4736: }
4737: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4738: if ($domconfig{'autoenroll'}{'co-owners'}) {
4739: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4740: }
4741: }
4742: if (keys(%legacy) > 0) {
4743: my %legacyhash = &get_legacy_domconf($udom);
4744: foreach my $item (keys(%legacyhash)) {
4745: if ($item =~ /^\Q$udom\E\.login/) {
4746: if ($legacy{'login'}) {
4747: $designhash{$item} = $legacyhash{$item};
4748: }
4749: } else {
4750: if ($legacy{'rolecolors'}) {
4751: $designhash{$item} = $legacyhash{$item};
4752: }
4753: }
4754: }
4755: }
4756: } else {
4757: %designhash = &get_legacy_domconf($udom);
4758: }
4759: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4760: $cachetime);
4761: return %designhash;
4762: }
4763:
4764: sub get_legacy_domconf {
4765: my ($udom) = @_;
4766: my %legacyhash;
4767: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4768: my $designfile = $designdir.'/'.$udom.'.tab';
4769: if (-e $designfile) {
4770: if ( open (my $fh,"<$designfile") ) {
4771: while (my $line = <$fh>) {
4772: next if ($line =~ /^\#/);
4773: chomp($line);
4774: my ($key,$val)=(split(/\=/,$line));
4775: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4776: }
4777: close($fh);
4778: }
4779: }
4780: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4781: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4782: }
4783: return %legacyhash;
4784: }
4785:
4786: =pod
4787:
4788: =item * &domainlogo()
4789:
4790: Inputs: $domain (usually will be undef)
4791:
4792: Returns: A link to a domain logo, if the domain logo exists.
4793: If the domain logo does not exist, a description of the domain.
4794:
4795: =cut
4796:
4797: ###############################################
4798: sub domainlogo {
4799: my $domain = &determinedomain(shift);
4800: my %designhash = &get_domainconf($domain);
4801: # See if there is a logo
4802: if ($designhash{$domain.'.login.domlogo'} ne '') {
4803: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4804: if ($imgsrc =~ m{^/(adm|res)/}) {
4805: if ($imgsrc =~ m{^/res/}) {
4806: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4807: &Apache::lonnet::repcopy($local_name);
4808: }
4809: $imgsrc = &lonhttpdurl($imgsrc);
4810: }
4811: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4812: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4813: return &Apache::lonnet::domain($domain,'description');
4814: } else {
4815: return '';
4816: }
4817: }
4818: ##############################################
4819:
4820: =pod
4821:
4822: =item * &designparm()
4823:
4824: Inputs: $which parameter; $domain (usually will be undef)
4825:
4826: Returns: value of designparamter $which
4827:
4828: =cut
4829:
4830:
4831: ##############################################
4832: sub designparm {
4833: my ($which,$domain)=@_;
4834: if (exists($env{'environment.color.'.$which})) {
4835: return $env{'environment.color.'.$which};
4836: }
4837: $domain=&determinedomain($domain);
4838: my %domdesign;
4839: unless ($domain eq 'public') {
4840: %domdesign = &get_domainconf($domain);
4841: }
4842: my $output;
4843: if ($domdesign{$domain.'.'.$which} ne '') {
4844: $output = $domdesign{$domain.'.'.$which};
4845: } else {
4846: $output = $defaultdesign{$which};
4847: }
4848: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4849: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4850: if ($output =~ m{^/(adm|res)/}) {
4851: if ($output =~ m{^/res/}) {
4852: my $local_name = &Apache::lonnet::filelocation('',$output);
4853: &Apache::lonnet::repcopy($local_name);
4854: }
4855: $output = &lonhttpdurl($output);
4856: }
4857: }
4858: return $output;
4859: }
4860:
4861: ##############################################
4862: =pod
4863:
4864: =item * &authorspace()
4865:
4866: Inputs: $url (usually will be undef).
4867:
4868: Returns: Path to Authoring Space containing the resource or
4869: directory being viewed (or for which action is being taken).
4870: If $url is provided, and begins /priv/<domain>/<uname>
4871: the path will be that portion of the $context argument.
4872: Otherwise the path will be for the author space of the current
4873: user when the current role is author, or for that of the
4874: co-author/assistant co-author space when the current role
4875: is co-author or assistant co-author.
4876:
4877: =cut
4878:
4879: sub authorspace {
4880: my ($url) = @_;
4881: if ($url ne '') {
4882: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4883: return $1;
4884: }
4885: }
4886: my $caname = '';
4887: my $cadom = '';
4888: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4889: ($cadom,$caname) =
4890: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4891: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4892: $caname = $env{'user.name'};
4893: $cadom = $env{'user.domain'};
4894: }
4895: if (($caname ne '') && ($cadom ne '')) {
4896: return "/priv/$cadom/$caname/";
4897: }
4898: return;
4899: }
4900:
4901: ##############################################
4902: =pod
4903:
4904: =item * &head_subbox()
4905:
4906: Inputs: $content (contains HTML code with page functions, etc.)
4907:
4908: Returns: HTML div with $content
4909: To be included in page header
4910:
4911: =cut
4912:
4913: sub head_subbox {
4914: my ($content)=@_;
4915: my $output =
4916: '<div class="LC_head_subbox">'
4917: .$content
4918: .'</div>'
4919: }
4920:
4921: ##############################################
4922: =pod
4923:
4924: =item * &CSTR_pageheader()
4925:
4926: Input: (optional) filename from which breadcrumb trail is built.
4927: In most cases no input as needed, as $env{'request.filename'}
4928: is appropriate for use in building the breadcrumb trail.
4929:
4930: Returns: HTML div with CSTR path and recent box
4931: To be included on Authoring Space pages
4932:
4933: =cut
4934:
4935: sub CSTR_pageheader {
4936: my ($trailfile) = @_;
4937: if ($trailfile eq '') {
4938: $trailfile = $env{'request.filename'};
4939: }
4940:
4941: # this is for resources; directories have customtitle, and crumbs
4942: # and select recent are created in lonpubdir.pm
4943:
4944: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
4945: my ($udom,$uname,$thisdisfn)=
4946: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
4947: my $formaction = "/priv/$udom/$uname/$thisdisfn";
4948: $formaction =~ s{/+}{/}g;
4949:
4950: my $parentpath = '';
4951: my $lastitem = '';
4952: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4953: $parentpath = $1;
4954: $lastitem = $2;
4955: } else {
4956: $lastitem = $thisdisfn;
4957: }
4958:
4959: my $output =
4960: '<div>'
4961: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
4962: .'<b>'.&mt('Authoring Space:').'</b> '
4963: .'<form name="dirs" method="post" action="'.$formaction
4964: .'" target="_top">' #FIXME lonpubdir: target="_parent"
4965: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
4966:
4967: if ($lastitem) {
4968: $output .=
4969: '<span class="LC_filename">'
4970: .$lastitem
4971: .'</span>';
4972: }
4973: $output .=
4974: '<br />'
4975: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
4976: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4977: .'</form>'
4978: .&Apache::lonmenu::constspaceform()
4979: .'</div>';
4980:
4981: return $output;
4982: }
4983:
4984: ###############################################
4985: ###############################################
4986:
4987: =pod
4988:
4989: =back
4990:
4991: =head1 HTML Helpers
4992:
4993: =over 4
4994:
4995: =item * &bodytag()
4996:
4997: Returns a uniform header for LON-CAPA web pages.
4998:
4999: Inputs:
5000:
5001: =over 4
5002:
5003: =item * $title, A title to be displayed on the page.
5004:
5005: =item * $function, the current role (can be undef).
5006:
5007: =item * $addentries, extra parameters for the <body> tag.
5008:
5009: =item * $bodyonly, if defined, only return the <body> tag.
5010:
5011: =item * $domain, if defined, force a given domain.
5012:
5013: =item * $forcereg, if page should register as content page (relevant for
5014: text interface only)
5015:
5016: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5017: navigational links
5018:
5019: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5020:
5021: =item * $no_inline_link, if true and in remote mode, don't show the
5022: 'Switch To Inline Menu' link
5023:
5024: =item * $args, optional argument valid values are
5025: no_auto_mt_title -> prevents &mt()ing the title arg
5026: inherit_jsmath -> when creating popup window in a page,
5027: should it have jsmath forced on by the
5028: current page
5029:
5030: =item * $advtoolsref, optional argument, ref to an array containing
5031: inlineremote items to be added in "Functions" menu below
5032: breadcrumbs.
5033:
5034: =back
5035:
5036: Returns: A uniform header for LON-CAPA web pages.
5037: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5038: If $bodyonly is undef or zero, an html string containing a <body> tag and
5039: other decorations will be returned.
5040:
5041: =cut
5042:
5043: sub bodytag {
5044: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5045: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
5046:
5047: my $public;
5048: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5049: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5050: $public = 1;
5051: }
5052: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5053: my $httphost = $args->{'use_absolute'};
5054:
5055: $function = &get_users_function() if (!$function);
5056: my $img = &designparm($function.'.img',$domain);
5057: my $font = &designparm($function.'.font',$domain);
5058: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5059:
5060: my %design = ( 'style' => 'margin-top: 0',
5061: 'bgcolor' => $pgbg,
5062: 'text' => $font,
5063: 'alink' => &designparm($function.'.alink',$domain),
5064: 'vlink' => &designparm($function.'.vlink',$domain),
5065: 'link' => &designparm($function.'.link',$domain),);
5066: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5067:
5068: # role and realm
5069: my ($role,$realm) = split(/\./,$env{'request.role'},2);
5070: if ($role eq 'ca') {
5071: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5072: $realm = &plainname($rname,$rdom);
5073: }
5074: # realm
5075: if ($env{'request.course.id'}) {
5076: if ($env{'request.role'} !~ /^cr/) {
5077: $role = &Apache::lonnet::plaintext($role,&course_type());
5078: }
5079: if ($env{'request.course.sec'}) {
5080: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5081: }
5082: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5083: } else {
5084: $role = &Apache::lonnet::plaintext($role);
5085: }
5086:
5087: if (!$realm) { $realm=' '; }
5088:
5089: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5090:
5091: # construct main body tag
5092: my $bodytag = "<body $extra_body_attr>".
5093: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
5094:
5095: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5096:
5097: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5098: return $bodytag;
5099: }
5100:
5101: if ($public) {
5102: undef($role);
5103: }
5104:
5105: my $titleinfo = '<h1>'.$title.'</h1>';
5106: #
5107: # Extra info if you are the DC
5108: my $dc_info = '';
5109: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5110: $env{'course.'.$env{'request.course.id'}.
5111: '.domain'}.'/'})) {
5112: my $cid = $env{'request.course.id'};
5113: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5114: $dc_info =~ s/\s+$//;
5115: }
5116:
5117: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
5118:
5119: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5120:
5121:
5122:
5123: my $funclist;
5124: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
5125: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
5126: Apache::lonmenu::serverform();
5127: my $forbodytag;
5128: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5129: $forcereg,$args->{'group'},
5130: $args->{'bread_crumbs'},
5131: $advtoolsref,'',\$forbodytag);
5132: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5133: $funclist = $forbodytag;
5134: }
5135: } else {
5136:
5137: # if ($env{'request.state'} eq 'construct') {
5138: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5139: # }
5140:
5141: $bodytag .= Apache::lonhtmlcommon::scripttag(
5142: Apache::lonmenu::utilityfunctions($httphost), 'start');
5143:
5144: my ($left,$right) = Apache::lonmenu::primary_menu();
5145:
5146: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5147: if ($dc_info) {
5148: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5149: }
5150: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5151: <em>$realm</em> $dc_info</div>|;
5152: return $bodytag;
5153: }
5154:
5155: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5156: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5157: }
5158:
5159: $bodytag .= $right;
5160:
5161: if ($dc_info) {
5162: $dc_info = &dc_courseid_toggle($dc_info);
5163: }
5164: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5165:
5166: #if directed to not display the secondary menu, don't.
5167: if ($args->{'no_secondary_menu'}) {
5168: return $bodytag;
5169: }
5170: #don't show menus for public users
5171: if (!$public){
5172: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5173: $bodytag .= Apache::lonmenu::serverform();
5174: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5175: if ($env{'request.state'} eq 'construct') {
5176: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5177: $args->{'bread_crumbs'});
5178: } elsif ($forcereg) {
5179: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5180: $args->{'group'});
5181: } else {
5182: my $forbodytag;
5183: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5184: $forcereg,$args->{'group'},
5185: $args->{'bread_crumbs'},
5186: $advtoolsref,'',\$forbodytag);
5187: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5188: $bodytag .= $forbodytag;
5189: }
5190: }
5191: }else{
5192: # this is to seperate menu from content when there's no secondary
5193: # menu. Especially needed for public accessible ressources.
5194: $bodytag .= '<hr style="clear:both" />';
5195: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5196: }
5197:
5198: return $bodytag;
5199: }
5200:
5201: #
5202: # Top frame rendering, Remote is up
5203: #
5204:
5205: my $imgsrc = $img;
5206: if ($img =~ /^\/adm/) {
5207: $imgsrc = &lonhttpdurl($img);
5208: }
5209: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
5210:
5211: my $help=($no_inline_link?''
5212: :&Apache::loncommon::top_nav_help('Help'));
5213:
5214: # Explicit link to get inline menu
5215: my $menu= ($no_inline_link?''
5216: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
5217:
5218: if ($dc_info) {
5219: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
5220: }
5221:
5222: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5223: unless ($public) {
5224: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5225: undef,'LC_menubuttons_link');
5226: }
5227:
5228: unless ($env{'form.inhibitmenu'}) {
5229: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
5230: <ol class="LC_primary_menu LC_floatright LC_right">
5231: <li>$help</li>
5232: <li>$menu</li>
5233: </ol><div id="LC_realm"> $realm $dc_info</div>|;
5234: }
5235: if ($env{'request.state'} eq 'construct') {
5236: if (!$public){
5237: if ($env{'request.state'} eq 'construct') {
5238: $funclist = &Apache::lonhtmlcommon::scripttag(
5239: &Apache::lonmenu::utilityfunctions($httphost), 'start').
5240: &Apache::lonhtmlcommon::scripttag('','end').
5241: &Apache::lonmenu::innerregister($forcereg,
5242: $args->{'bread_crumbs'});
5243: }
5244: }
5245: }
5246: return $bodytag."\n".$funclist;
5247: }
5248:
5249: sub dc_courseid_toggle {
5250: my ($dc_info) = @_;
5251: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5252: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5253: &mt('(More ...)').'</a></span>'.
5254: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5255: }
5256:
5257: sub make_attr_string {
5258: my ($register,$attr_ref) = @_;
5259:
5260: if ($attr_ref && !ref($attr_ref)) {
5261: die("addentries Must be a hash ref ".
5262: join(':',caller(1))." ".
5263: join(':',caller(0))." ");
5264: }
5265:
5266: if ($register) {
5267: my ($on_load,$on_unload);
5268: foreach my $key (keys(%{$attr_ref})) {
5269: if (lc($key) eq 'onload') {
5270: $on_load.=$attr_ref->{$key}.';';
5271: delete($attr_ref->{$key});
5272:
5273: } elsif (lc($key) eq 'onunload') {
5274: $on_unload.=$attr_ref->{$key}.';';
5275: delete($attr_ref->{$key});
5276: }
5277: }
5278: if ($env{'environment.remote'} eq 'on') {
5279: $attr_ref->{'onload'} =
5280: &Apache::lonmenu::loadevents(). $on_load;
5281: $attr_ref->{'onunload'}=
5282: &Apache::lonmenu::unloadevents().$on_unload;
5283: } else {
5284: $attr_ref->{'onload'} = $on_load;
5285: $attr_ref->{'onunload'}= $on_unload;
5286: }
5287: }
5288:
5289: my $attr_string;
5290: foreach my $attr (sort(keys(%$attr_ref))) {
5291: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5292: }
5293: return $attr_string;
5294: }
5295:
5296:
5297: ###############################################
5298: ###############################################
5299:
5300: =pod
5301:
5302: =item * &endbodytag()
5303:
5304: Returns a uniform footer for LON-CAPA web pages.
5305:
5306: Inputs: 1 - optional reference to an args hash
5307: If in the hash, key for noredirectlink has a value which evaluates to true,
5308: a 'Continue' link is not displayed if the page contains an
5309: internal redirect in the <head></head> section,
5310: i.e., $env{'internal.head.redirect'} exists
5311:
5312: =cut
5313:
5314: sub endbodytag {
5315: my ($args) = @_;
5316: my $endbodytag;
5317: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5318: $endbodytag='</body>';
5319: }
5320: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5321: if ( exists( $env{'internal.head.redirect'} ) ) {
5322: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5323: $endbodytag=
5324: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5325: &mt('Continue').'</a>'.
5326: $endbodytag;
5327: }
5328: }
5329: return $endbodytag;
5330: }
5331:
5332: =pod
5333:
5334: =item * &standard_css()
5335:
5336: Returns a style sheet
5337:
5338: Inputs: (all optional)
5339: domain -> force to color decorate a page for a specific
5340: domain
5341: function -> force usage of a specific rolish color scheme
5342: bgcolor -> override the default page bgcolor
5343:
5344: =cut
5345:
5346: sub standard_css {
5347: my ($function,$domain,$bgcolor) = @_;
5348: $function = &get_users_function() if (!$function);
5349: my $img = &designparm($function.'.img', $domain);
5350: my $tabbg = &designparm($function.'.tabbg', $domain);
5351: my $font = &designparm($function.'.font', $domain);
5352: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5353: #second colour for later usage
5354: my $sidebg = &designparm($function.'.sidebg',$domain);
5355: my $pgbg_or_bgcolor =
5356: $bgcolor ||
5357: &designparm($function.'.pgbg', $domain);
5358: my $pgbg = &designparm($function.'.pgbg', $domain);
5359: my $alink = &designparm($function.'.alink', $domain);
5360: my $vlink = &designparm($function.'.vlink', $domain);
5361: my $link = &designparm($function.'.link', $domain);
5362:
5363: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5364: my $mono = 'monospace';
5365: my $data_table_head = $sidebg;
5366: my $data_table_light = '#FAFAFA';
5367: my $data_table_dark = '#E0E0E0';
5368: my $data_table_darker = '#CCCCCC';
5369: my $data_table_highlight = '#FFFF00';
5370: my $mail_new = '#FFBB77';
5371: my $mail_new_hover = '#DD9955';
5372: my $mail_read = '#BBBB77';
5373: my $mail_read_hover = '#999944';
5374: my $mail_replied = '#AAAA88';
5375: my $mail_replied_hover = '#888855';
5376: my $mail_other = '#99BBBB';
5377: my $mail_other_hover = '#669999';
5378: my $table_header = '#DDDDDD';
5379: my $feedback_link_bg = '#BBBBBB';
5380: my $lg_border_color = '#C8C8C8';
5381: my $button_hover = '#BF2317';
5382:
5383: my $border = ($env{'browser.type'} eq 'explorer' ||
5384: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5385: : '0 3px 0 4px';
5386:
5387:
5388: return <<END;
5389:
5390: /* needed for iframe to allow 100% height in FF */
5391: body, html {
5392: margin: 0;
5393: padding: 0 0.5%;
5394: height: 99%; /* to avoid scrollbars */
5395: }
5396:
5397: body {
5398: font-family: $sans;
5399: line-height:130%;
5400: font-size:0.83em;
5401: color:$font;
5402: }
5403:
5404: a:focus,
5405: a:focus img {
5406: color: red;
5407: }
5408:
5409: form, .inline {
5410: display: inline;
5411: }
5412:
5413: .LC_right {
5414: text-align:right;
5415: }
5416:
5417: .LC_middle {
5418: vertical-align:middle;
5419: }
5420:
5421: .LC_floatleft {
5422: float: left;
5423: }
5424:
5425: .LC_floatright {
5426: float: right;
5427: }
5428:
5429: .LC_400Box {
5430: width:400px;
5431: }
5432:
5433: .LC_iframecontainer {
5434: width: 98%;
5435: margin: 0;
5436: position: fixed;
5437: top: 8.5em;
5438: bottom: 0;
5439: }
5440:
5441: .LC_iframecontainer iframe{
5442: border: none;
5443: width: 100%;
5444: height: 100%;
5445: }
5446:
5447: .LC_filename {
5448: font-family: $mono;
5449: white-space:pre;
5450: font-size: 120%;
5451: }
5452:
5453: .LC_fileicon {
5454: border: none;
5455: height: 1.3em;
5456: vertical-align: text-bottom;
5457: margin-right: 0.3em;
5458: text-decoration:none;
5459: }
5460:
5461: .LC_setting {
5462: text-decoration:underline;
5463: }
5464:
5465: .LC_error {
5466: color: red;
5467: }
5468:
5469: .LC_warning {
5470: color: darkorange;
5471: }
5472:
5473: .LC_diff_removed {
5474: color: red;
5475: }
5476:
5477: .LC_info,
5478: .LC_success,
5479: .LC_diff_added {
5480: color: green;
5481: }
5482:
5483: div.LC_confirm_box {
5484: background-color: #FAFAFA;
5485: border: 1px solid $lg_border_color;
5486: margin-right: 0;
5487: padding: 5px;
5488: }
5489:
5490: div.LC_confirm_box .LC_error img,
5491: div.LC_confirm_box .LC_success img {
5492: vertical-align: middle;
5493: }
5494:
5495: .LC_icon {
5496: border: none;
5497: vertical-align: middle;
5498: }
5499:
5500: .LC_docs_spacer {
5501: width: 25px;
5502: height: 1px;
5503: border: none;
5504: }
5505:
5506: .LC_internal_info {
5507: color: #999999;
5508: }
5509:
5510: .LC_discussion {
5511: background: $data_table_dark;
5512: border: 1px solid black;
5513: margin: 2px;
5514: }
5515:
5516: .LC_disc_action_left {
5517: background: $sidebg;
5518: text-align: left;
5519: padding: 4px;
5520: margin: 2px;
5521: }
5522:
5523: .LC_disc_action_right {
5524: background: $sidebg;
5525: text-align: right;
5526: padding: 4px;
5527: margin: 2px;
5528: }
5529:
5530: .LC_disc_new_item {
5531: background: white;
5532: border: 2px solid red;
5533: margin: 4px;
5534: padding: 4px;
5535: }
5536:
5537: .LC_disc_old_item {
5538: background: white;
5539: margin: 4px;
5540: padding: 4px;
5541: }
5542:
5543: table.LC_pastsubmission {
5544: border: 1px solid black;
5545: margin: 2px;
5546: }
5547:
5548: table#LC_menubuttons {
5549: width: 100%;
5550: background: $pgbg;
5551: border: 2px;
5552: border-collapse: separate;
5553: padding: 0;
5554: }
5555:
5556: table#LC_title_bar a {
5557: color: $fontmenu;
5558: }
5559:
5560: table#LC_title_bar {
5561: clear: both;
5562: display: none;
5563: }
5564:
5565: table#LC_title_bar,
5566: table.LC_breadcrumbs, /* obsolete? */
5567: table#LC_title_bar.LC_with_remote {
5568: width: 100%;
5569: border-color: $pgbg;
5570: border-style: solid;
5571: border-width: $border;
5572: background: $pgbg;
5573: color: $fontmenu;
5574: border-collapse: collapse;
5575: padding: 0;
5576: margin: 0;
5577: }
5578:
5579: ul.LC_breadcrumb_tools_outerlist {
5580: margin: 0;
5581: padding: 0;
5582: position: relative;
5583: list-style: none;
5584: }
5585: ul.LC_breadcrumb_tools_outerlist li {
5586: display: inline;
5587: }
5588:
5589: .LC_breadcrumb_tools_navigation {
5590: padding: 0;
5591: margin: 0;
5592: float: left;
5593: }
5594: .LC_breadcrumb_tools_tools {
5595: padding: 0;
5596: margin: 0;
5597: float: right;
5598: }
5599:
5600: table#LC_title_bar td {
5601: background: $tabbg;
5602: }
5603:
5604: table#LC_menubuttons img {
5605: border: none;
5606: }
5607:
5608: .LC_breadcrumbs_component {
5609: float: right;
5610: margin: 0 1em;
5611: }
5612: .LC_breadcrumbs_component img {
5613: vertical-align: middle;
5614: }
5615:
5616: td.LC_table_cell_checkbox {
5617: text-align: center;
5618: }
5619:
5620: .LC_fontsize_small {
5621: font-size: 70%;
5622: }
5623:
5624: #LC_breadcrumbs {
5625: clear:both;
5626: background: $sidebg;
5627: border-bottom: 1px solid $lg_border_color;
5628: line-height: 2.5em;
5629: overflow: hidden;
5630: margin: 0;
5631: padding: 0;
5632: text-align: left;
5633: }
5634:
5635: .LC_head_subbox, .LC_actionbox {
5636: clear:both;
5637: background: #F8F8F8; /* $sidebg; */
5638: border: 1px solid $sidebg;
5639: margin: 0 0 10px 0;
5640: padding: 3px;
5641: text-align: left;
5642: }
5643:
5644: .LC_fontsize_medium {
5645: font-size: 85%;
5646: }
5647:
5648: .LC_fontsize_large {
5649: font-size: 120%;
5650: }
5651:
5652: .LC_menubuttons_inline_text {
5653: color: $font;
5654: font-size: 90%;
5655: padding-left:3px;
5656: }
5657:
5658: .LC_menubuttons_inline_text img{
5659: vertical-align: middle;
5660: }
5661:
5662: li.LC_menubuttons_inline_text img {
5663: cursor:pointer;
5664: text-decoration: none;
5665: }
5666:
5667: .LC_menubuttons_link {
5668: text-decoration: none;
5669: }
5670:
5671: .LC_menubuttons_category {
5672: color: $font;
5673: background: $pgbg;
5674: font-size: larger;
5675: font-weight: bold;
5676: }
5677:
5678: td.LC_menubuttons_text {
5679: color: $font;
5680: }
5681:
5682: .LC_current_location {
5683: background: $tabbg;
5684: }
5685:
5686: table.LC_data_table {
5687: border: 1px solid #000000;
5688: border-collapse: separate;
5689: border-spacing: 1px;
5690: background: $pgbg;
5691: }
5692:
5693: .LC_data_table_dense {
5694: font-size: small;
5695: }
5696:
5697: table.LC_nested_outer {
5698: border: 1px solid #000000;
5699: border-collapse: collapse;
5700: border-spacing: 0;
5701: width: 100%;
5702: }
5703:
5704: table.LC_innerpickbox,
5705: table.LC_nested {
5706: border: none;
5707: border-collapse: collapse;
5708: border-spacing: 0;
5709: width: 100%;
5710: }
5711:
5712: table.LC_data_table tr th,
5713: table.LC_calendar tr th,
5714: table.LC_prior_tries tr th,
5715: table.LC_innerpickbox tr th {
5716: font-weight: bold;
5717: background-color: $data_table_head;
5718: color:$fontmenu;
5719: font-size:90%;
5720: }
5721:
5722: table.LC_innerpickbox tr th,
5723: table.LC_innerpickbox tr td {
5724: vertical-align: top;
5725: }
5726:
5727: table.LC_data_table tr.LC_info_row > td {
5728: background-color: #CCCCCC;
5729: font-weight: bold;
5730: text-align: left;
5731: }
5732:
5733: table.LC_data_table tr.LC_odd_row > td {
5734: background-color: $data_table_light;
5735: padding: 2px;
5736: vertical-align: top;
5737: }
5738:
5739: table.LC_pick_box tr > td.LC_odd_row {
5740: background-color: $data_table_light;
5741: vertical-align: top;
5742: }
5743:
5744: table.LC_data_table tr.LC_even_row > td {
5745: background-color: $data_table_dark;
5746: padding: 2px;
5747: vertical-align: top;
5748: }
5749:
5750: table.LC_pick_box tr > td.LC_even_row {
5751: background-color: $data_table_dark;
5752: vertical-align: top;
5753: }
5754:
5755: table.LC_data_table tr.LC_data_table_highlight td {
5756: background-color: $data_table_darker;
5757: }
5758:
5759: table.LC_data_table tr td.LC_leftcol_header {
5760: background-color: $data_table_head;
5761: font-weight: bold;
5762: }
5763:
5764: table.LC_data_table tr.LC_empty_row td,
5765: table.LC_nested tr.LC_empty_row td {
5766: font-weight: bold;
5767: font-style: italic;
5768: text-align: center;
5769: padding: 8px;
5770: }
5771:
5772: table.LC_data_table tr.LC_empty_row td,
5773: table.LC_data_table tr.LC_footer_row td {
5774: background-color: $sidebg;
5775: }
5776:
5777: table.LC_nested tr.LC_empty_row td {
5778: background-color: #FFFFFF;
5779: }
5780:
5781: table.LC_caption {
5782: }
5783:
5784: table.LC_nested tr.LC_empty_row td {
5785: padding: 4ex
5786: }
5787:
5788: table.LC_nested_outer tr th {
5789: font-weight: bold;
5790: color:$fontmenu;
5791: background-color: $data_table_head;
5792: font-size: small;
5793: border-bottom: 1px solid #000000;
5794: }
5795:
5796: table.LC_nested_outer tr td.LC_subheader {
5797: background-color: $data_table_head;
5798: font-weight: bold;
5799: font-size: small;
5800: border-bottom: 1px solid #000000;
5801: text-align: right;
5802: }
5803:
5804: table.LC_nested tr.LC_info_row td {
5805: background-color: #CCCCCC;
5806: font-weight: bold;
5807: font-size: small;
5808: text-align: center;
5809: }
5810:
5811: table.LC_nested tr.LC_info_row td.LC_left_item,
5812: table.LC_nested_outer tr th.LC_left_item {
5813: text-align: left;
5814: }
5815:
5816: table.LC_nested td {
5817: background-color: #FFFFFF;
5818: font-size: small;
5819: }
5820:
5821: table.LC_nested_outer tr th.LC_right_item,
5822: table.LC_nested tr.LC_info_row td.LC_right_item,
5823: table.LC_nested tr.LC_odd_row td.LC_right_item,
5824: table.LC_nested tr td.LC_right_item {
5825: text-align: right;
5826: }
5827:
5828: table.LC_nested tr.LC_odd_row td {
5829: background-color: #EEEEEE;
5830: }
5831:
5832: table.LC_createuser {
5833: }
5834:
5835: table.LC_createuser tr.LC_section_row td {
5836: font-size: small;
5837: }
5838:
5839: table.LC_createuser tr.LC_info_row td {
5840: background-color: #CCCCCC;
5841: font-weight: bold;
5842: text-align: center;
5843: }
5844:
5845: table.LC_calendar {
5846: border: 1px solid #000000;
5847: border-collapse: collapse;
5848: width: 98%;
5849: }
5850:
5851: table.LC_calendar_pickdate {
5852: font-size: xx-small;
5853: }
5854:
5855: table.LC_calendar tr td {
5856: border: 1px solid #000000;
5857: vertical-align: top;
5858: width: 14%;
5859: }
5860:
5861: table.LC_calendar tr td.LC_calendar_day_empty {
5862: background-color: $data_table_dark;
5863: }
5864:
5865: table.LC_calendar tr td.LC_calendar_day_current {
5866: background-color: $data_table_highlight;
5867: }
5868:
5869: table.LC_data_table tr td.LC_mail_new {
5870: background-color: $mail_new;
5871: }
5872:
5873: table.LC_data_table tr.LC_mail_new:hover {
5874: background-color: $mail_new_hover;
5875: }
5876:
5877: table.LC_data_table tr td.LC_mail_read {
5878: background-color: $mail_read;
5879: }
5880:
5881: /*
5882: table.LC_data_table tr.LC_mail_read:hover {
5883: background-color: $mail_read_hover;
5884: }
5885: */
5886:
5887: table.LC_data_table tr td.LC_mail_replied {
5888: background-color: $mail_replied;
5889: }
5890:
5891: /*
5892: table.LC_data_table tr.LC_mail_replied:hover {
5893: background-color: $mail_replied_hover;
5894: }
5895: */
5896:
5897: table.LC_data_table tr td.LC_mail_other {
5898: background-color: $mail_other;
5899: }
5900:
5901: /*
5902: table.LC_data_table tr.LC_mail_other:hover {
5903: background-color: $mail_other_hover;
5904: }
5905: */
5906:
5907: table.LC_data_table tr > td.LC_browser_file,
5908: table.LC_data_table tr > td.LC_browser_file_published {
5909: background: #AAEE77;
5910: }
5911:
5912: table.LC_data_table tr > td.LC_browser_file_locked,
5913: table.LC_data_table tr > td.LC_browser_file_unpublished {
5914: background: #FFAA99;
5915: }
5916:
5917: table.LC_data_table tr > td.LC_browser_file_obsolete {
5918: background: #888888;
5919: }
5920:
5921: table.LC_data_table tr > td.LC_browser_file_modified,
5922: table.LC_data_table tr > td.LC_browser_file_metamodified {
5923: background: #F8F866;
5924: }
5925:
5926: table.LC_data_table tr.LC_browser_folder > td {
5927: background: #E0E8FF;
5928: }
5929:
5930: table.LC_data_table tr > td.LC_roles_is {
5931: /* background: #77FF77; */
5932: }
5933:
5934: table.LC_data_table tr > td.LC_roles_future {
5935: border-right: 8px solid #FFFF77;
5936: }
5937:
5938: table.LC_data_table tr > td.LC_roles_will {
5939: border-right: 8px solid #FFAA77;
5940: }
5941:
5942: table.LC_data_table tr > td.LC_roles_expired {
5943: border-right: 8px solid #FF7777;
5944: }
5945:
5946: table.LC_data_table tr > td.LC_roles_will_not {
5947: border-right: 8px solid #AAFF77;
5948: }
5949:
5950: table.LC_data_table tr > td.LC_roles_selected {
5951: border-right: 8px solid #11CC55;
5952: }
5953:
5954: span.LC_current_location {
5955: font-size:larger;
5956: background: $pgbg;
5957: }
5958:
5959: span.LC_current_nav_location {
5960: font-weight:bold;
5961: background: $sidebg;
5962: }
5963:
5964: span.LC_parm_menu_item {
5965: font-size: larger;
5966: }
5967:
5968: span.LC_parm_scope_all {
5969: color: red;
5970: }
5971:
5972: span.LC_parm_scope_folder {
5973: color: green;
5974: }
5975:
5976: span.LC_parm_scope_resource {
5977: color: orange;
5978: }
5979:
5980: span.LC_parm_part {
5981: color: blue;
5982: }
5983:
5984: span.LC_parm_folder,
5985: span.LC_parm_symb {
5986: font-size: x-small;
5987: font-family: $mono;
5988: color: #AAAAAA;
5989: }
5990:
5991: ul.LC_parm_parmlist li {
5992: display: inline-block;
5993: padding: 0.3em 0.8em;
5994: vertical-align: top;
5995: width: 150px;
5996: border-top:1px solid $lg_border_color;
5997: }
5998:
5999: td.LC_parm_overview_level_menu,
6000: td.LC_parm_overview_map_menu,
6001: td.LC_parm_overview_parm_selectors,
6002: td.LC_parm_overview_restrictions {
6003: border: 1px solid black;
6004: border-collapse: collapse;
6005: }
6006:
6007: table.LC_parm_overview_restrictions td {
6008: border-width: 1px 4px 1px 4px;
6009: border-style: solid;
6010: border-color: $pgbg;
6011: text-align: center;
6012: }
6013:
6014: table.LC_parm_overview_restrictions th {
6015: background: $tabbg;
6016: border-width: 1px 4px 1px 4px;
6017: border-style: solid;
6018: border-color: $pgbg;
6019: }
6020:
6021: table#LC_helpmenu {
6022: border: none;
6023: height: 55px;
6024: border-spacing: 0;
6025: }
6026:
6027: table#LC_helpmenu fieldset legend {
6028: font-size: larger;
6029: }
6030:
6031: table#LC_helpmenu_links {
6032: width: 100%;
6033: border: 1px solid black;
6034: background: $pgbg;
6035: padding: 0;
6036: border-spacing: 1px;
6037: }
6038:
6039: table#LC_helpmenu_links tr td {
6040: padding: 1px;
6041: background: $tabbg;
6042: text-align: center;
6043: font-weight: bold;
6044: }
6045:
6046: table#LC_helpmenu_links a:link,
6047: table#LC_helpmenu_links a:visited,
6048: table#LC_helpmenu_links a:active {
6049: text-decoration: none;
6050: color: $font;
6051: }
6052:
6053: table#LC_helpmenu_links a:hover {
6054: text-decoration: underline;
6055: color: $vlink;
6056: }
6057:
6058: .LC_chrt_popup_exists {
6059: border: 1px solid #339933;
6060: margin: -1px;
6061: }
6062:
6063: .LC_chrt_popup_up {
6064: border: 1px solid yellow;
6065: margin: -1px;
6066: }
6067:
6068: .LC_chrt_popup {
6069: border: 1px solid #8888FF;
6070: background: #CCCCFF;
6071: }
6072:
6073: table.LC_pick_box {
6074: border-collapse: separate;
6075: background: white;
6076: border: 1px solid black;
6077: border-spacing: 1px;
6078: }
6079:
6080: table.LC_pick_box td.LC_pick_box_title {
6081: background: $sidebg;
6082: font-weight: bold;
6083: text-align: left;
6084: vertical-align: top;
6085: width: 184px;
6086: padding: 8px;
6087: }
6088:
6089: table.LC_pick_box td.LC_pick_box_value {
6090: text-align: left;
6091: padding: 8px;
6092: }
6093:
6094: table.LC_pick_box td.LC_pick_box_select {
6095: text-align: left;
6096: padding: 8px;
6097: }
6098:
6099: table.LC_pick_box td.LC_pick_box_separator {
6100: padding: 0;
6101: height: 1px;
6102: background: black;
6103: }
6104:
6105: table.LC_pick_box td.LC_pick_box_submit {
6106: text-align: right;
6107: }
6108:
6109: table.LC_pick_box td.LC_evenrow_value {
6110: text-align: left;
6111: padding: 8px;
6112: background-color: $data_table_light;
6113: }
6114:
6115: table.LC_pick_box td.LC_oddrow_value {
6116: text-align: left;
6117: padding: 8px;
6118: background-color: $data_table_light;
6119: }
6120:
6121: span.LC_helpform_receipt_cat {
6122: font-weight: bold;
6123: }
6124:
6125: table.LC_group_priv_box {
6126: background: white;
6127: border: 1px solid black;
6128: border-spacing: 1px;
6129: }
6130:
6131: table.LC_group_priv_box td.LC_pick_box_title {
6132: background: $tabbg;
6133: font-weight: bold;
6134: text-align: right;
6135: width: 184px;
6136: }
6137:
6138: table.LC_group_priv_box td.LC_groups_fixed {
6139: background: $data_table_light;
6140: text-align: center;
6141: }
6142:
6143: table.LC_group_priv_box td.LC_groups_optional {
6144: background: $data_table_dark;
6145: text-align: center;
6146: }
6147:
6148: table.LC_group_priv_box td.LC_groups_functionality {
6149: background: $data_table_darker;
6150: text-align: center;
6151: font-weight: bold;
6152: }
6153:
6154: table.LC_group_priv td {
6155: text-align: left;
6156: padding: 0;
6157: }
6158:
6159: .LC_navbuttons {
6160: margin: 2ex 0ex 2ex 0ex;
6161: }
6162:
6163: .LC_topic_bar {
6164: font-weight: bold;
6165: background: $tabbg;
6166: margin: 1em 0em 1em 2em;
6167: padding: 3px;
6168: font-size: 1.2em;
6169: }
6170:
6171: .LC_topic_bar span {
6172: left: 0.5em;
6173: position: absolute;
6174: vertical-align: middle;
6175: font-size: 1.2em;
6176: }
6177:
6178: table.LC_course_group_status {
6179: margin: 20px;
6180: }
6181:
6182: table.LC_status_selector td {
6183: vertical-align: top;
6184: text-align: center;
6185: padding: 4px;
6186: }
6187:
6188: div.LC_feedback_link {
6189: clear: both;
6190: background: $sidebg;
6191: width: 100%;
6192: padding-bottom: 10px;
6193: border: 1px $tabbg solid;
6194: height: 22px;
6195: line-height: 22px;
6196: padding-top: 5px;
6197: }
6198:
6199: div.LC_feedback_link img {
6200: height: 22px;
6201: vertical-align:middle;
6202: }
6203:
6204: div.LC_feedback_link a {
6205: text-decoration: none;
6206: }
6207:
6208: div.LC_comblock {
6209: display:inline;
6210: color:$font;
6211: font-size:90%;
6212: }
6213:
6214: div.LC_feedback_link div.LC_comblock {
6215: padding-left:5px;
6216: }
6217:
6218: div.LC_feedback_link div.LC_comblock a {
6219: color:$font;
6220: }
6221:
6222: span.LC_feedback_link {
6223: /* background: $feedback_link_bg; */
6224: font-size: larger;
6225: }
6226:
6227: span.LC_message_link {
6228: /* background: $feedback_link_bg; */
6229: font-size: larger;
6230: position: absolute;
6231: right: 1em;
6232: }
6233:
6234: table.LC_prior_tries {
6235: border: 1px solid #000000;
6236: border-collapse: separate;
6237: border-spacing: 1px;
6238: }
6239:
6240: table.LC_prior_tries td {
6241: padding: 2px;
6242: }
6243:
6244: .LC_answer_correct {
6245: background: lightgreen;
6246: color: darkgreen;
6247: padding: 6px;
6248: }
6249:
6250: .LC_answer_charged_try {
6251: background: #FFAAAA;
6252: color: darkred;
6253: padding: 6px;
6254: }
6255:
6256: .LC_answer_not_charged_try,
6257: .LC_answer_no_grade,
6258: .LC_answer_late {
6259: background: lightyellow;
6260: color: black;
6261: padding: 6px;
6262: }
6263:
6264: .LC_answer_previous {
6265: background: lightblue;
6266: color: darkblue;
6267: padding: 6px;
6268: }
6269:
6270: .LC_answer_no_message {
6271: background: #FFFFFF;
6272: color: black;
6273: padding: 6px;
6274: }
6275:
6276: .LC_answer_unknown {
6277: background: orange;
6278: color: black;
6279: padding: 6px;
6280: }
6281:
6282: span.LC_prior_numerical,
6283: span.LC_prior_string,
6284: span.LC_prior_custom,
6285: span.LC_prior_reaction,
6286: span.LC_prior_math {
6287: font-family: $mono;
6288: white-space: pre;
6289: }
6290:
6291: span.LC_prior_string {
6292: font-family: $mono;
6293: white-space: pre;
6294: }
6295:
6296: table.LC_prior_option {
6297: width: 100%;
6298: border-collapse: collapse;
6299: }
6300:
6301: table.LC_prior_rank,
6302: table.LC_prior_match {
6303: border-collapse: collapse;
6304: }
6305:
6306: table.LC_prior_option tr td,
6307: table.LC_prior_rank tr td,
6308: table.LC_prior_match tr td {
6309: border: 1px solid #000000;
6310: }
6311:
6312: .LC_nobreak {
6313: white-space: nowrap;
6314: }
6315:
6316: span.LC_cusr_emph {
6317: font-style: italic;
6318: }
6319:
6320: span.LC_cusr_subheading {
6321: font-weight: normal;
6322: font-size: 85%;
6323: }
6324:
6325: div.LC_docs_entry_move {
6326: border: 1px solid #BBBBBB;
6327: background: #DDDDDD;
6328: width: 22px;
6329: padding: 1px;
6330: margin: 0;
6331: }
6332:
6333: table.LC_data_table tr > td.LC_docs_entry_commands,
6334: table.LC_data_table tr > td.LC_docs_entry_parameter {
6335: font-size: x-small;
6336: }
6337:
6338: .LC_docs_entry_parameter {
6339: white-space: nowrap;
6340: }
6341:
6342: .LC_docs_copy {
6343: color: #000099;
6344: }
6345:
6346: .LC_docs_cut {
6347: color: #550044;
6348: }
6349:
6350: .LC_docs_rename {
6351: color: #009900;
6352: }
6353:
6354: .LC_docs_remove {
6355: color: #990000;
6356: }
6357:
6358: .LC_docs_reinit_warn,
6359: .LC_docs_ext_edit {
6360: font-size: x-small;
6361: }
6362:
6363: table.LC_docs_adddocs td,
6364: table.LC_docs_adddocs th {
6365: border: 1px solid #BBBBBB;
6366: padding: 4px;
6367: background: #DDDDDD;
6368: }
6369:
6370: table.LC_sty_begin {
6371: background: #BBFFBB;
6372: }
6373:
6374: table.LC_sty_end {
6375: background: #FFBBBB;
6376: }
6377:
6378: table.LC_double_column {
6379: border-width: 0;
6380: border-collapse: collapse;
6381: width: 100%;
6382: padding: 2px;
6383: }
6384:
6385: table.LC_double_column tr td.LC_left_col {
6386: top: 2px;
6387: left: 2px;
6388: width: 47%;
6389: vertical-align: top;
6390: }
6391:
6392: table.LC_double_column tr td.LC_right_col {
6393: top: 2px;
6394: right: 2px;
6395: width: 47%;
6396: vertical-align: top;
6397: }
6398:
6399: div.LC_left_float {
6400: float: left;
6401: padding-right: 5%;
6402: padding-bottom: 4px;
6403: }
6404:
6405: div.LC_clear_float_header {
6406: padding-bottom: 2px;
6407: }
6408:
6409: div.LC_clear_float_footer {
6410: padding-top: 10px;
6411: clear: both;
6412: }
6413:
6414: div.LC_grade_show_user {
6415: /* border-left: 5px solid $sidebg; */
6416: border-top: 5px solid #000000;
6417: margin: 50px 0 0 0;
6418: padding: 15px 0 5px 10px;
6419: }
6420:
6421: div.LC_grade_show_user_odd_row {
6422: /* border-left: 5px solid #000000; */
6423: }
6424:
6425: div.LC_grade_show_user div.LC_Box {
6426: margin-right: 50px;
6427: }
6428:
6429: div.LC_grade_submissions,
6430: div.LC_grade_message_center,
6431: div.LC_grade_info_links {
6432: margin: 5px;
6433: width: 99%;
6434: background: #FFFFFF;
6435: }
6436:
6437: div.LC_grade_submissions_header,
6438: div.LC_grade_message_center_header {
6439: font-weight: bold;
6440: font-size: large;
6441: }
6442:
6443: div.LC_grade_submissions_body,
6444: div.LC_grade_message_center_body {
6445: border: 1px solid black;
6446: width: 99%;
6447: background: #FFFFFF;
6448: }
6449:
6450: table.LC_scantron_action {
6451: width: 100%;
6452: }
6453:
6454: table.LC_scantron_action tr th {
6455: font-weight:bold;
6456: font-style:normal;
6457: }
6458:
6459: .LC_edit_problem_header,
6460: div.LC_edit_problem_footer {
6461: font-weight: normal;
6462: font-size: medium;
6463: margin: 2px;
6464: background-color: $sidebg;
6465: }
6466:
6467: div.LC_edit_problem_header,
6468: div.LC_edit_problem_header div,
6469: div.LC_edit_problem_footer,
6470: div.LC_edit_problem_footer div,
6471: div.LC_edit_problem_editxml_header,
6472: div.LC_edit_problem_editxml_header div {
6473: margin-top: 5px;
6474: }
6475:
6476: div.LC_edit_problem_header_title {
6477: font-weight: bold;
6478: font-size: larger;
6479: background: $tabbg;
6480: padding: 3px;
6481: margin: 0 0 5px 0;
6482: }
6483:
6484: table.LC_edit_problem_header_title {
6485: width: 100%;
6486: background: $tabbg;
6487: }
6488:
6489: div.LC_edit_problem_discards {
6490: float: left;
6491: padding-bottom: 5px;
6492: }
6493:
6494: div.LC_edit_problem_saves {
6495: float: right;
6496: padding-bottom: 5px;
6497: }
6498:
6499: .LC_edit_opt {
6500: padding-left: 1em;
6501: white-space: nowrap;
6502: }
6503:
6504: .LC_edit_problem_latexhelper{
6505: text-align: right;
6506: }
6507:
6508: #LC_edit_problem_colorful div{
6509: margin-left: 40px;
6510: }
6511:
6512: img.stift {
6513: border-width: 0;
6514: vertical-align: middle;
6515: }
6516:
6517: table td.LC_mainmenu_col_fieldset {
6518: vertical-align: top;
6519: }
6520:
6521: div.LC_createcourse {
6522: margin: 10px 10px 10px 10px;
6523: }
6524:
6525: .LC_dccid {
6526: float: right;
6527: margin: 0.2em 0 0 0;
6528: padding: 0;
6529: font-size: 90%;
6530: display:none;
6531: }
6532:
6533: ol.LC_primary_menu a:hover,
6534: ol#LC_MenuBreadcrumbs a:hover,
6535: ol#LC_PathBreadcrumbs a:hover,
6536: ul#LC_secondary_menu a:hover,
6537: .LC_FormSectionClearButton input:hover
6538: ul.LC_TabContent li:hover a {
6539: color:$button_hover;
6540: text-decoration:none;
6541: }
6542:
6543: h1 {
6544: padding: 0;
6545: line-height:130%;
6546: }
6547:
6548: h2,
6549: h3,
6550: h4,
6551: h5,
6552: h6 {
6553: margin: 5px 0 5px 0;
6554: padding: 0;
6555: line-height:130%;
6556: }
6557:
6558: .LC_hcell {
6559: padding:3px 15px 3px 15px;
6560: margin: 0;
6561: background-color:$tabbg;
6562: color:$fontmenu;
6563: border-bottom:solid 1px $lg_border_color;
6564: }
6565:
6566: .LC_Box > .LC_hcell {
6567: margin: 0 -10px 10px -10px;
6568: }
6569:
6570: .LC_noBorder {
6571: border: 0;
6572: }
6573:
6574: .LC_FormSectionClearButton input {
6575: background-color:transparent;
6576: border: none;
6577: cursor:pointer;
6578: text-decoration:underline;
6579: }
6580:
6581: .LC_help_open_topic {
6582: color: #FFFFFF;
6583: background-color: #EEEEFF;
6584: margin: 1px;
6585: padding: 4px;
6586: border: 1px solid #000033;
6587: white-space: nowrap;
6588: /* vertical-align: middle; */
6589: }
6590:
6591: dl,
6592: ul,
6593: div,
6594: fieldset {
6595: margin: 10px 10px 10px 0;
6596: /* overflow: hidden; */
6597: }
6598:
6599: fieldset > legend {
6600: font-weight: bold;
6601: padding: 0 5px 0 5px;
6602: }
6603:
6604: #LC_nav_bar {
6605: float: left;
6606: background-color: $pgbg_or_bgcolor;
6607: margin: 0 0 2px 0;
6608: }
6609:
6610: #LC_realm {
6611: margin: 0.2em 0 0 0;
6612: padding: 0;
6613: font-weight: bold;
6614: text-align: center;
6615: background-color: $pgbg_or_bgcolor;
6616: }
6617:
6618: #LC_nav_bar em {
6619: font-weight: bold;
6620: font-style: normal;
6621: }
6622:
6623: ol.LC_primary_menu {
6624: margin: 0;
6625: padding: 0;
6626: background-color: $pgbg_or_bgcolor;
6627: }
6628:
6629: ol#LC_PathBreadcrumbs {
6630: margin: 0;
6631: }
6632:
6633: ol.LC_primary_menu li {
6634: color: RGB(80, 80, 80);
6635: vertical-align: middle;
6636: text-align: left;
6637: list-style: none;
6638: float: left;
6639: }
6640:
6641: ol.LC_primary_menu li a {
6642: display: block;
6643: margin: 0;
6644: padding: 0 5px 0 10px;
6645: text-decoration: none;
6646: }
6647:
6648: ol.LC_primary_menu li ul {
6649: display: none;
6650: width: 10em;
6651: background-color: $data_table_light;
6652: }
6653:
6654: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
6655: display: block;
6656: position: absolute;
6657: margin: 0;
6658: padding: 0;
6659: z-index: 2;
6660: }
6661:
6662: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
6663: font-size: 90%;
6664: vertical-align: top;
6665: float: none;
6666: border-left: 1px solid black;
6667: border-right: 1px solid black;
6668: }
6669:
6670: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
6671: background-color:$data_table_light;
6672: }
6673:
6674: ol.LC_primary_menu li li a:hover {
6675: color:$button_hover;
6676: background-color:$data_table_dark;
6677: }
6678:
6679: ol.LC_primary_menu li img {
6680: vertical-align: bottom;
6681: height: 1.1em;
6682: margin: 0.2em 0 0 0;
6683: }
6684:
6685: ol.LC_primary_menu a {
6686: color: RGB(80, 80, 80);
6687: text-decoration: none;
6688: }
6689:
6690: ol.LC_primary_menu a.LC_new_message {
6691: font-weight:bold;
6692: color: darkred;
6693: }
6694:
6695: ol.LC_docs_parameters {
6696: margin-left: 0;
6697: padding: 0;
6698: list-style: none;
6699: }
6700:
6701: ol.LC_docs_parameters li {
6702: margin: 0;
6703: padding-right: 20px;
6704: display: inline;
6705: }
6706:
6707: ol.LC_docs_parameters li:before {
6708: content: "\\002022 \\0020";
6709: }
6710:
6711: li.LC_docs_parameters_title {
6712: font-weight: bold;
6713: }
6714:
6715: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6716: content: "";
6717: }
6718:
6719: ul#LC_secondary_menu {
6720: clear: right;
6721: color: $fontmenu;
6722: background: $tabbg;
6723: list-style: none;
6724: padding: 0;
6725: margin: 0;
6726: width: 100%;
6727: text-align: left;
6728: float: left;
6729: }
6730:
6731: ul#LC_secondary_menu li {
6732: font-weight: bold;
6733: line-height: 1.8em;
6734: border-right: 1px solid black;
6735: vertical-align: middle;
6736: float: left;
6737: }
6738:
6739: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
6740: background-color: $data_table_light;
6741: }
6742:
6743: ul#LC_secondary_menu li a {
6744: padding: 0 0.8em;
6745: }
6746:
6747: ul#LC_secondary_menu li ul {
6748: display: none;
6749: }
6750:
6751: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
6752: display: block;
6753: position: absolute;
6754: margin: 0;
6755: padding: 0;
6756: list-style:none;
6757: float: none;
6758: background-color: $data_table_light;
6759: z-index: 2;
6760: margin-left: -1px;
6761: }
6762:
6763: ul#LC_secondary_menu li ul li {
6764: font-size: 90%;
6765: vertical-align: top;
6766: border-left: 1px solid black;
6767: border-right: 1px solid black;
6768: background-color: $data_table_light;
6769: list-style:none;
6770: float: none;
6771: }
6772:
6773: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
6774: background-color: $data_table_dark;
6775: }
6776:
6777: ul.LC_TabContent {
6778: display:block;
6779: background: $sidebg;
6780: border-bottom: solid 1px $lg_border_color;
6781: list-style:none;
6782: margin: -1px -10px 0 -10px;
6783: padding: 0;
6784: }
6785:
6786: ul.LC_TabContent li,
6787: ul.LC_TabContentBigger li {
6788: float:left;
6789: }
6790:
6791: ul#LC_secondary_menu li a {
6792: color: $fontmenu;
6793: text-decoration: none;
6794: }
6795:
6796: ul.LC_TabContent {
6797: min-height:20px;
6798: }
6799:
6800: ul.LC_TabContent li {
6801: vertical-align:middle;
6802: padding: 0 16px 0 10px;
6803: background-color:$tabbg;
6804: border-bottom:solid 1px $lg_border_color;
6805: border-left: solid 1px $font;
6806: }
6807:
6808: ul.LC_TabContent .right {
6809: float:right;
6810: }
6811:
6812: ul.LC_TabContent li a,
6813: ul.LC_TabContent li {
6814: color:rgb(47,47,47);
6815: text-decoration:none;
6816: font-size:95%;
6817: font-weight:bold;
6818: min-height:20px;
6819: }
6820:
6821: ul.LC_TabContent li a:hover,
6822: ul.LC_TabContent li a:focus {
6823: color: $button_hover;
6824: background:none;
6825: outline:none;
6826: }
6827:
6828: ul.LC_TabContent li:hover {
6829: color: $button_hover;
6830: cursor:pointer;
6831: }
6832:
6833: ul.LC_TabContent li.active {
6834: color: $font;
6835: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6836: border-bottom:solid 1px #FFFFFF;
6837: cursor: default;
6838: }
6839:
6840: ul.LC_TabContent li.active a {
6841: color:$font;
6842: background:#FFFFFF;
6843: outline: none;
6844: }
6845:
6846: ul.LC_TabContent li.goback {
6847: float: left;
6848: border-left: none;
6849: }
6850:
6851: #maincoursedoc {
6852: clear:both;
6853: }
6854:
6855: ul.LC_TabContentBigger {
6856: display:block;
6857: list-style:none;
6858: padding: 0;
6859: }
6860:
6861: ul.LC_TabContentBigger li {
6862: vertical-align:bottom;
6863: height: 30px;
6864: font-size:110%;
6865: font-weight:bold;
6866: color: #737373;
6867: }
6868:
6869: ul.LC_TabContentBigger li.active {
6870: position: relative;
6871: top: 1px;
6872: }
6873:
6874: ul.LC_TabContentBigger li a {
6875: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6876: height: 30px;
6877: line-height: 30px;
6878: text-align: center;
6879: display: block;
6880: text-decoration: none;
6881: outline: none;
6882: }
6883:
6884: ul.LC_TabContentBigger li.active a {
6885: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6886: color:$font;
6887: }
6888:
6889: ul.LC_TabContentBigger li b {
6890: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6891: display: block;
6892: float: left;
6893: padding: 0 30px;
6894: border-bottom: 1px solid $lg_border_color;
6895: }
6896:
6897: ul.LC_TabContentBigger li:hover b {
6898: color:$button_hover;
6899: }
6900:
6901: ul.LC_TabContentBigger li.active b {
6902: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6903: color:$font;
6904: border: 0;
6905: }
6906:
6907:
6908: ul.LC_CourseBreadcrumbs {
6909: background: $sidebg;
6910: height: 2em;
6911: padding-left: 10px;
6912: margin: 0;
6913: list-style-position: inside;
6914: }
6915:
6916: ol#LC_MenuBreadcrumbs,
6917: ol#LC_PathBreadcrumbs {
6918: padding-left: 10px;
6919: margin: 0;
6920: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6921: }
6922:
6923: ol#LC_MenuBreadcrumbs li,
6924: ol#LC_PathBreadcrumbs li,
6925: ul.LC_CourseBreadcrumbs li {
6926: display: inline;
6927: white-space: normal;
6928: }
6929:
6930: ol#LC_MenuBreadcrumbs li a,
6931: ul.LC_CourseBreadcrumbs li a {
6932: text-decoration: none;
6933: font-size:90%;
6934: }
6935:
6936: ol#LC_MenuBreadcrumbs h1 {
6937: display: inline;
6938: font-size: 90%;
6939: line-height: 2.5em;
6940: margin: 0;
6941: padding: 0;
6942: }
6943:
6944: ol#LC_PathBreadcrumbs li a {
6945: text-decoration:none;
6946: font-size:100%;
6947: font-weight:bold;
6948: }
6949:
6950: .LC_Box {
6951: border: solid 1px $lg_border_color;
6952: padding: 0 10px 10px 10px;
6953: }
6954:
6955: .LC_DocsBox {
6956: border: solid 1px $lg_border_color;
6957: padding: 0 0 10px 10px;
6958: }
6959:
6960: .LC_AboutMe_Image {
6961: float:left;
6962: margin-right:10px;
6963: }
6964:
6965: .LC_Clear_AboutMe_Image {
6966: clear:left;
6967: }
6968:
6969: dl.LC_ListStyleClean dt {
6970: padding-right: 5px;
6971: display: table-header-group;
6972: }
6973:
6974: dl.LC_ListStyleClean dd {
6975: display: table-row;
6976: }
6977:
6978: .LC_ListStyleClean,
6979: .LC_ListStyleSimple,
6980: .LC_ListStyleNormal,
6981: .LC_ListStyleSpecial {
6982: /* display:block; */
6983: list-style-position: inside;
6984: list-style-type: none;
6985: overflow: hidden;
6986: padding: 0;
6987: }
6988:
6989: .LC_ListStyleSimple li,
6990: .LC_ListStyleSimple dd,
6991: .LC_ListStyleNormal li,
6992: .LC_ListStyleNormal dd,
6993: .LC_ListStyleSpecial li,
6994: .LC_ListStyleSpecial dd {
6995: margin: 0;
6996: padding: 5px 5px 5px 10px;
6997: clear: both;
6998: }
6999:
7000: .LC_ListStyleClean li,
7001: .LC_ListStyleClean dd {
7002: padding-top: 0;
7003: padding-bottom: 0;
7004: }
7005:
7006: .LC_ListStyleSimple dd,
7007: .LC_ListStyleSimple li {
7008: border-bottom: solid 1px $lg_border_color;
7009: }
7010:
7011: .LC_ListStyleSpecial li,
7012: .LC_ListStyleSpecial dd {
7013: list-style-type: none;
7014: background-color: RGB(220, 220, 220);
7015: margin-bottom: 4px;
7016: }
7017:
7018: table.LC_SimpleTable {
7019: margin:5px;
7020: border:solid 1px $lg_border_color;
7021: }
7022:
7023: table.LC_SimpleTable tr {
7024: padding: 0;
7025: border:solid 1px $lg_border_color;
7026: }
7027:
7028: table.LC_SimpleTable thead {
7029: background:rgb(220,220,220);
7030: }
7031:
7032: div.LC_columnSection {
7033: display: block;
7034: clear: both;
7035: overflow: hidden;
7036: margin: 0;
7037: }
7038:
7039: div.LC_columnSection>* {
7040: float: left;
7041: margin: 10px 20px 10px 0;
7042: overflow:hidden;
7043: }
7044:
7045: table em {
7046: font-weight: bold;
7047: font-style: normal;
7048: }
7049:
7050: table.LC_tableBrowseRes,
7051: table.LC_tableOfContent {
7052: border:none;
7053: border-spacing: 1px;
7054: padding: 3px;
7055: background-color: #FFFFFF;
7056: font-size: 90%;
7057: }
7058:
7059: table.LC_tableOfContent {
7060: border-collapse: collapse;
7061: }
7062:
7063: table.LC_tableBrowseRes a,
7064: table.LC_tableOfContent a {
7065: background-color: transparent;
7066: text-decoration: none;
7067: }
7068:
7069: table.LC_tableOfContent img {
7070: border: none;
7071: height: 1.3em;
7072: vertical-align: text-bottom;
7073: margin-right: 0.3em;
7074: }
7075:
7076: a#LC_content_toolbar_firsthomework {
7077: background-image:url(/res/adm/pages/open-first-problem.gif);
7078: }
7079:
7080: a#LC_content_toolbar_everything {
7081: background-image:url(/res/adm/pages/show-all.gif);
7082: }
7083:
7084: a#LC_content_toolbar_uncompleted {
7085: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7086: }
7087:
7088: #LC_content_toolbar_clearbubbles {
7089: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7090: }
7091:
7092: a#LC_content_toolbar_changefolder {
7093: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7094: }
7095:
7096: a#LC_content_toolbar_changefolder_toggled {
7097: background-image:url(/res/adm/pages/open-all-folders.gif);
7098: }
7099:
7100: a#LC_content_toolbar_edittoplevel {
7101: background-image:url(/res/adm/pages/edittoplevel.gif);
7102: }
7103:
7104: ul#LC_toolbar li a:hover {
7105: background-position: bottom center;
7106: }
7107:
7108: ul#LC_toolbar {
7109: padding: 0;
7110: margin: 2px;
7111: list-style:none;
7112: position:relative;
7113: background-color:white;
7114: overflow: auto;
7115: }
7116:
7117: ul#LC_toolbar li {
7118: border:1px solid white;
7119: padding: 0;
7120: margin: 0;
7121: float: left;
7122: display:inline;
7123: vertical-align:middle;
7124: white-space: nowrap;
7125: }
7126:
7127:
7128: a.LC_toolbarItem {
7129: display:block;
7130: padding: 0;
7131: margin: 0;
7132: height: 32px;
7133: width: 32px;
7134: color:white;
7135: border: none;
7136: background-repeat:no-repeat;
7137: background-color:transparent;
7138: }
7139:
7140: ul.LC_funclist {
7141: margin: 0;
7142: padding: 0.5em 1em 0.5em 0;
7143: }
7144:
7145: ul.LC_funclist > li:first-child {
7146: font-weight:bold;
7147: margin-left:0.8em;
7148: }
7149:
7150: ul.LC_funclist + ul.LC_funclist {
7151: /*
7152: left border as a seperator if we have more than
7153: one list
7154: */
7155: border-left: 1px solid $sidebg;
7156: /*
7157: this hides the left border behind the border of the
7158: outer box if element is wrapped to the next 'line'
7159: */
7160: margin-left: -1px;
7161: }
7162:
7163: ul.LC_funclist li {
7164: display: inline;
7165: white-space: nowrap;
7166: margin: 0 0 0 25px;
7167: line-height: 150%;
7168: }
7169:
7170: .LC_hidden {
7171: display: none;
7172: }
7173:
7174: .LCmodal-overlay {
7175: position:fixed;
7176: top:0;
7177: right:0;
7178: bottom:0;
7179: left:0;
7180: height:100%;
7181: width:100%;
7182: margin:0;
7183: padding:0;
7184: background:#999;
7185: opacity:.75;
7186: filter: alpha(opacity=75);
7187: -moz-opacity: 0.75;
7188: z-index:101;
7189: }
7190:
7191: * html .LCmodal-overlay {
7192: position: absolute;
7193: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7194: }
7195:
7196: .LCmodal-window {
7197: position:fixed;
7198: top:50%;
7199: left:50%;
7200: margin:0;
7201: padding:0;
7202: z-index:102;
7203: }
7204:
7205: * html .LCmodal-window {
7206: position:absolute;
7207: }
7208:
7209: .LCclose-window {
7210: position:absolute;
7211: width:32px;
7212: height:32px;
7213: right:8px;
7214: top:8px;
7215: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7216: text-indent:-99999px;
7217: overflow:hidden;
7218: cursor:pointer;
7219: }
7220:
7221: /*
7222: styles used by TTH when "Default set of options to pass to tth/m
7223: when converting TeX" in course settings has been set
7224:
7225: option passed: -t
7226:
7227: */
7228:
7229: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7230: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7231: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7232: td div.norm {line-height:normal;}
7233:
7234: /*
7235: option passed -y3
7236: */
7237:
7238: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7239: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7240: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7241:
7242: END
7243: }
7244:
7245: =pod
7246:
7247: =item * &headtag()
7248:
7249: Returns a uniform footer for LON-CAPA web pages.
7250:
7251: Inputs: $title - optional title for the head
7252: $head_extra - optional extra HTML to put inside the <head>
7253: $args - optional arguments
7254: force_register - if is true call registerurl so the remote is
7255: informed
7256: redirect -> array ref of
7257: 1- seconds before redirect occurs
7258: 2- url to redirect to
7259: 3- whether the side effect should occur
7260: (side effect of setting
7261: $env{'internal.head.redirect'} to the url
7262: redirected too)
7263: domain -> force to color decorate a page for a specific
7264: domain
7265: function -> force usage of a specific rolish color scheme
7266: bgcolor -> override the default page bgcolor
7267: no_auto_mt_title
7268: -> prevent &mt()ing the title arg
7269:
7270: =cut
7271:
7272: sub headtag {
7273: my ($title,$head_extra,$args) = @_;
7274:
7275: my $function = $args->{'function'} || &get_users_function();
7276: my $domain = $args->{'domain'} || &determinedomain();
7277: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7278: my $httphost = $args->{'use_absolute'};
7279: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7280: $Apache::lonnet::perlvar{'lonVersion'},
7281: #time(),
7282: $env{'environment.color.timestamp'},
7283: $function,$domain,$bgcolor);
7284:
7285: $url = '/adm/css/'.&escape($url).'.css';
7286:
7287: my $result =
7288: '<head>'.
7289: &font_settings($args);
7290:
7291: my $inhibitprint = &print_suppression();
7292:
7293: if (!$args->{'frameset'}) {
7294: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7295: }
7296: if ($args->{'force_register'}) {
7297: $result .= &Apache::lonmenu::registerurl(1);
7298: }
7299: if (!$args->{'no_nav_bar'}
7300: && !$args->{'only_body'}
7301: && !$args->{'frameset'}) {
7302: $result .= &help_menu_js($httphost);
7303: $result.=&modal_window();
7304: $result.=&togglebox_script();
7305: $result.=&wishlist_window();
7306: $result.=&LCprogressbarUpdate_script();
7307: } else {
7308: if ($args->{'add_modal'}) {
7309: $result.=&modal_window();
7310: }
7311: if ($args->{'add_wishlist'}) {
7312: $result.=&wishlist_window();
7313: }
7314: if ($args->{'add_togglebox'}) {
7315: $result.=&togglebox_script();
7316: }
7317: if ($args->{'add_progressbar'}) {
7318: $result.=&LCprogressbarUpdate_script();
7319: }
7320: }
7321: if (ref($args->{'redirect'})) {
7322: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7323: $url = &Apache::lonenc::check_encrypt($url);
7324: if (!$inhibit_continue) {
7325: $env{'internal.head.redirect'} = $url;
7326: }
7327: $result.=<<ADDMETA
7328: <meta http-equiv="pragma" content="no-cache" />
7329: <meta http-equiv="Refresh" content="$time; url=$url" />
7330: ADDMETA
7331: }
7332: if (!defined($title)) {
7333: $title = 'The LearningOnline Network with CAPA';
7334: }
7335: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7336: $result .= '<title> LON-CAPA '.$title.'</title>'
7337: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7338: if (!$args->{'frameset'}) {
7339: $result .= ' /';
7340: }
7341: $result .= '>'
7342: .$inhibitprint
7343: .$head_extra;
7344: if ($env{'browser.mobile'}) {
7345: $result .= '
7346: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7347: <meta name="apple-mobile-web-app-capable" content="yes" />';
7348: }
7349: return $result.'</head>';
7350: }
7351:
7352: =pod
7353:
7354: =item * &font_settings()
7355:
7356: Returns neccessary <meta> to set the proper encoding
7357:
7358: Inputs: optional reference to HASH -- $args passed to &headtag()
7359:
7360: =cut
7361:
7362: sub font_settings {
7363: my ($args) = @_;
7364: my $headerstring='';
7365: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
7366: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
7367: $headerstring.=
7368: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
7369: if (!$args->{'frameset'}) {
7370: $headerstring.= ' /';
7371: }
7372: $headerstring .= '>'."\n";
7373: }
7374: return $headerstring;
7375: }
7376:
7377: =pod
7378:
7379: =item * &print_suppression()
7380:
7381: In course context returns css which causes the body to be blank when media="print",
7382: if printout generation is unavailable for the current resource.
7383:
7384: This could be because:
7385:
7386: (a) printstartdate is in the future
7387:
7388: (b) printenddate is in the past
7389:
7390: (c) there is an active exam block with "printout"
7391: functionality blocked
7392:
7393: Users with pav, pfo or evb privileges are exempt.
7394:
7395: Inputs: none
7396:
7397: =cut
7398:
7399:
7400: sub print_suppression {
7401: my $noprint;
7402: if ($env{'request.course.id'}) {
7403: my $scope = $env{'request.course.id'};
7404: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7405: (&Apache::lonnet::allowed('pfo',$scope))) {
7406: return;
7407: }
7408: if ($env{'request.course.sec'} ne '') {
7409: $scope .= "/$env{'request.course.sec'}";
7410: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7411: (&Apache::lonnet::allowed('pfo',$scope))) {
7412: return;
7413: }
7414: }
7415: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7416: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7417: my $blocked = &blocking_status('printout',$cnum,$cdom);
7418: if ($blocked) {
7419: my $checkrole = "cm./$cdom/$cnum";
7420: if ($env{'request.course.sec'} ne '') {
7421: $checkrole .= "/$env{'request.course.sec'}";
7422: }
7423: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7424: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7425: $noprint = 1;
7426: }
7427: }
7428: unless ($noprint) {
7429: my $symb = &Apache::lonnet::symbread();
7430: if ($symb ne '') {
7431: my $navmap = Apache::lonnavmaps::navmap->new();
7432: if (ref($navmap)) {
7433: my $res = $navmap->getBySymb($symb);
7434: if (ref($res)) {
7435: if (!$res->resprintable()) {
7436: $noprint = 1;
7437: }
7438: }
7439: }
7440: }
7441: }
7442: if ($noprint) {
7443: return <<"ENDSTYLE";
7444: <style type="text/css" media="print">
7445: body { display:none }
7446: </style>
7447: ENDSTYLE
7448: }
7449: }
7450: return;
7451: }
7452:
7453: =pod
7454:
7455: =item * &xml_begin()
7456:
7457: Returns the needed doctype and <html>
7458:
7459: Inputs: none
7460:
7461: =cut
7462:
7463: sub xml_begin {
7464: my ($is_frameset) = @_;
7465: my $output='';
7466:
7467: if ($env{'browser.mathml'}) {
7468: $output='<?xml version="1.0"?>'
7469: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7470: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7471:
7472: # .'<!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">] >'
7473: .'<!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">'
7474: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7475: .'xmlns="http://www.w3.org/1999/xhtml">';
7476: } elsif ($is_frameset) {
7477: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
7478: '<html>'."\n";
7479: } else {
7480: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
7481: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
7482: }
7483: return $output;
7484: }
7485:
7486: =pod
7487:
7488: =item * &start_page()
7489:
7490: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7491:
7492: Inputs:
7493:
7494: =over 4
7495:
7496: $title - optional title for the page
7497:
7498: $head_extra - optional extra HTML to incude inside the <head>
7499:
7500: $args - additional optional args supported are:
7501:
7502: =over 8
7503:
7504: only_body -> is true will set &bodytag() onlybodytag
7505: arg on
7506: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7507: add_entries -> additional attributes to add to the <body>
7508: domain -> force to color decorate a page for a
7509: specific domain
7510: function -> force usage of a specific rolish color
7511: scheme
7512: redirect -> see &headtag()
7513: bgcolor -> override the default page bg color
7514: js_ready -> return a string ready for being used in
7515: a javascript writeln
7516: html_encode -> return a string ready for being used in
7517: a html attribute
7518: force_register -> if is true will turn on the &bodytag()
7519: $forcereg arg
7520: frameset -> if true will start with a <frameset>
7521: rather than <body>
7522: skip_phases -> hash ref of
7523: head -> skip the <html><head> generation
7524: body -> skip all <body> generation
7525: no_inline_link -> if true and in remote mode, don't show the
7526: 'Switch To Inline Menu' link
7527: no_auto_mt_title -> prevent &mt()ing the title arg
7528: inherit_jsmath -> when creating popup window in a page,
7529: should it have jsmath forced on by the
7530: current page
7531: bread_crumbs -> Array containing breadcrumbs
7532: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7533: group -> includes the current group, if page is for a
7534: specific group
7535:
7536: =back
7537:
7538: =back
7539:
7540: =cut
7541:
7542: sub start_page {
7543: my ($title,$head_extra,$args) = @_;
7544: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7545:
7546: $env{'internal.start_page'}++;
7547: my ($result,@advtools);
7548:
7549: if (! exists($args->{'skip_phases'}{'head'}) ) {
7550: $result .= &xml_begin($args->{'frameset') . &headtag($title, $head_extra, $args);
7551: }
7552:
7553: if (! exists($args->{'skip_phases'}{'body'}) ) {
7554: if ($args->{'frameset'}) {
7555: my $attr_string = &make_attr_string($args->{'force_register'},
7556: $args->{'add_entries'});
7557: $result .= "\n<frameset $attr_string>\n";
7558: } else {
7559: $result .=
7560: &bodytag($title,
7561: $args->{'function'}, $args->{'add_entries'},
7562: $args->{'only_body'}, $args->{'domain'},
7563: $args->{'force_register'}, $args->{'no_nav_bar'},
7564: $args->{'bgcolor'}, $args->{'no_inline_link'},
7565: $args, \@advtools);
7566: }
7567: }
7568:
7569: if ($args->{'js_ready'}) {
7570: $result = &js_ready($result);
7571: }
7572: if ($args->{'html_encode'}) {
7573: $result = &html_encode($result);
7574: }
7575:
7576: # Preparation for new and consistent functionlist at top of screen
7577: # if ($args->{'functionlist'}) {
7578: # $result .= &build_functionlist();
7579: #}
7580:
7581: # Don't add anything more if only_body wanted or in const space
7582: return $result if $args->{'only_body'}
7583: || $env{'request.state'} eq 'construct';
7584:
7585: #Breadcrumbs
7586: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7587: &Apache::lonhtmlcommon::clear_breadcrumbs();
7588: #if any br links exists, add them to the breadcrumbs
7589: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7590: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7591: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7592: }
7593: }
7594: # if @advtools array contains items add then to the breadcrumbs
7595: if (@advtools > 0) {
7596: &Apache::lonmenu::advtools_crumbs(@advtools);
7597: }
7598:
7599: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7600: if(exists($args->{'bread_crumbs_component'})){
7601: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7602: }else{
7603: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7604: }
7605: } elsif (($env{'environment.remote'} eq 'on') &&
7606: ($env{'form.inhibitmenu'} ne 'yes') &&
7607: ($env{'request.noversionuri'} =~ m{^/res/}) &&
7608: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
7609: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
7610: }
7611: return $result;
7612: }
7613:
7614: sub end_page {
7615: my ($args) = @_;
7616: $env{'internal.end_page'}++;
7617: my $result;
7618: if ($args->{'discussion'}) {
7619: my ($target,$parser);
7620: if (ref($args->{'discussion'})) {
7621: ($target,$parser) =($args->{'discussion'}{'target'},
7622: $args->{'discussion'}{'parser'});
7623: }
7624: $result .= &Apache::lonxml::xmlend($target,$parser);
7625: }
7626: if ($args->{'frameset'}) {
7627: $result .= '</frameset>';
7628: } else {
7629: $result .= &endbodytag($args);
7630: }
7631: unless ($args->{'notbody'}) {
7632: $result .= "\n</html>";
7633: }
7634:
7635: if ($args->{'js_ready'}) {
7636: $result = &js_ready($result);
7637: }
7638:
7639: if ($args->{'html_encode'}) {
7640: $result = &html_encode($result);
7641: }
7642:
7643: return $result;
7644: }
7645:
7646: sub wishlist_window {
7647: return(<<'ENDWISHLIST');
7648: <script type="text/javascript">
7649: // <![CDATA[
7650: // <!-- BEGIN LON-CAPA Internal
7651: function set_wishlistlink(title, path) {
7652: if (!title) {
7653: title = document.title;
7654: title = title.replace(/^LON-CAPA /,'');
7655: }
7656: if (!path) {
7657: path = location.pathname;
7658: }
7659: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7660: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7661: }
7662: // END LON-CAPA Internal -->
7663: // ]]>
7664: </script>
7665: ENDWISHLIST
7666: }
7667:
7668: sub modal_window {
7669: return(<<'ENDMODAL');
7670: <script type="text/javascript">
7671: // <![CDATA[
7672: // <!-- BEGIN LON-CAPA Internal
7673: var modalWindow = {
7674: parent:"body",
7675: windowId:null,
7676: content:null,
7677: width:null,
7678: height:null,
7679: close:function()
7680: {
7681: $(".LCmodal-window").remove();
7682: $(".LCmodal-overlay").remove();
7683: },
7684: open:function()
7685: {
7686: var modal = "";
7687: modal += "<div class=\"LCmodal-overlay\"></div>";
7688: 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;\">";
7689: modal += this.content;
7690: modal += "</div>";
7691:
7692: $(this.parent).append(modal);
7693:
7694: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7695: $(".LCclose-window").click(function(){modalWindow.close();});
7696: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7697: }
7698: };
7699: var openMyModal = function(source,width,height,scrolling,transparency,style)
7700: {
7701: modalWindow.windowId = "myModal";
7702: modalWindow.width = width;
7703: modalWindow.height = height;
7704: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
7705: modalWindow.open();
7706: };
7707: // END LON-CAPA Internal -->
7708: // ]]>
7709: </script>
7710: ENDMODAL
7711: }
7712:
7713: sub modal_link {
7714: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
7715: unless ($width) { $width=480; }
7716: unless ($height) { $height=400; }
7717: unless ($scrolling) { $scrolling='yes'; }
7718: unless ($transparency) { $transparency='true'; }
7719:
7720: my $target_attr;
7721: if (defined($target)) {
7722: $target_attr = 'target="'.$target.'"';
7723: }
7724: return <<"ENDLINK";
7725: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
7726: $linktext</a>
7727: ENDLINK
7728: }
7729:
7730: sub modal_adhoc_script {
7731: my ($funcname,$width,$height,$content)=@_;
7732: return (<<ENDADHOC);
7733: <script type="text/javascript">
7734: // <![CDATA[
7735: var $funcname = function()
7736: {
7737: modalWindow.windowId = "myModal";
7738: modalWindow.width = $width;
7739: modalWindow.height = $height;
7740: modalWindow.content = '$content';
7741: modalWindow.open();
7742: };
7743: // ]]>
7744: </script>
7745: ENDADHOC
7746: }
7747:
7748: sub modal_adhoc_inner {
7749: my ($funcname,$width,$height,$content)=@_;
7750: my $innerwidth=$width-20;
7751: $content=&js_ready(
7752: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7753: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
7754: $content.
7755: &end_scrollbox().
7756: &end_page()
7757: );
7758: return &modal_adhoc_script($funcname,$width,$height,$content);
7759: }
7760:
7761: sub modal_adhoc_window {
7762: my ($funcname,$width,$height,$content,$linktext)=@_;
7763: return &modal_adhoc_inner($funcname,$width,$height,$content).
7764: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7765: }
7766:
7767: sub modal_adhoc_launch {
7768: my ($funcname,$width,$height,$content)=@_;
7769: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7770: <script type="text/javascript">
7771: // <![CDATA[
7772: $funcname();
7773: // ]]>
7774: </script>
7775: ENDLAUNCH
7776: }
7777:
7778: sub modal_adhoc_close {
7779: return (<<ENDCLOSE);
7780: <script type="text/javascript">
7781: // <![CDATA[
7782: modalWindow.close();
7783: // ]]>
7784: </script>
7785: ENDCLOSE
7786: }
7787:
7788: sub togglebox_script {
7789: return(<<ENDTOGGLE);
7790: <script type="text/javascript">
7791: // <![CDATA[
7792: function LCtoggleDisplay(id,hidetext,showtext) {
7793: link = document.getElementById(id + "link").childNodes[0];
7794: with (document.getElementById(id).style) {
7795: if (display == "none" ) {
7796: display = "inline";
7797: link.nodeValue = hidetext;
7798: } else {
7799: display = "none";
7800: link.nodeValue = showtext;
7801: }
7802: }
7803: }
7804: // ]]>
7805: </script>
7806: ENDTOGGLE
7807: }
7808:
7809: sub start_togglebox {
7810: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7811: unless ($heading) { $heading=''; } else { $heading.=' '; }
7812: unless ($showtext) { $showtext=&mt('show'); }
7813: unless ($hidetext) { $hidetext=&mt('hide'); }
7814: unless ($headerbg) { $headerbg='#FFFFFF'; }
7815: return &start_data_table().
7816: &start_data_table_header_row().
7817: '<td bgcolor="'.$headerbg.'">'.$heading.
7818: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7819: $showtext.'\')">'.$showtext.'</a>]</td>'.
7820: &end_data_table_header_row().
7821: '<tr id="'.$id.'" style="display:none""><td>';
7822: }
7823:
7824: sub end_togglebox {
7825: return '</td></tr>'.&end_data_table();
7826: }
7827:
7828: sub LCprogressbar_script {
7829: my ($id)=@_;
7830: return(<<ENDPROGRESS);
7831: <script type="text/javascript">
7832: // <![CDATA[
7833: \$('#progressbar$id').progressbar({
7834: value: 0,
7835: change: function(event, ui) {
7836: var newVal = \$(this).progressbar('option', 'value');
7837: \$('.pblabel', this).text(LCprogressTxt);
7838: }
7839: });
7840: // ]]>
7841: </script>
7842: ENDPROGRESS
7843: }
7844:
7845: sub LCprogressbarUpdate_script {
7846: return(<<ENDPROGRESSUPDATE);
7847: <style type="text/css">
7848: .ui-progressbar { position:relative; }
7849: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7850: </style>
7851: <script type="text/javascript">
7852: // <![CDATA[
7853: var LCprogressTxt='---';
7854:
7855: function LCupdateProgress(percent,progresstext,id) {
7856: LCprogressTxt=progresstext;
7857: \$('#progressbar'+id).progressbar('value',percent);
7858: }
7859: // ]]>
7860: </script>
7861: ENDPROGRESSUPDATE
7862: }
7863:
7864: my $LClastpercent;
7865: my $LCidcnt;
7866: my $LCcurrentid;
7867:
7868: sub LCprogressbar {
7869: my ($r)=(@_);
7870: $LClastpercent=0;
7871: $LCidcnt++;
7872: $LCcurrentid=$$.'_'.$LCidcnt;
7873: my $starting=&mt('Starting');
7874: my $content=(<<ENDPROGBAR);
7875: <div id="progressbar$LCcurrentid">
7876: <span class="pblabel">$starting</span>
7877: </div>
7878: ENDPROGBAR
7879: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7880: }
7881:
7882: sub LCprogressbarUpdate {
7883: my ($r,$val,$text)=@_;
7884: unless ($val) {
7885: if ($LClastpercent) {
7886: $val=$LClastpercent;
7887: } else {
7888: $val=0;
7889: }
7890: }
7891: if ($val<0) { $val=0; }
7892: if ($val>100) { $val=0; }
7893: $LClastpercent=$val;
7894: unless ($text) { $text=$val.'%'; }
7895: $text=&js_ready($text);
7896: &r_print($r,<<ENDUPDATE);
7897: <script type="text/javascript">
7898: // <![CDATA[
7899: LCupdateProgress($val,'$text','$LCcurrentid');
7900: // ]]>
7901: </script>
7902: ENDUPDATE
7903: }
7904:
7905: sub LCprogressbarClose {
7906: my ($r)=@_;
7907: $LClastpercent=0;
7908: &r_print($r,<<ENDCLOSE);
7909: <script type="text/javascript">
7910: // <![CDATA[
7911: \$("#progressbar$LCcurrentid").hide('slow');
7912: // ]]>
7913: </script>
7914: ENDCLOSE
7915: }
7916:
7917: sub r_print {
7918: my ($r,$to_print)=@_;
7919: if ($r) {
7920: $r->print($to_print);
7921: $r->rflush();
7922: } else {
7923: print($to_print);
7924: }
7925: }
7926:
7927: sub html_encode {
7928: my ($result) = @_;
7929:
7930: $result = &HTML::Entities::encode($result,'<>&"');
7931:
7932: return $result;
7933: }
7934:
7935: sub js_ready {
7936: my ($result) = @_;
7937:
7938: $result =~ s/[\n\r]/ /xmsg;
7939: $result =~ s/\\/\\\\/xmsg;
7940: $result =~ s/'/\\'/xmsg;
7941: $result =~ s{</}{<\\/}xmsg;
7942:
7943: return $result;
7944: }
7945:
7946: sub validate_page {
7947: if ( exists($env{'internal.start_page'})
7948: && $env{'internal.start_page'} > 1) {
7949: &Apache::lonnet::logthis('start_page called multiple times '.
7950: $env{'internal.start_page'}.' '.
7951: $ENV{'request.filename'});
7952: }
7953: if ( exists($env{'internal.end_page'})
7954: && $env{'internal.end_page'} > 1) {
7955: &Apache::lonnet::logthis('end_page called multiple times '.
7956: $env{'internal.end_page'}.' '.
7957: $env{'request.filename'});
7958: }
7959: if ( exists($env{'internal.start_page'})
7960: && ! exists($env{'internal.end_page'})) {
7961: &Apache::lonnet::logthis('start_page called without end_page '.
7962: $env{'request.filename'});
7963: }
7964: if ( ! exists($env{'internal.start_page'})
7965: && exists($env{'internal.end_page'})) {
7966: &Apache::lonnet::logthis('end_page called without start_page'.
7967: $env{'request.filename'});
7968: }
7969: }
7970:
7971:
7972: sub start_scrollbox {
7973: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
7974: unless ($outerwidth) { $outerwidth='520px'; }
7975: unless ($width) { $width='500px'; }
7976: unless ($height) { $height='200px'; }
7977: my ($table_id,$div_id,$tdcol);
7978: if ($id ne '') {
7979: $table_id = ' id="table_'.$id.'"';
7980: $div_id = ' id="div_'.$id.'"';
7981: }
7982: if ($bgcolor ne '') {
7983: $tdcol = "background-color: $bgcolor;";
7984: }
7985: my $nicescroll_js;
7986: if ($env{'browser.mobile'}) {
7987: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
7988: }
7989: return <<"END";
7990: $nicescroll_js
7991:
7992: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
7993: <div style="overflow:auto; width:$width; height:$height;"$div_id>
7994: END
7995: }
7996:
7997: sub end_scrollbox {
7998: return '</div></td></tr></table>';
7999: }
8000:
8001: sub nicescroll_javascript {
8002: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8003: my %options;
8004: if (ref($cursor) eq 'HASH') {
8005: %options = %{$cursor};
8006: }
8007: unless ($options{'railalign'} =~ /^left|right$/) {
8008: $options{'railalign'} = 'left';
8009: }
8010: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8011: my $function = &get_users_function();
8012: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8013: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8014: $options{'cursorcolor'} = '#00F';
8015: }
8016: }
8017: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8018: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8019: $options{'cursoropacity'}='1.0';
8020: }
8021: } else {
8022: $options{'cursoropacity'}='1.0';
8023: }
8024: if ($options{'cursorfixedheight'} eq 'none') {
8025: delete($options{'cursorfixedheight'});
8026: } else {
8027: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8028: }
8029: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8030: delete($options{'railoffset'});
8031: }
8032: my @niceoptions;
8033: while (my($key,$value) = each(%options)) {
8034: if ($value =~ /^\{.+\}$/) {
8035: push(@niceoptions,$key.':'.$value);
8036: } else {
8037: push(@niceoptions,$key.':"'.$value.'"');
8038: }
8039: }
8040: my $nicescroll_js = '
8041: $(document).ready(
8042: function() {
8043: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8044: }
8045: );
8046: ';
8047: if ($framecheck) {
8048: $nicescroll_js .= '
8049: function expand_div(caller) {
8050: if (top === self) {
8051: document.getElementById("'.$id.'").style.width = "auto";
8052: document.getElementById("'.$id.'").style.height = "auto";
8053: } else {
8054: try {
8055: if (parent.frames) {
8056: if (parent.frames.length > 1) {
8057: var framesrc = parent.frames[1].location.href;
8058: var currsrc = framesrc.replace(/\#.*$/,"");
8059: if ((caller == "search") || (currsrc == "'.$location.'")) {
8060: document.getElementById("'.$id.'").style.width = "auto";
8061: document.getElementById("'.$id.'").style.height = "auto";
8062: }
8063: }
8064: }
8065: } catch (e) {
8066: return;
8067: }
8068: }
8069: return;
8070: }
8071: ';
8072: }
8073: if ($needjsready) {
8074: $nicescroll_js = '
8075: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8076: } else {
8077: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8078: }
8079: return $nicescroll_js;
8080: }
8081:
8082: sub simple_error_page {
8083: my ($r,$title,$msg,$args) = @_;
8084: if (ref($args) eq 'HASH') {
8085: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8086: } else {
8087: $msg = &mt($msg);
8088: }
8089:
8090: my $page =
8091: &Apache::loncommon::start_page($title).
8092: '<p class="LC_error">'.$msg.'</p>'.
8093: &Apache::loncommon::end_page();
8094: if (ref($r)) {
8095: $r->print($page);
8096: return;
8097: }
8098: return $page;
8099: }
8100:
8101: {
8102: my @row_count;
8103:
8104: sub start_data_table_count {
8105: unshift(@row_count, 0);
8106: return;
8107: }
8108:
8109: sub end_data_table_count {
8110: shift(@row_count);
8111: return;
8112: }
8113:
8114: sub start_data_table {
8115: my ($add_class,$id) = @_;
8116: my $css_class = (join(' ','LC_data_table',$add_class));
8117: my $table_id;
8118: if (defined($id)) {
8119: $table_id = ' id="'.$id.'"';
8120: }
8121: &start_data_table_count();
8122: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8123: }
8124:
8125: sub end_data_table {
8126: &end_data_table_count();
8127: return '</table>'."\n";;
8128: }
8129:
8130: sub start_data_table_row {
8131: my ($add_class, $id) = @_;
8132: $row_count[0]++;
8133: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8134: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8135: $id = (' id="'.$id.'"') unless ($id eq '');
8136: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8137: }
8138:
8139: sub continue_data_table_row {
8140: my ($add_class, $id) = @_;
8141: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8142: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8143: $id = (' id="'.$id.'"') unless ($id eq '');
8144: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8145: }
8146:
8147: sub end_data_table_row {
8148: return '</tr>'."\n";;
8149: }
8150:
8151: sub start_data_table_empty_row {
8152: # $row_count[0]++;
8153: return '<tr class="LC_empty_row" >'."\n";;
8154: }
8155:
8156: sub end_data_table_empty_row {
8157: return '</tr>'."\n";;
8158: }
8159:
8160: sub start_data_table_header_row {
8161: return '<tr class="LC_header_row">'."\n";;
8162: }
8163:
8164: sub end_data_table_header_row {
8165: return '</tr>'."\n";;
8166: }
8167:
8168: sub data_table_caption {
8169: my $caption = shift;
8170: return "<caption class=\"LC_caption\">$caption</caption>";
8171: }
8172: }
8173:
8174: =pod
8175:
8176: =item * &inhibit_menu_check($arg)
8177:
8178: Checks for a inhibitmenu state and generates output to preserve it
8179:
8180: Inputs: $arg - can be any of
8181: - undef - in which case the return value is a string
8182: to add into arguments list of a uri
8183: - 'input' - in which case the return value is a HTML
8184: <form> <input> field of type hidden to
8185: preserve the value
8186: - a url - in which case the return value is the url with
8187: the neccesary cgi args added to preserve the
8188: inhibitmenu state
8189: - a ref to a url - no return value, but the string is
8190: updated to include the neccessary cgi
8191: args to preserve the inhibitmenu state
8192:
8193: =cut
8194:
8195: sub inhibit_menu_check {
8196: my ($arg) = @_;
8197: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8198: if ($arg eq 'input') {
8199: if ($env{'form.inhibitmenu'}) {
8200: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8201: } else {
8202: return
8203: }
8204: }
8205: if ($env{'form.inhibitmenu'}) {
8206: if (ref($arg)) {
8207: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8208: } elsif ($arg eq '') {
8209: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8210: } else {
8211: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8212: }
8213: }
8214: if (!ref($arg)) {
8215: return $arg;
8216: }
8217: }
8218:
8219: ###############################################
8220:
8221: =pod
8222:
8223: =back
8224:
8225: =head1 User Information Routines
8226:
8227: =over 4
8228:
8229: =item * &get_users_function()
8230:
8231: Used by &bodytag to determine the current users primary role.
8232: Returns either 'student','coordinator','admin', or 'author'.
8233:
8234: =cut
8235:
8236: ###############################################
8237: sub get_users_function {
8238: my $function = 'norole';
8239: if ($env{'request.role'}=~/^(st)/) {
8240: $function='student';
8241: }
8242: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8243: $function='coordinator';
8244: }
8245: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8246: $function='admin';
8247: }
8248: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8249: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8250: $function='author';
8251: }
8252: return $function;
8253: }
8254:
8255: ###############################################
8256:
8257: =pod
8258:
8259: =item * &show_course()
8260:
8261: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8262: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8263:
8264: Inputs:
8265: None
8266:
8267: Outputs:
8268: Scalar: 1 if 'Course' to be used, 0 otherwise.
8269:
8270: =cut
8271:
8272: ###############################################
8273: sub show_course {
8274: my $course = !$env{'user.adv'};
8275: if (!$env{'user.adv'}) {
8276: foreach my $env (keys(%env)) {
8277: next if ($env !~ m/^user\.priv\./);
8278: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8279: $course = 0;
8280: last;
8281: }
8282: }
8283: }
8284: return $course;
8285: }
8286:
8287: ###############################################
8288:
8289: =pod
8290:
8291: =item * &check_user_status()
8292:
8293: Determines current status of supplied role for a
8294: specific user. Roles can be active, previous or future.
8295:
8296: Inputs:
8297: user's domain, user's username, course's domain,
8298: course's number, optional section ID.
8299:
8300: Outputs:
8301: role status: active, previous or future.
8302:
8303: =cut
8304:
8305: sub check_user_status {
8306: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8307: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8308: my @uroles = keys %userinfo;
8309: my $srchstr;
8310: my $active_chk = 'none';
8311: my $now = time;
8312: if (@uroles > 0) {
8313: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8314: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8315: } else {
8316: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8317: }
8318: if (grep/^\Q$srchstr\E$/,@uroles) {
8319: my $role_end = 0;
8320: my $role_start = 0;
8321: $active_chk = 'active';
8322: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8323: $role_end = $1;
8324: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8325: $role_start = $1;
8326: }
8327: }
8328: if ($role_start > 0) {
8329: if ($now < $role_start) {
8330: $active_chk = 'future';
8331: }
8332: }
8333: if ($role_end > 0) {
8334: if ($now > $role_end) {
8335: $active_chk = 'previous';
8336: }
8337: }
8338: }
8339: }
8340: return $active_chk;
8341: }
8342:
8343: ###############################################
8344:
8345: =pod
8346:
8347: =item * &get_sections()
8348:
8349: Determines all the sections for a course including
8350: sections with students and sections containing other roles.
8351: Incoming parameters:
8352:
8353: 1. domain
8354: 2. course number
8355: 3. reference to array containing roles for which sections should
8356: be gathered (optional).
8357: 4. reference to array containing status types for which sections
8358: should be gathered (optional).
8359:
8360: If the third argument is undefined, sections are gathered for any role.
8361: If the fourth argument is undefined, sections are gathered for any status.
8362: Permissible values are 'active' or 'future' or 'previous'.
8363:
8364: Returns section hash (keys are section IDs, values are
8365: number of users in each section), subject to the
8366: optional roles filter, optional status filter
8367:
8368: =cut
8369:
8370: ###############################################
8371: sub get_sections {
8372: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8373: if (!defined($cdom) || !defined($cnum)) {
8374: my $cid = $env{'request.course.id'};
8375:
8376: return if (!defined($cid));
8377:
8378: $cdom = $env{'course.'.$cid.'.domain'};
8379: $cnum = $env{'course.'.$cid.'.num'};
8380: }
8381:
8382: my %sectioncount;
8383: my $now = time;
8384:
8385: my $check_students = 1;
8386: my $only_students = 0;
8387: if (ref($possible_roles) eq 'ARRAY') {
8388: if (grep(/^st$/,@{$possible_roles})) {
8389: if (@{$possible_roles} == 1) {
8390: $only_students = 1;
8391: }
8392: } else {
8393: $check_students = 0;
8394: }
8395: }
8396:
8397: if ($check_students) {
8398: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
8399: my $sec_index = &Apache::loncoursedata::CL_SECTION();
8400: my $status_index = &Apache::loncoursedata::CL_STATUS();
8401: my $start_index = &Apache::loncoursedata::CL_START();
8402: my $end_index = &Apache::loncoursedata::CL_END();
8403: my $status;
8404: while (my ($student,$data) = each(%$classlist)) {
8405: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
8406: $data->[$status_index],
8407: $data->[$start_index],
8408: $data->[$end_index]);
8409: if ($stu_status eq 'Active') {
8410: $status = 'active';
8411: } elsif ($end < $now) {
8412: $status = 'previous';
8413: } elsif ($start > $now) {
8414: $status = 'future';
8415: }
8416: if ($section ne '-1' && $section !~ /^\s*$/) {
8417: if ((!defined($possible_status)) || (($status ne '') &&
8418: (grep/^\Q$status\E$/,@{$possible_status}))) {
8419: $sectioncount{$section}++;
8420: }
8421: }
8422: }
8423: }
8424: if ($only_students) {
8425: return %sectioncount;
8426: }
8427: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8428: foreach my $user (sort(keys(%courseroles))) {
8429: if ($user !~ /^(\w{2})/) { next; }
8430: my ($role) = ($user =~ /^(\w{2})/);
8431: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
8432: my ($section,$status);
8433: if ($role eq 'cr' &&
8434: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
8435: $section=$1;
8436: }
8437: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
8438: if (!defined($section) || $section eq '-1') { next; }
8439: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
8440: if ($end == -1 && $start == -1) {
8441: next; #deleted role
8442: }
8443: if (!defined($possible_status)) {
8444: $sectioncount{$section}++;
8445: } else {
8446: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
8447: $status = 'active';
8448: } elsif ($end < $now) {
8449: $status = 'future';
8450: } elsif ($start > $now) {
8451: $status = 'previous';
8452: }
8453: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
8454: $sectioncount{$section}++;
8455: }
8456: }
8457: }
8458: return %sectioncount;
8459: }
8460:
8461: ###############################################
8462:
8463: =pod
8464:
8465: =item * &get_course_users()
8466:
8467: Retrieves usernames:domains for users in the specified course
8468: with specific role(s), and access status.
8469:
8470: Incoming parameters:
8471: 1. course domain
8472: 2. course number
8473: 3. access status: users must have - either active,
8474: previous, future, or all.
8475: 4. reference to array of permissible roles
8476: 5. reference to array of section restrictions (optional)
8477: 6. reference to results object (hash of hashes).
8478: 7. reference to optional userdata hash
8479: 8. reference to optional statushash
8480: 9. flag if privileged users (except those set to unhide in
8481: course settings) should be excluded
8482: Keys of top level results hash are roles.
8483: Keys of inner hashes are username:domain, with
8484: values set to access type.
8485: Optional userdata hash returns an array with arguments in the
8486: same order as loncoursedata::get_classlist() for student data.
8487:
8488: Optional statushash returns
8489:
8490: Entries for end, start, section and status are blank because
8491: of the possibility of multiple values for non-student roles.
8492:
8493: =cut
8494:
8495: ###############################################
8496:
8497: sub get_course_users {
8498: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
8499: my %idx = ();
8500: my %seclists;
8501:
8502: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
8503: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
8504: $idx{end} = &Apache::loncoursedata::CL_END();
8505: $idx{start} = &Apache::loncoursedata::CL_START();
8506: $idx{id} = &Apache::loncoursedata::CL_ID();
8507: $idx{section} = &Apache::loncoursedata::CL_SECTION();
8508: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
8509: $idx{status} = &Apache::loncoursedata::CL_STATUS();
8510:
8511: if (grep(/^st$/,@{$roles})) {
8512: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
8513: my $now = time;
8514: foreach my $student (keys(%{$classlist})) {
8515: my $match = 0;
8516: my $secmatch = 0;
8517: my $section = $$classlist{$student}[$idx{section}];
8518: my $status = $$classlist{$student}[$idx{status}];
8519: if ($section eq '') {
8520: $section = 'none';
8521: }
8522: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8523: if (grep(/^all$/,@{$sections})) {
8524: $secmatch = 1;
8525: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8526: if (grep(/^none$/,@{$sections})) {
8527: $secmatch = 1;
8528: }
8529: } else {
8530: if (grep(/^\Q$section\E$/,@{$sections})) {
8531: $secmatch = 1;
8532: }
8533: }
8534: if (!$secmatch) {
8535: next;
8536: }
8537: }
8538: if (defined($$types{'active'})) {
8539: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8540: push(@{$$users{st}{$student}},'active');
8541: $match = 1;
8542: }
8543: }
8544: if (defined($$types{'previous'})) {
8545: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8546: push(@{$$users{st}{$student}},'previous');
8547: $match = 1;
8548: }
8549: }
8550: if (defined($$types{'future'})) {
8551: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8552: push(@{$$users{st}{$student}},'future');
8553: $match = 1;
8554: }
8555: }
8556: if ($match) {
8557: push(@{$seclists{$student}},$section);
8558: if (ref($userdata) eq 'HASH') {
8559: $$userdata{$student} = $$classlist{$student};
8560: }
8561: if (ref($statushash) eq 'HASH') {
8562: $statushash->{$student}{'st'}{$section} = $status;
8563: }
8564: }
8565: }
8566: }
8567: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8568: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8569: my $now = time;
8570: my %displaystatus = ( previous => 'Expired',
8571: active => 'Active',
8572: future => 'Future',
8573: );
8574: my (%nothide,@possdoms);
8575: if ($hidepriv) {
8576: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8577: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8578: if ($user !~ /:/) {
8579: $nothide{join(':',split(/[\@]/,$user))}=1;
8580: } else {
8581: $nothide{$user} = 1;
8582: }
8583: }
8584: my @possdoms = ($cdom);
8585: if ($coursehash{'checkforpriv'}) {
8586: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
8587: }
8588: }
8589: foreach my $person (sort(keys(%coursepersonnel))) {
8590: my $match = 0;
8591: my $secmatch = 0;
8592: my $status;
8593: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8594: $user =~ s/:$//;
8595: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8596: if ($end == -1 || $start == -1) {
8597: next;
8598: }
8599: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8600: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8601: my ($uname,$udom) = split(/:/,$user);
8602: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8603: if (grep(/^all$/,@{$sections})) {
8604: $secmatch = 1;
8605: } elsif ($usec eq '') {
8606: if (grep(/^none$/,@{$sections})) {
8607: $secmatch = 1;
8608: }
8609: } else {
8610: if (grep(/^\Q$usec\E$/,@{$sections})) {
8611: $secmatch = 1;
8612: }
8613: }
8614: if (!$secmatch) {
8615: next;
8616: }
8617: }
8618: if ($usec eq '') {
8619: $usec = 'none';
8620: }
8621: if ($uname ne '' && $udom ne '') {
8622: if ($hidepriv) {
8623: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
8624: (!$nothide{$uname.':'.$udom})) {
8625: next;
8626: }
8627: }
8628: if ($end > 0 && $end < $now) {
8629: $status = 'previous';
8630: } elsif ($start > $now) {
8631: $status = 'future';
8632: } else {
8633: $status = 'active';
8634: }
8635: foreach my $type (keys(%{$types})) {
8636: if ($status eq $type) {
8637: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8638: push(@{$$users{$role}{$user}},$type);
8639: }
8640: $match = 1;
8641: }
8642: }
8643: if (($match) && (ref($userdata) eq 'HASH')) {
8644: if (!exists($$userdata{$uname.':'.$udom})) {
8645: &get_user_info($udom,$uname,\%idx,$userdata);
8646: }
8647: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8648: push(@{$seclists{$uname.':'.$udom}},$usec);
8649: }
8650: if (ref($statushash) eq 'HASH') {
8651: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8652: }
8653: }
8654: }
8655: }
8656: }
8657: if (grep(/^ow$/,@{$roles})) {
8658: if ((defined($cdom)) && (defined($cnum))) {
8659: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8660: if ( defined($csettings{'internal.courseowner'}) ) {
8661: my $owner = $csettings{'internal.courseowner'};
8662: next if ($owner eq '');
8663: my ($ownername,$ownerdom);
8664: if ($owner =~ /^([^:]+):([^:]+)$/) {
8665: $ownername = $1;
8666: $ownerdom = $2;
8667: } else {
8668: $ownername = $owner;
8669: $ownerdom = $cdom;
8670: $owner = $ownername.':'.$ownerdom;
8671: }
8672: @{$$users{'ow'}{$owner}} = 'any';
8673: if (defined($userdata) &&
8674: !exists($$userdata{$owner})) {
8675: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8676: if (!grep(/^none$/,@{$seclists{$owner}})) {
8677: push(@{$seclists{$owner}},'none');
8678: }
8679: if (ref($statushash) eq 'HASH') {
8680: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8681: }
8682: }
8683: }
8684: }
8685: }
8686: foreach my $user (keys(%seclists)) {
8687: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8688: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8689: }
8690: }
8691: return;
8692: }
8693:
8694: sub get_user_info {
8695: my ($udom,$uname,$idx,$userdata) = @_;
8696: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8697: &plainname($uname,$udom,'lastname');
8698: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8699: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8700: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8701: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8702: return;
8703: }
8704:
8705: ###############################################
8706:
8707: =pod
8708:
8709: =item * &get_user_quota()
8710:
8711: Retrieves quota assigned for storage of user files.
8712: Default is to report quota for portfolio files.
8713:
8714: Incoming parameters:
8715: 1. user's username
8716: 2. user's domain
8717: 3. quota name - portfolio, author, or course
8718: (if no quota name provided, defaults to portfolio).
8719: 4. crstype - official, unofficial, textbook or community, if quota name is
8720: course
8721:
8722: Returns:
8723: 1. Disk quota (in MB) assigned to student.
8724: 2. (Optional) Type of setting: custom or default
8725: (individually assigned or default for user's
8726: institutional status).
8727: 3. (Optional) - User's institutional status (e.g., faculty, staff
8728: or student - types as defined in localenroll::inst_usertypes
8729: for user's domain, which determines default quota for user.
8730: 4. (Optional) - Default quota which would apply to the user.
8731:
8732: If a value has been stored in the user's environment,
8733: it will return that, otherwise it returns the maximal default
8734: defined for the user's institutional status(es) in the domain.
8735:
8736: =cut
8737:
8738: ###############################################
8739:
8740:
8741: sub get_user_quota {
8742: my ($uname,$udom,$quotaname,$crstype) = @_;
8743: my ($quota,$quotatype,$settingstatus,$defquota);
8744: if (!defined($udom)) {
8745: $udom = $env{'user.domain'};
8746: }
8747: if (!defined($uname)) {
8748: $uname = $env{'user.name'};
8749: }
8750: if (($udom eq '' || $uname eq '') ||
8751: ($udom eq 'public') && ($uname eq 'public')) {
8752: $quota = 0;
8753: $quotatype = 'default';
8754: $defquota = 0;
8755: } else {
8756: my $inststatus;
8757: if ($quotaname eq 'course') {
8758: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
8759: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
8760: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
8761: } else {
8762: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
8763: $quota = $cenv{'internal.uploadquota'};
8764: }
8765: } else {
8766: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8767: if ($quotaname eq 'author') {
8768: $quota = $env{'environment.authorquota'};
8769: } else {
8770: $quota = $env{'environment.portfolioquota'};
8771: }
8772: $inststatus = $env{'environment.inststatus'};
8773: } else {
8774: my %userenv =
8775: &Apache::lonnet::get('environment',['portfolioquota',
8776: 'authorquota','inststatus'],$udom,$uname);
8777: my ($tmp) = keys(%userenv);
8778: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8779: if ($quotaname eq 'author') {
8780: $quota = $userenv{'authorquota'};
8781: } else {
8782: $quota = $userenv{'portfolioquota'};
8783: }
8784: $inststatus = $userenv{'inststatus'};
8785: } else {
8786: undef(%userenv);
8787: }
8788: }
8789: }
8790: if ($quota eq '' || wantarray) {
8791: if ($quotaname eq 'course') {
8792: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
8793: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
8794: ($crstype eq 'community') || ($crstype eq 'textbook')) {
8795: $defquota = $domdefs{$crstype.'quota'};
8796: }
8797: if ($defquota eq '') {
8798: $defquota = 500;
8799: }
8800: } else {
8801: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
8802: }
8803: if ($quota eq '') {
8804: $quota = $defquota;
8805: $quotatype = 'default';
8806: } else {
8807: $quotatype = 'custom';
8808: }
8809: }
8810: }
8811: if (wantarray) {
8812: return ($quota,$quotatype,$settingstatus,$defquota);
8813: } else {
8814: return $quota;
8815: }
8816: }
8817:
8818: ###############################################
8819:
8820: =pod
8821:
8822: =item * &default_quota()
8823:
8824: Retrieves default quota assigned for storage of user portfolio files,
8825: given an (optional) user's institutional status.
8826:
8827: Incoming parameters:
8828:
8829: 1. domain
8830: 2. (Optional) institutional status(es). This is a : separated list of
8831: status types (e.g., faculty, staff, student etc.)
8832: which apply to the user for whom the default is being retrieved.
8833: If the institutional status string in undefined, the domain
8834: default quota will be returned.
8835: 3. quota name - portfolio, author, or course
8836: (if no quota name provided, defaults to portfolio).
8837:
8838: Returns:
8839:
8840: 1. Default disk quota (in MB) for user portfolios in the domain.
8841: 2. (Optional) institutional type which determined the value of the
8842: default quota.
8843:
8844: If a value has been stored in the domain's configuration db,
8845: it will return that, otherwise it returns 20 (for backwards
8846: compatibility with domains which have not set up a configuration
8847: db file; the original statically defined portfolio quota was 20 MB).
8848:
8849: If the user's status includes multiple types (e.g., staff and student),
8850: the largest default quota which applies to the user determines the
8851: default quota returned.
8852:
8853: =cut
8854:
8855: ###############################################
8856:
8857:
8858: sub default_quota {
8859: my ($udom,$inststatus,$quotaname) = @_;
8860: my ($defquota,$settingstatus);
8861: my %quotahash = &Apache::lonnet::get_dom('configuration',
8862: ['quotas'],$udom);
8863: my $key = 'defaultquota';
8864: if ($quotaname eq 'author') {
8865: $key = 'authorquota';
8866: }
8867: if (ref($quotahash{'quotas'}) eq 'HASH') {
8868: if ($inststatus ne '') {
8869: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8870: foreach my $item (@statuses) {
8871: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8872: if ($quotahash{'quotas'}{$key}{$item} ne '') {
8873: if ($defquota eq '') {
8874: $defquota = $quotahash{'quotas'}{$key}{$item};
8875: $settingstatus = $item;
8876: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
8877: $defquota = $quotahash{'quotas'}{$key}{$item};
8878: $settingstatus = $item;
8879: }
8880: }
8881: } elsif ($key eq 'defaultquota') {
8882: if ($quotahash{'quotas'}{$item} ne '') {
8883: if ($defquota eq '') {
8884: $defquota = $quotahash{'quotas'}{$item};
8885: $settingstatus = $item;
8886: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8887: $defquota = $quotahash{'quotas'}{$item};
8888: $settingstatus = $item;
8889: }
8890: }
8891: }
8892: }
8893: }
8894: if ($defquota eq '') {
8895: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8896: $defquota = $quotahash{'quotas'}{$key}{'default'};
8897: } elsif ($key eq 'defaultquota') {
8898: $defquota = $quotahash{'quotas'}{'default'};
8899: }
8900: $settingstatus = 'default';
8901: if ($defquota eq '') {
8902: if ($quotaname eq 'author') {
8903: $defquota = 500;
8904: }
8905: }
8906: }
8907: } else {
8908: $settingstatus = 'default';
8909: if ($quotaname eq 'author') {
8910: $defquota = 500;
8911: } else {
8912: $defquota = 20;
8913: }
8914: }
8915: if (wantarray) {
8916: return ($defquota,$settingstatus);
8917: } else {
8918: return $defquota;
8919: }
8920: }
8921:
8922: ###############################################
8923:
8924: =pod
8925:
8926: =item * &excess_filesize_warning()
8927:
8928: Returns warning message if upload of file to authoring space, or copying
8929: of existing file within authoring space will cause quota for the authoring
8930: space to be exceeded.
8931:
8932: Same, if upload of a file directly to a course/community via Course Editor
8933: will cause quota for uploaded content for the course to be exceeded.
8934:
8935: Inputs: 7
8936: 1. username or coursenum
8937: 2. domain
8938: 3. context ('author' or 'course')
8939: 4. filename of file for which action is being requested
8940: 5. filesize (kB) of file
8941: 6. action being taken: copy or upload.
8942: 7. quotatype (in course context -- official, unofficial, community or textbook).
8943:
8944: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
8945: otherwise return null.
8946:
8947: =back
8948:
8949: =cut
8950:
8951: sub excess_filesize_warning {
8952: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
8953: my $current_disk_usage = 0;
8954: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
8955: if ($context eq 'author') {
8956: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
8957: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
8958: } else {
8959: foreach my $subdir ('docs','supplemental') {
8960: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
8961: }
8962: }
8963: $disk_quota = int($disk_quota * 1000);
8964: if (($current_disk_usage + $filesize) > $disk_quota) {
8965: return '<p><span class="LC_warning">'.
8966: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
8967: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
8968: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
8969: $disk_quota,$current_disk_usage).
8970: '</p>';
8971: }
8972: return;
8973: }
8974:
8975: ###############################################
8976:
8977:
8978: sub get_secgrprole_info {
8979: my ($cdom,$cnum,$needroles,$type) = @_;
8980: my %sections_count = &get_sections($cdom,$cnum);
8981: my @sections = (sort {$a <=> $b} keys(%sections_count));
8982: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8983: my @groups = sort(keys(%curr_groups));
8984: my $allroles = [];
8985: my $rolehash;
8986: my $accesshash = {
8987: active => 'Currently has access',
8988: future => 'Will have future access',
8989: previous => 'Previously had access',
8990: };
8991: if ($needroles) {
8992: $rolehash = {'all' => 'all'};
8993: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8994: if (&Apache::lonnet::error(%user_roles)) {
8995: undef(%user_roles);
8996: }
8997: foreach my $item (keys(%user_roles)) {
8998: my ($role)=split(/\:/,$item,2);
8999: if ($role eq 'cr') { next; }
9000: if ($role =~ /^cr/) {
9001: $$rolehash{$role} = (split('/',$role))[3];
9002: } else {
9003: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9004: }
9005: }
9006: foreach my $key (sort(keys(%{$rolehash}))) {
9007: push(@{$allroles},$key);
9008: }
9009: push (@{$allroles},'st');
9010: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9011: }
9012: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9013: }
9014:
9015: sub user_picker {
9016: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
9017: my $currdom = $dom;
9018: my %curr_selected = (
9019: srchin => 'dom',
9020: srchby => 'lastname',
9021: );
9022: my $srchterm;
9023: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9024: if ($srch->{'srchby'} ne '') {
9025: $curr_selected{'srchby'} = $srch->{'srchby'};
9026: }
9027: if ($srch->{'srchin'} ne '') {
9028: $curr_selected{'srchin'} = $srch->{'srchin'};
9029: }
9030: if ($srch->{'srchtype'} ne '') {
9031: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9032: }
9033: if ($srch->{'srchdomain'} ne '') {
9034: $currdom = $srch->{'srchdomain'};
9035: }
9036: $srchterm = $srch->{'srchterm'};
9037: }
9038: my %lt=&Apache::lonlocal::texthash(
9039: 'usr' => 'Search criteria',
9040: 'doma' => 'Domain/institution to search',
9041: 'uname' => 'username',
9042: 'lastname' => 'last name',
9043: 'lastfirst' => 'last name, first name',
9044: 'crs' => 'in this course',
9045: 'dom' => 'in selected LON-CAPA domain',
9046: 'alc' => 'all LON-CAPA',
9047: 'instd' => 'in institutional directory for selected domain',
9048: 'exact' => 'is',
9049: 'contains' => 'contains',
9050: 'begins' => 'begins with',
9051: 'youm' => "You must include some text to search for.",
9052: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9053: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9054: 'yomc' => "You must choose a domain when using an institutional directory search.",
9055: 'ymcd' => "You must choose a domain when using a domain search.",
9056: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9057: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9058: 'thfo' => "The following need to be corrected before the search can be run:",
9059: );
9060: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
9061: my $srchinsel = ' <select name="srchin">';
9062:
9063: my @srchins = ('crs','dom','alc','instd');
9064:
9065: foreach my $option (@srchins) {
9066: # FIXME 'alc' option unavailable until
9067: # loncreateuser::print_user_query_page()
9068: # has been completed.
9069: next if ($option eq 'alc');
9070: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9071: next if ($option eq 'crs' && !$env{'request.course.id'});
9072: if ($curr_selected{'srchin'} eq $option) {
9073: $srchinsel .= '
9074: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9075: } else {
9076: $srchinsel .= '
9077: <option value="'.$option.'">'.$lt{$option}.'</option>';
9078: }
9079: }
9080: $srchinsel .= "\n </select>\n";
9081:
9082: my $srchbysel = ' <select name="srchby">';
9083: foreach my $option ('lastname','lastfirst','uname') {
9084: if ($curr_selected{'srchby'} eq $option) {
9085: $srchbysel .= '
9086: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9087: } else {
9088: $srchbysel .= '
9089: <option value="'.$option.'">'.$lt{$option}.'</option>';
9090: }
9091: }
9092: $srchbysel .= "\n </select>\n";
9093:
9094: my $srchtypesel = ' <select name="srchtype">';
9095: foreach my $option ('begins','contains','exact') {
9096: if ($curr_selected{'srchtype'} eq $option) {
9097: $srchtypesel .= '
9098: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9099: } else {
9100: $srchtypesel .= '
9101: <option value="'.$option.'">'.$lt{$option}.'</option>';
9102: }
9103: }
9104: $srchtypesel .= "\n </select>\n";
9105:
9106: my ($newuserscript,$new_user_create);
9107: my $context_dom = $env{'request.role.domain'};
9108: if ($context eq 'requestcrs') {
9109: if ($env{'form.coursedom'} ne '') {
9110: $context_dom = $env{'form.coursedom'};
9111: }
9112: }
9113: if ($forcenewuser) {
9114: if (ref($srch) eq 'HASH') {
9115: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9116: if ($cancreate) {
9117: $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>';
9118: } else {
9119: my $helplink = 'javascript:helpMenu('."'display'".')';
9120: my %usertypetext = (
9121: official => 'institutional',
9122: unofficial => 'non-institutional',
9123: );
9124: $new_user_create = '<p class="LC_warning">'
9125: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9126: .' '
9127: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9128: ,'<a href="'.$helplink.'">','</a>')
9129: .'</p><br />';
9130: }
9131: }
9132: }
9133:
9134: $newuserscript = <<"ENDSCRIPT";
9135:
9136: function setSearch(createnew,callingForm) {
9137: if (createnew == 1) {
9138: for (var i=0; i<callingForm.srchby.length; i++) {
9139: if (callingForm.srchby.options[i].value == 'uname') {
9140: callingForm.srchby.selectedIndex = i;
9141: }
9142: }
9143: for (var i=0; i<callingForm.srchin.length; i++) {
9144: if ( callingForm.srchin.options[i].value == 'dom') {
9145: callingForm.srchin.selectedIndex = i;
9146: }
9147: }
9148: for (var i=0; i<callingForm.srchtype.length; i++) {
9149: if (callingForm.srchtype.options[i].value == 'exact') {
9150: callingForm.srchtype.selectedIndex = i;
9151: }
9152: }
9153: for (var i=0; i<callingForm.srchdomain.length; i++) {
9154: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9155: callingForm.srchdomain.selectedIndex = i;
9156: }
9157: }
9158: }
9159: }
9160: ENDSCRIPT
9161:
9162: }
9163:
9164: my $output = <<"END_BLOCK";
9165: <script type="text/javascript">
9166: // <![CDATA[
9167: function validateEntry(callingForm) {
9168:
9169: var checkok = 1;
9170: var srchin;
9171: for (var i=0; i<callingForm.srchin.length; i++) {
9172: if ( callingForm.srchin[i].checked ) {
9173: srchin = callingForm.srchin[i].value;
9174: }
9175: }
9176:
9177: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9178: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9179: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9180: var srchterm = callingForm.srchterm.value;
9181: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9182: var msg = "";
9183:
9184: if (srchterm == "") {
9185: checkok = 0;
9186: msg += "$lt{'youm'}\\n";
9187: }
9188:
9189: if (srchtype== 'begins') {
9190: if (srchterm.length < 2) {
9191: checkok = 0;
9192: msg += "$lt{'thte'}\\n";
9193: }
9194: }
9195:
9196: if (srchtype== 'contains') {
9197: if (srchterm.length < 3) {
9198: checkok = 0;
9199: msg += "$lt{'thet'}\\n";
9200: }
9201: }
9202: if (srchin == 'instd') {
9203: if (srchdomain == '') {
9204: checkok = 0;
9205: msg += "$lt{'yomc'}\\n";
9206: }
9207: }
9208: if (srchin == 'dom') {
9209: if (srchdomain == '') {
9210: checkok = 0;
9211: msg += "$lt{'ymcd'}\\n";
9212: }
9213: }
9214: if (srchby == 'lastfirst') {
9215: if (srchterm.indexOf(",") == -1) {
9216: checkok = 0;
9217: msg += "$lt{'whus'}\\n";
9218: }
9219: if (srchterm.indexOf(",") == srchterm.length -1) {
9220: checkok = 0;
9221: msg += "$lt{'whse'}\\n";
9222: }
9223: }
9224: if (checkok == 0) {
9225: alert("$lt{'thfo'}\\n"+msg);
9226: return;
9227: }
9228: if (checkok == 1) {
9229: callingForm.submit();
9230: }
9231: }
9232:
9233: $newuserscript
9234:
9235: // ]]>
9236: </script>
9237:
9238: $new_user_create
9239:
9240: END_BLOCK
9241:
9242: $output .= &Apache::lonhtmlcommon::start_pick_box().
9243: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
9244: $domform.
9245: &Apache::lonhtmlcommon::row_closure().
9246: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
9247: $srchbysel.
9248: $srchtypesel.
9249: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9250: $srchinsel.
9251: &Apache::lonhtmlcommon::row_closure(1).
9252: &Apache::lonhtmlcommon::end_pick_box().
9253: '<br />';
9254: return $output;
9255: }
9256:
9257: sub user_rule_check {
9258: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9259: my $response;
9260: if (ref($usershash) eq 'HASH') {
9261: foreach my $user (keys(%{$usershash})) {
9262: my ($uname,$udom) = split(/:/,$user);
9263: next if ($udom eq '' || $uname eq '');
9264: my ($id,$newuser);
9265: if (ref($usershash->{$user}) eq 'HASH') {
9266: $newuser = $usershash->{$user}->{'newuser'};
9267: $id = $usershash->{$user}->{'id'};
9268: }
9269: my $inst_response;
9270: if (ref($checks) eq 'HASH') {
9271: if (defined($checks->{'username'})) {
9272: ($inst_response,%{$inst_results->{$user}}) =
9273: &Apache::lonnet::get_instuser($udom,$uname);
9274: } elsif (defined($checks->{'id'})) {
9275: ($inst_response,%{$inst_results->{$user}}) =
9276: &Apache::lonnet::get_instuser($udom,undef,$id);
9277: }
9278: } else {
9279: ($inst_response,%{$inst_results->{$user}}) =
9280: &Apache::lonnet::get_instuser($udom,$uname);
9281: return;
9282: }
9283: if (!$got_rules->{$udom}) {
9284: my %domconfig = &Apache::lonnet::get_dom('configuration',
9285: ['usercreation'],$udom);
9286: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9287: foreach my $item ('username','id') {
9288: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9289: $$curr_rules{$udom}{$item} =
9290: $domconfig{'usercreation'}{$item.'_rule'};
9291: }
9292: }
9293: }
9294: $got_rules->{$udom} = 1;
9295: }
9296: foreach my $item (keys(%{$checks})) {
9297: if (ref($$curr_rules{$udom}) eq 'HASH') {
9298: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
9299: if (@{$$curr_rules{$udom}{$item}} > 0) {
9300: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
9301: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
9302: if ($rule_check{$rule}) {
9303: $$rulematch{$user}{$item} = $rule;
9304: if ($inst_response eq 'ok') {
9305: if (ref($inst_results) eq 'HASH') {
9306: if (ref($inst_results->{$user}) eq 'HASH') {
9307: if (keys(%{$inst_results->{$user}}) == 0) {
9308: $$alerts{$item}{$udom}{$uname} = 1;
9309: }
9310: }
9311: }
9312: }
9313: last;
9314: }
9315: }
9316: }
9317: }
9318: }
9319: }
9320: }
9321: }
9322: return;
9323: }
9324:
9325: sub user_rule_formats {
9326: my ($domain,$domdesc,$curr_rules,$check) = @_;
9327: my %text = (
9328: 'username' => 'Usernames',
9329: 'id' => 'IDs',
9330: );
9331: my $output;
9332: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
9333: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
9334: if (@{$ruleorder} > 0) {
9335: $output = '<br />'.
9336: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
9337: '<span class="LC_cusr_emph">','</span>',$domdesc).
9338: ' <ul>';
9339: foreach my $rule (@{$ruleorder}) {
9340: if (ref($curr_rules) eq 'ARRAY') {
9341: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
9342: if (ref($rules->{$rule}) eq 'HASH') {
9343: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
9344: $rules->{$rule}{'desc'}.'</li>';
9345: }
9346: }
9347: }
9348: }
9349: $output .= '</ul>';
9350: }
9351: }
9352: return $output;
9353: }
9354:
9355: sub instrule_disallow_msg {
9356: my ($checkitem,$domdesc,$count,$mode) = @_;
9357: my $response;
9358: my %text = (
9359: item => 'username',
9360: items => 'usernames',
9361: match => 'matches',
9362: do => 'does',
9363: action => 'a username',
9364: one => 'one',
9365: );
9366: if ($count > 1) {
9367: $text{'item'} = 'usernames';
9368: $text{'match'} ='match';
9369: $text{'do'} = 'do';
9370: $text{'action'} = 'usernames',
9371: $text{'one'} = 'ones';
9372: }
9373: if ($checkitem eq 'id') {
9374: $text{'items'} = 'IDs';
9375: $text{'item'} = 'ID';
9376: $text{'action'} = 'an ID';
9377: if ($count > 1) {
9378: $text{'item'} = 'IDs';
9379: $text{'action'} = 'IDs';
9380: }
9381: }
9382: $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 />';
9383: if ($mode eq 'upload') {
9384: if ($checkitem eq 'username') {
9385: $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'}.");
9386: } elsif ($checkitem eq 'id') {
9387: $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.");
9388: }
9389: } elsif ($mode eq 'selfcreate') {
9390: if ($checkitem eq 'id') {
9391: $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.");
9392: }
9393: } else {
9394: if ($checkitem eq 'username') {
9395: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
9396: } elsif ($checkitem eq 'id') {
9397: $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.");
9398: }
9399: }
9400: return $response;
9401: }
9402:
9403: sub personal_data_fieldtitles {
9404: my %fieldtitles = &Apache::lonlocal::texthash (
9405: id => 'Student/Employee ID',
9406: permanentemail => 'E-mail address',
9407: lastname => 'Last Name',
9408: firstname => 'First Name',
9409: middlename => 'Middle Name',
9410: generation => 'Generation',
9411: gen => 'Generation',
9412: inststatus => 'Affiliation',
9413: );
9414: return %fieldtitles;
9415: }
9416:
9417: sub sorted_inst_types {
9418: my ($dom) = @_;
9419: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
9420: my $othertitle = &mt('All users');
9421: if ($env{'request.course.id'}) {
9422: $othertitle = &mt('Any users');
9423: }
9424: my @types;
9425: if (ref($order) eq 'ARRAY') {
9426: @types = @{$order};
9427: }
9428: if (@types == 0) {
9429: if (ref($usertypes) eq 'HASH') {
9430: @types = sort(keys(%{$usertypes}));
9431: }
9432: }
9433: if (keys(%{$usertypes}) > 0) {
9434: $othertitle = &mt('Other users');
9435: }
9436: return ($othertitle,$usertypes,\@types);
9437: }
9438:
9439: sub get_institutional_codes {
9440: my ($settings,$allcourses,$LC_code) = @_;
9441: # Get complete list of course sections to update
9442: my @currsections = ();
9443: my @currxlists = ();
9444: my $coursecode = $$settings{'internal.coursecode'};
9445:
9446: if ($$settings{'internal.sectionnums'} ne '') {
9447: @currsections = split(/,/,$$settings{'internal.sectionnums'});
9448: }
9449:
9450: if ($$settings{'internal.crosslistings'} ne '') {
9451: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
9452: }
9453:
9454: if (@currxlists > 0) {
9455: foreach (@currxlists) {
9456: if (m/^([^:]+):(\w*)$/) {
9457: unless (grep/^$1$/,@{$allcourses}) {
9458: push @{$allcourses},$1;
9459: $$LC_code{$1} = $2;
9460: }
9461: }
9462: }
9463: }
9464:
9465: if (@currsections > 0) {
9466: foreach (@currsections) {
9467: if (m/^(\w+):(\w*)$/) {
9468: my $sec = $coursecode.$1;
9469: my $lc_sec = $2;
9470: unless (grep/^$sec$/,@{$allcourses}) {
9471: push @{$allcourses},$sec;
9472: $$LC_code{$sec} = $lc_sec;
9473: }
9474: }
9475: }
9476: }
9477: return;
9478: }
9479:
9480: sub get_standard_codeitems {
9481: return ('Year','Semester','Department','Number','Section');
9482: }
9483:
9484: =pod
9485:
9486: =head1 Slot Helpers
9487:
9488: =over 4
9489:
9490: =item * sorted_slots()
9491:
9492: Sorts an array of slot names in order of an optional sort key,
9493: default sort is by slot start time (earliest first).
9494:
9495: Inputs:
9496:
9497: =over 4
9498:
9499: slotsarr - Reference to array of unsorted slot names.
9500:
9501: slots - Reference to hash of hash, where outer hash keys are slot names.
9502:
9503: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
9504:
9505: =back
9506:
9507: Returns:
9508:
9509: =over 4
9510:
9511: sorted - An array of slot names sorted by a specified sort key
9512: (default sort key is start time of the slot).
9513:
9514: =back
9515:
9516: =cut
9517:
9518:
9519: sub sorted_slots {
9520: my ($slotsarr,$slots,$sortkey) = @_;
9521: if ($sortkey eq '') {
9522: $sortkey = 'starttime';
9523: }
9524: my @sorted;
9525: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
9526: @sorted =
9527: sort {
9528: if (ref($slots->{$a}) && ref($slots->{$b})) {
9529: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
9530: }
9531: if (ref($slots->{$a})) { return -1;}
9532: if (ref($slots->{$b})) { return 1;}
9533: return 0;
9534: } @{$slotsarr};
9535: }
9536: return @sorted;
9537: }
9538:
9539: =pod
9540:
9541: =item * get_future_slots()
9542:
9543: Inputs:
9544:
9545: =over 4
9546:
9547: cnum - course number
9548:
9549: cdom - course domain
9550:
9551: now - current UNIX time
9552:
9553: symb - optional symb
9554:
9555: =back
9556:
9557: Returns:
9558:
9559: =over 4
9560:
9561: sorted_reservable - ref to array of student_schedulable slots currently
9562: reservable, ordered by end date of reservation period.
9563:
9564: reservable_now - ref to hash of student_schedulable slots currently
9565: reservable.
9566:
9567: Keys in inner hash are:
9568: (a) symb: either blank or symb to which slot use is restricted.
9569: (b) endreserve: end date of reservation period.
9570:
9571: sorted_future - ref to array of student_schedulable slots reservable in
9572: the future, ordered by start date of reservation period.
9573:
9574: future_reservable - ref to hash of student_schedulable slots reservable
9575: in the future.
9576:
9577: Keys in inner hash are:
9578: (a) symb: either blank or symb to which slot use is restricted.
9579: (b) startreserve: start date of reservation period.
9580:
9581: =back
9582:
9583: =cut
9584:
9585: sub get_future_slots {
9586: my ($cnum,$cdom,$now,$symb) = @_;
9587: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
9588: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
9589: foreach my $slot (keys(%slots)) {
9590: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
9591: if ($symb) {
9592: next if (($slots{$slot}->{'symb'} ne '') &&
9593: ($slots{$slot}->{'symb'} ne $symb));
9594: }
9595: if (($slots{$slot}->{'starttime'} > $now) &&
9596: ($slots{$slot}->{'endtime'} > $now)) {
9597: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
9598: my $userallowed = 0;
9599: if ($slots{$slot}->{'allowedsections'}) {
9600: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
9601: if (!defined($env{'request.role.sec'})
9602: && grep(/^No section assigned$/,@allowed_sec)) {
9603: $userallowed=1;
9604: } else {
9605: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
9606: $userallowed=1;
9607: }
9608: }
9609: unless ($userallowed) {
9610: if (defined($env{'request.course.groups'})) {
9611: my @groups = split(/:/,$env{'request.course.groups'});
9612: foreach my $group (@groups) {
9613: if (grep(/^\Q$group\E$/,@allowed_sec)) {
9614: $userallowed=1;
9615: last;
9616: }
9617: }
9618: }
9619: }
9620: }
9621: if ($slots{$slot}->{'allowedusers'}) {
9622: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
9623: my $user = $env{'user.name'}.':'.$env{'user.domain'};
9624: if (grep(/^\Q$user\E$/,@allowed_users)) {
9625: $userallowed = 1;
9626: }
9627: }
9628: next unless($userallowed);
9629: }
9630: my $startreserve = $slots{$slot}->{'startreserve'};
9631: my $endreserve = $slots{$slot}->{'endreserve'};
9632: my $symb = $slots{$slot}->{'symb'};
9633: if (($startreserve < $now) &&
9634: (!$endreserve || $endreserve > $now)) {
9635: my $lastres = $endreserve;
9636: if (!$lastres) {
9637: $lastres = $slots{$slot}->{'starttime'};
9638: }
9639: $reservable_now{$slot} = {
9640: symb => $symb,
9641: endreserve => $lastres
9642: };
9643: } elsif (($startreserve > $now) &&
9644: (!$endreserve || $endreserve > $startreserve)) {
9645: $future_reservable{$slot} = {
9646: symb => $symb,
9647: startreserve => $startreserve
9648: };
9649: }
9650: }
9651: }
9652: my @unsorted_reservable = keys(%reservable_now);
9653: if (@unsorted_reservable > 0) {
9654: @sorted_reservable =
9655: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9656: }
9657: my @unsorted_future = keys(%future_reservable);
9658: if (@unsorted_future > 0) {
9659: @sorted_future =
9660: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9661: }
9662: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9663: }
9664:
9665: =pod
9666:
9667: =back
9668:
9669: =head1 HTTP Helpers
9670:
9671: =over 4
9672:
9673: =item * &get_unprocessed_cgi($query,$possible_names)
9674:
9675: Modify the %env hash to contain unprocessed CGI form parameters held in
9676: $query. The parameters listed in $possible_names (an array reference),
9677: will be set in $env{'form.name'} if they do not already exist.
9678:
9679: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9680: $possible_names is an ref to an array of form element names. As an example:
9681: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9682: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9683:
9684: =cut
9685:
9686: sub get_unprocessed_cgi {
9687: my ($query,$possible_names)= @_;
9688: # $Apache::lonxml::debug=1;
9689: foreach my $pair (split(/&/,$query)) {
9690: my ($name, $value) = split(/=/,$pair);
9691: $name = &unescape($name);
9692: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9693: $value =~ tr/+/ /;
9694: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9695: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9696: }
9697: }
9698: }
9699:
9700: =pod
9701:
9702: =item * &cacheheader()
9703:
9704: returns cache-controlling header code
9705:
9706: =cut
9707:
9708: sub cacheheader {
9709: unless ($env{'request.method'} eq 'GET') { return ''; }
9710: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9711: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9712: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9713: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9714: return $output;
9715: }
9716:
9717: =pod
9718:
9719: =item * &no_cache($r)
9720:
9721: specifies header code to not have cache
9722:
9723: =cut
9724:
9725: sub no_cache {
9726: my ($r) = @_;
9727: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9728: $env{'request.method'} ne 'GET') { return ''; }
9729: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9730: $r->no_cache(1);
9731: $r->header_out("Expires" => $date);
9732: $r->header_out("Pragma" => "no-cache");
9733: }
9734:
9735: sub content_type {
9736: my ($r,$type,$charset) = @_;
9737: if ($r) {
9738: # Note that printout.pl calls this with undef for $r.
9739: &no_cache($r);
9740: }
9741: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9742: unless ($charset) {
9743: $charset=&Apache::lonlocal::current_encoding;
9744: }
9745: if ($charset) { $type.='; charset='.$charset; }
9746: if ($r) {
9747: $r->content_type($type);
9748: } else {
9749: print("Content-type: $type\n\n");
9750: }
9751: }
9752:
9753: =pod
9754:
9755: =item * &add_to_env($name,$value)
9756:
9757: adds $name to the %env hash with value
9758: $value, if $name already exists, the entry is converted to an array
9759: reference and $value is added to the array.
9760:
9761: =cut
9762:
9763: sub add_to_env {
9764: my ($name,$value)=@_;
9765: if (defined($env{$name})) {
9766: if (ref($env{$name})) {
9767: #already have multiple values
9768: push(@{ $env{$name} },$value);
9769: } else {
9770: #first time seeing multiple values, convert hash entry to an arrayref
9771: my $first=$env{$name};
9772: undef($env{$name});
9773: push(@{ $env{$name} },$first,$value);
9774: }
9775: } else {
9776: $env{$name}=$value;
9777: }
9778: }
9779:
9780: =pod
9781:
9782: =item * &get_env_multiple($name)
9783:
9784: gets $name from the %env hash, it seemlessly handles the cases where multiple
9785: values may be defined and end up as an array ref.
9786:
9787: returns an array of values
9788:
9789: =cut
9790:
9791: sub get_env_multiple {
9792: my ($name) = @_;
9793: my @values;
9794: if (defined($env{$name})) {
9795: # exists is it an array
9796: if (ref($env{$name})) {
9797: @values=@{ $env{$name} };
9798: } else {
9799: $values[0]=$env{$name};
9800: }
9801: }
9802: return(@values);
9803: }
9804:
9805: sub ask_for_embedded_content {
9806: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9807: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
9808: %currsubfile,%unused,$rem);
9809: my $counter = 0;
9810: my $numnew = 0;
9811: my $numremref = 0;
9812: my $numinvalid = 0;
9813: my $numpathchg = 0;
9814: my $numexisting = 0;
9815: my $numunused = 0;
9816: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
9817: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
9818: my $heading = &mt('Upload embedded files');
9819: my $buttontext = &mt('Upload');
9820:
9821: if ($env{'request.course.id'}) {
9822: if ($actionurl eq '/adm/dependencies') {
9823: $navmap = Apache::lonnavmaps::navmap->new();
9824: }
9825: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9826: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9827: }
9828: if (($actionurl eq '/adm/portfolio') ||
9829: ($actionurl eq '/adm/coursegrp_portfolio')) {
9830: my $current_path='/';
9831: if ($env{'form.currentpath'}) {
9832: $current_path = $env{'form.currentpath'};
9833: }
9834: if ($actionurl eq '/adm/coursegrp_portfolio') {
9835: $udom = $cdom;
9836: $uname = $cnum;
9837: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9838: } else {
9839: $udom = $env{'user.domain'};
9840: $uname = $env{'user.name'};
9841: $url = '/userfiles/portfolio';
9842: }
9843: $toplevel = $url.'/';
9844: $url .= $current_path;
9845: $getpropath = 1;
9846: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9847: ($actionurl eq '/adm/imsimport')) {
9848: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9849: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9850: $toplevel = $url;
9851: if ($rest ne '') {
9852: $url .= $rest;
9853: }
9854: } elsif ($actionurl eq '/adm/coursedocs') {
9855: if (ref($args) eq 'HASH') {
9856: $url = $args->{'docs_url'};
9857: $toplevel = $url;
9858: if ($args->{'context'} eq 'paste') {
9859: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
9860: ($path) =
9861: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9862: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9863: $fileloc =~ s{^/}{};
9864: }
9865: }
9866: } elsif ($actionurl eq '/adm/dependencies') {
9867: if ($env{'request.course.id'} ne '') {
9868: if (ref($args) eq 'HASH') {
9869: $url = $args->{'docs_url'};
9870: $title = $args->{'docs_title'};
9871: $toplevel = $url;
9872: unless ($toplevel =~ m{^/}) {
9873: $toplevel = "/$url";
9874: }
9875: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
9876: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
9877: $path = $1;
9878: } else {
9879: ($path) =
9880: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9881: }
9882: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9883: $fileloc =~ s{^/}{};
9884: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
9885: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
9886: }
9887: }
9888: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9889: $udom = $cdom;
9890: $uname = $cnum;
9891: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
9892: $toplevel = $url;
9893: $path = $url;
9894: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
9895: $fileloc =~ s{^/}{};
9896: }
9897: foreach my $file (keys(%{$allfiles})) {
9898: my $embed_file;
9899: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
9900: $embed_file = $1;
9901: } else {
9902: $embed_file = $file;
9903: }
9904: my ($absolutepath,$cleaned_file);
9905: if ($embed_file =~ m{^\w+://}) {
9906: $cleaned_file = $embed_file;
9907: $newfiles{$cleaned_file} = 1;
9908: $mapping{$cleaned_file} = $embed_file;
9909: } else {
9910: $cleaned_file = &clean_path($embed_file);
9911: if ($embed_file =~ m{^/}) {
9912: $absolutepath = $embed_file;
9913: }
9914: if ($cleaned_file =~ m{/}) {
9915: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
9916: $path = &check_for_traversal($path,$url,$toplevel);
9917: my $item = $fname;
9918: if ($path ne '') {
9919: $item = $path.'/'.$fname;
9920: $subdependencies{$path}{$fname} = 1;
9921: } else {
9922: $dependencies{$item} = 1;
9923: }
9924: if ($absolutepath) {
9925: $mapping{$item} = $absolutepath;
9926: } else {
9927: $mapping{$item} = $embed_file;
9928: }
9929: } else {
9930: $dependencies{$embed_file} = 1;
9931: if ($absolutepath) {
9932: $mapping{$cleaned_file} = $absolutepath;
9933: } else {
9934: $mapping{$cleaned_file} = $embed_file;
9935: }
9936: }
9937: }
9938: }
9939: my $dirptr = 16384;
9940: foreach my $path (keys(%subdependencies)) {
9941: $currsubfile{$path} = {};
9942: if (($actionurl eq '/adm/portfolio') ||
9943: ($actionurl eq '/adm/coursegrp_portfolio')) {
9944: my ($sublistref,$listerror) =
9945: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9946: if (ref($sublistref) eq 'ARRAY') {
9947: foreach my $line (@{$sublistref}) {
9948: my ($file_name,$rest) = split(/\&/,$line,2);
9949: $currsubfile{$path}{$file_name} = 1;
9950: }
9951: }
9952: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9953: if (opendir(my $dir,$url.'/'.$path)) {
9954: my @subdir_list = grep(!/^\./,readdir($dir));
9955: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
9956: }
9957: } elsif (($actionurl eq '/adm/dependencies') ||
9958: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9959: ($args->{'context'} eq 'paste')) ||
9960: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
9961: if ($env{'request.course.id'} ne '') {
9962: my $dir;
9963: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9964: $dir = $fileloc;
9965: } else {
9966: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9967: }
9968: if ($dir ne '') {
9969: my ($sublistref,$listerror) =
9970: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
9971: if (ref($sublistref) eq 'ARRAY') {
9972: foreach my $line (@{$sublistref}) {
9973: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
9974: undef,$mtime)=split(/\&/,$line,12);
9975: unless (($testdir&$dirptr) ||
9976: ($file_name =~ /^\.\.?$/)) {
9977: $currsubfile{$path}{$file_name} = [$size,$mtime];
9978: }
9979: }
9980: }
9981: }
9982: }
9983: }
9984: foreach my $file (keys(%{$subdependencies{$path}})) {
9985: if (exists($currsubfile{$path}{$file})) {
9986: my $item = $path.'/'.$file;
9987: unless ($mapping{$item} eq $item) {
9988: $pathchanges{$item} = 1;
9989: }
9990: $existing{$item} = 1;
9991: $numexisting ++;
9992: } else {
9993: $newfiles{$path.'/'.$file} = 1;
9994: }
9995: }
9996: if ($actionurl eq '/adm/dependencies') {
9997: foreach my $path (keys(%currsubfile)) {
9998: if (ref($currsubfile{$path}) eq 'HASH') {
9999: foreach my $file (keys(%{$currsubfile{$path}})) {
10000: unless ($subdependencies{$path}{$file}) {
10001: next if (($rem ne '') &&
10002: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10003: (ref($navmap) &&
10004: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10005: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10006: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10007: $unused{$path.'/'.$file} = 1;
10008: }
10009: }
10010: }
10011: }
10012: }
10013: }
10014: my %currfile;
10015: if (($actionurl eq '/adm/portfolio') ||
10016: ($actionurl eq '/adm/coursegrp_portfolio')) {
10017: my ($dirlistref,$listerror) =
10018: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10019: if (ref($dirlistref) eq 'ARRAY') {
10020: foreach my $line (@{$dirlistref}) {
10021: my ($file_name,$rest) = split(/\&/,$line,2);
10022: $currfile{$file_name} = 1;
10023: }
10024: }
10025: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10026: if (opendir(my $dir,$url)) {
10027: my @dir_list = grep(!/^\./,readdir($dir));
10028: map {$currfile{$_} = 1;} @dir_list;
10029: }
10030: } elsif (($actionurl eq '/adm/dependencies') ||
10031: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10032: ($args->{'context'} eq 'paste')) ||
10033: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10034: if ($env{'request.course.id'} ne '') {
10035: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10036: if ($dir ne '') {
10037: my ($dirlistref,$listerror) =
10038: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10039: if (ref($dirlistref) eq 'ARRAY') {
10040: foreach my $line (@{$dirlistref}) {
10041: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10042: $size,undef,$mtime)=split(/\&/,$line,12);
10043: unless (($testdir&$dirptr) ||
10044: ($file_name =~ /^\.\.?$/)) {
10045: $currfile{$file_name} = [$size,$mtime];
10046: }
10047: }
10048: }
10049: }
10050: }
10051: }
10052: foreach my $file (keys(%dependencies)) {
10053: if (exists($currfile{$file})) {
10054: unless ($mapping{$file} eq $file) {
10055: $pathchanges{$file} = 1;
10056: }
10057: $existing{$file} = 1;
10058: $numexisting ++;
10059: } else {
10060: $newfiles{$file} = 1;
10061: }
10062: }
10063: foreach my $file (keys(%currfile)) {
10064: unless (($file eq $filename) ||
10065: ($file eq $filename.'.bak') ||
10066: ($dependencies{$file})) {
10067: if ($actionurl eq '/adm/dependencies') {
10068: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10069: next if (($rem ne '') &&
10070: (($env{"httpref.$rem".$file} ne '') ||
10071: (ref($navmap) &&
10072: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10073: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10074: ($navmap->getResourceByUrl($rem.$1)))))));
10075: }
10076: }
10077: $unused{$file} = 1;
10078: }
10079: }
10080: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10081: ($args->{'context'} eq 'paste')) {
10082: $counter = scalar(keys(%existing));
10083: $numpathchg = scalar(keys(%pathchanges));
10084: return ($output,$counter,$numpathchg,\%existing);
10085: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10086: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10087: $counter = scalar(keys(%existing));
10088: $numpathchg = scalar(keys(%pathchanges));
10089: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10090: }
10091: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10092: if ($actionurl eq '/adm/dependencies') {
10093: next if ($embed_file =~ m{^\w+://});
10094: }
10095: $upload_output .= &start_data_table_row().
10096: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10097: '<span class="LC_filename">'.$embed_file.'</span>';
10098: unless ($mapping{$embed_file} eq $embed_file) {
10099: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10100: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10101: }
10102: $upload_output .= '</td>';
10103: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10104: $upload_output.='<td align="right">'.
10105: '<span class="LC_info LC_fontsize_medium">'.
10106: &mt("URL points to web address").'</span>';
10107: $numremref++;
10108: } elsif ($args->{'error_on_invalid_names'}
10109: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10110: $upload_output.='<td align="right"><span class="LC_warning">'.
10111: &mt('Invalid characters').'</span>';
10112: $numinvalid++;
10113: } else {
10114: $upload_output .= '<td>'.
10115: &embedded_file_element('upload_embedded',$counter,
10116: $embed_file,\%mapping,
10117: $allfiles,$codebase,'upload');
10118: $counter ++;
10119: $numnew ++;
10120: }
10121: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10122: }
10123: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10124: if ($actionurl eq '/adm/dependencies') {
10125: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10126: $modify_output .= &start_data_table_row().
10127: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10128: '<img src="'.&icon($embed_file).'" border="0" />'.
10129: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10130: '<td>'.$size.'</td>'.
10131: '<td>'.$mtime.'</td>'.
10132: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10133: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10134: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10135: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10136: &embedded_file_element('upload_embedded',$counter,
10137: $embed_file,\%mapping,
10138: $allfiles,$codebase,'modify').
10139: '</div></td>'.
10140: &end_data_table_row()."\n";
10141: $counter ++;
10142: } else {
10143: $upload_output .= &start_data_table_row().
10144: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10145: '<span class="LC_filename">'.$embed_file.'</span></td>'.
10146: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10147: &Apache::loncommon::end_data_table_row()."\n";
10148: }
10149: }
10150: my $delidx = $counter;
10151: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10152: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10153: $delete_output .= &start_data_table_row().
10154: '<td><img src="'.&icon($oldfile).'" />'.
10155: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
10156: '<td>'.$size.'</td>'.
10157: '<td>'.$mtime.'</td>'.
10158: '<td><label><input type="checkbox" name="del_upload_dep" '.
10159: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10160: &embedded_file_element('upload_embedded',$delidx,
10161: $oldfile,\%mapping,$allfiles,
10162: $codebase,'delete').'</td>'.
10163: &end_data_table_row()."\n";
10164: $numunused ++;
10165: $delidx ++;
10166: }
10167: if ($upload_output) {
10168: $upload_output = &start_data_table().
10169: $upload_output.
10170: &end_data_table()."\n";
10171: }
10172: if ($modify_output) {
10173: $modify_output = &start_data_table().
10174: &start_data_table_header_row().
10175: '<th>'.&mt('File').'</th>'.
10176: '<th>'.&mt('Size (KB)').'</th>'.
10177: '<th>'.&mt('Modified').'</th>'.
10178: '<th>'.&mt('Upload replacement?').'</th>'.
10179: &end_data_table_header_row().
10180: $modify_output.
10181: &end_data_table()."\n";
10182: }
10183: if ($delete_output) {
10184: $delete_output = &start_data_table().
10185: &start_data_table_header_row().
10186: '<th>'.&mt('File').'</th>'.
10187: '<th>'.&mt('Size (KB)').'</th>'.
10188: '<th>'.&mt('Modified').'</th>'.
10189: '<th>'.&mt('Delete?').'</th>'.
10190: &end_data_table_header_row().
10191: $delete_output.
10192: &end_data_table()."\n";
10193: }
10194: my $applies = 0;
10195: if ($numremref) {
10196: $applies ++;
10197: }
10198: if ($numinvalid) {
10199: $applies ++;
10200: }
10201: if ($numexisting) {
10202: $applies ++;
10203: }
10204: if ($counter || $numunused) {
10205: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10206: ' method="post" enctype="multipart/form-data">'."\n".
10207: $state.'<h3>'.$heading.'</h3>';
10208: if ($actionurl eq '/adm/dependencies') {
10209: if ($numnew) {
10210: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10211: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10212: $upload_output.'<br />'."\n";
10213: }
10214: if ($numexisting) {
10215: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10216: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10217: $modify_output.'<br />'."\n";
10218: $buttontext = &mt('Save changes');
10219: }
10220: if ($numunused) {
10221: $output .= '<h4>'.&mt('Unused files').'</h4>'.
10222: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10223: $delete_output.'<br />'."\n";
10224: $buttontext = &mt('Save changes');
10225: }
10226: } else {
10227: $output .= $upload_output.'<br />'."\n";
10228: }
10229: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10230: $counter.'" />'."\n";
10231: if ($actionurl eq '/adm/dependencies') {
10232: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10233: $numnew.'" />'."\n";
10234: } elsif ($actionurl eq '') {
10235: $output .= '<input type="hidden" name="phase" value="three" />';
10236: }
10237: } elsif ($applies) {
10238: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10239: if ($applies > 1) {
10240: $output .=
10241: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10242: if ($numremref) {
10243: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10244: }
10245: if ($numinvalid) {
10246: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10247: }
10248: if ($numexisting) {
10249: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10250: }
10251: $output .= '</ul><br />';
10252: } elsif ($numremref) {
10253: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10254: } elsif ($numinvalid) {
10255: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10256: } elsif ($numexisting) {
10257: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10258: }
10259: $output .= $upload_output.'<br />';
10260: }
10261: my ($pathchange_output,$chgcount);
10262: $chgcount = $counter;
10263: if (keys(%pathchanges) > 0) {
10264: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10265: if ($counter) {
10266: $output .= &embedded_file_element('pathchange',$chgcount,
10267: $embed_file,\%mapping,
10268: $allfiles,$codebase,'change');
10269: } else {
10270: $pathchange_output .=
10271: &start_data_table_row().
10272: '<td><input type ="checkbox" name="namechange" value="'.
10273: $chgcount.'" checked="checked" /></td>'.
10274: '<td>'.$mapping{$embed_file}.'</td>'.
10275: '<td>'.$embed_file.
10276: &embedded_file_element('pathchange',$numpathchg,$embed_file,
10277: \%mapping,$allfiles,$codebase,'change').
10278: '</td>'.&end_data_table_row();
10279: }
10280: $numpathchg ++;
10281: $chgcount ++;
10282: }
10283: }
10284: if (($counter) || ($numunused)) {
10285: if ($numpathchg) {
10286: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10287: $numpathchg.'" />'."\n";
10288: }
10289: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10290: ($actionurl eq '/adm/imsimport')) {
10291: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10292: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10293: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10294: } elsif ($actionurl eq '/adm/dependencies') {
10295: $output .= '<input type="hidden" name="action" value="process_changes" />';
10296: }
10297: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10298: } elsif ($numpathchg) {
10299: my %pathchange = ();
10300: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10301: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10302: $output .= '<p>'.&mt('or').'</p>';
10303: }
10304: }
10305: return ($output,$counter,$numpathchg);
10306: }
10307:
10308: =pod
10309:
10310: =item * clean_path($name)
10311:
10312: Performs clean-up of directories, subdirectories and filename in an
10313: embedded object, referenced in an HTML file which is being uploaded
10314: to a course or portfolio, where
10315: "Upload embedded images/multimedia files if HTML file" checkbox was
10316: checked.
10317:
10318: Clean-up is similar to replacements in lonnet::clean_filename()
10319: except each / between sub-directory and next level is preserved.
10320:
10321: =cut
10322:
10323: sub clean_path {
10324: my ($embed_file) = @_;
10325: $embed_file =~s{^/+}{};
10326: my @contents;
10327: if ($embed_file =~ m{/}) {
10328: @contents = split(/\//,$embed_file);
10329: } else {
10330: @contents = ($embed_file);
10331: }
10332: my $lastidx = scalar(@contents)-1;
10333: for (my $i=0; $i<=$lastidx; $i++) {
10334: $contents[$i]=~s{\\}{/}g;
10335: $contents[$i]=~s/\s+/\_/g;
10336: $contents[$i]=~s{[^/\w\.\-]}{}g;
10337: if ($i == $lastidx) {
10338: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10339: }
10340: }
10341: if ($lastidx > 0) {
10342: return join('/',@contents);
10343: } else {
10344: return $contents[0];
10345: }
10346: }
10347:
10348: sub embedded_file_element {
10349: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10350: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10351: (ref($codebase) eq 'HASH'));
10352: my $output;
10353: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10354: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10355: }
10356: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10357: &escape($embed_file).'" />';
10358: unless (($context eq 'upload_embedded') &&
10359: ($mapping->{$embed_file} eq $embed_file)) {
10360: $output .='
10361: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10362: }
10363: my $attrib;
10364: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10365: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10366: }
10367: $output .=
10368: "\n\t\t".
10369: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10370: $attrib.'" />';
10371: if (exists($codebase->{$mapping->{$embed_file}})) {
10372: $output .=
10373: "\n\t\t".
10374: '<input name="codebase_'.$num.'" type="hidden" value="'.
10375: &escape($codebase->{$mapping->{$embed_file}}).'" />';
10376: }
10377: return $output;
10378: }
10379:
10380: sub get_dependency_details {
10381: my ($currfile,$currsubfile,$embed_file) = @_;
10382: my ($size,$mtime,$showsize,$showmtime);
10383: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10384: if ($embed_file =~ m{/}) {
10385: my ($path,$fname) = split(/\//,$embed_file);
10386: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10387: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10388: }
10389: } else {
10390: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10391: ($size,$mtime) = @{$currfile->{$embed_file}};
10392: }
10393: }
10394: $showsize = $size/1024.0;
10395: $showsize = sprintf("%.1f",$showsize);
10396: if ($mtime > 0) {
10397: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10398: }
10399: }
10400: return ($showsize,$showmtime);
10401: }
10402:
10403: sub ask_embedded_js {
10404: return <<"END";
10405: <script type="text/javascript"">
10406: // <![CDATA[
10407: function toggleBrowse(counter) {
10408: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10409: var fileid = document.getElementById('embedded_item_'+counter);
10410: var uploaddivid = document.getElementById('moduploaddep_'+counter);
10411: if (chkboxid.checked == true) {
10412: uploaddivid.style.display='block';
10413: } else {
10414: uploaddivid.style.display='none';
10415: fileid.value = '';
10416: }
10417: }
10418: // ]]>
10419: </script>
10420:
10421: END
10422: }
10423:
10424: sub upload_embedded {
10425: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10426: $current_disk_usage,$hiddenstate,$actionurl) = @_;
10427: my (%pathchange,$output,$modifyform,$footer,$returnflag);
10428: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10429: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10430: my $orig_uploaded_filename =
10431: $env{'form.embedded_item_'.$i.'.filename'};
10432: foreach my $type ('orig','ref','attrib','codebase') {
10433: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10434: $env{'form.embedded_'.$type.'_'.$i} =
10435: &unescape($env{'form.embedded_'.$type.'_'.$i});
10436: }
10437: }
10438: my ($path,$fname) =
10439: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10440: # no path, whole string is fname
10441: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10442: $fname = &Apache::lonnet::clean_filename($fname);
10443: # See if there is anything left
10444: next if ($fname eq '');
10445:
10446: # Check if file already exists as a file or directory.
10447: my ($state,$msg);
10448: if ($context eq 'portfolio') {
10449: my $port_path = $dirpath;
10450: if ($group ne '') {
10451: $port_path = "groups/$group/$port_path";
10452: }
10453: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10454: $fname,$group,'embedded_item_'.$i,
10455: $dir_root,$port_path,$disk_quota,
10456: $current_disk_usage,$uname,$udom);
10457: if ($state eq 'will_exceed_quota'
10458: || $state eq 'file_locked') {
10459: $output .= $msg;
10460: next;
10461: }
10462: } elsif (($context eq 'author') || ($context eq 'testbank')) {
10463: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10464: if ($state eq 'exists') {
10465: $output .= $msg;
10466: next;
10467: }
10468: }
10469: # Check if extension is valid
10470: if (($fname =~ /\.(\w+)$/) &&
10471: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10472: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10473: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10474: next;
10475: } elsif (($fname =~ /\.(\w+)$/) &&
10476: (!defined(&Apache::loncommon::fileembstyle($1)))) {
10477: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10478: next;
10479: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10480: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10481: next;
10482: }
10483: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10484: my $subdir = $path;
10485: $subdir =~ s{/+$}{};
10486: if ($context eq 'portfolio') {
10487: my $result;
10488: if ($state eq 'existingfile') {
10489: $result=
10490: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10491: $dirpath.$env{'form.currentpath'}.$subdir);
10492: } else {
10493: $result=
10494: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10495: $dirpath.
10496: $env{'form.currentpath'}.$subdir);
10497: if ($result !~ m|^/uploaded/|) {
10498: $output .= '<span class="LC_error">'
10499: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10500: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10501: .'</span><br />';
10502: next;
10503: } else {
10504: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10505: $path.$fname.'</span>').'<br />';
10506: }
10507: }
10508: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10509: my $extendedsubdir = $dirpath.'/'.$subdir;
10510: $extendedsubdir =~ s{/+$}{};
10511: my $result =
10512: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10513: if ($result !~ m|^/uploaded/|) {
10514: $output .= '<span class="LC_error">'
10515: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10516: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10517: .'</span><br />';
10518: next;
10519: } else {
10520: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10521: $path.$fname.'</span>').'<br />';
10522: if ($context eq 'syllabus') {
10523: &Apache::lonnet::make_public_indefinitely($result);
10524: }
10525: }
10526: } else {
10527: # Save the file
10528: my $target = $env{'form.embedded_item_'.$i};
10529: my $fullpath = $dir_root.$dirpath.'/'.$path;
10530: my $dest = $fullpath.$fname;
10531: my $url = $url_root.$dirpath.'/'.$path.$fname;
10532: my @parts=split(/\//,"$dirpath/$path");
10533: my $count;
10534: my $filepath = $dir_root;
10535: foreach my $subdir (@parts) {
10536: $filepath .= "/$subdir";
10537: if (!-e $filepath) {
10538: mkdir($filepath,0770);
10539: }
10540: }
10541: my $fh;
10542: if (!open($fh,'>'.$dest)) {
10543: &Apache::lonnet::logthis('Failed to create '.$dest);
10544: $output .= '<span class="LC_error">'.
10545: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10546: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10547: '</span><br />';
10548: } else {
10549: if (!print $fh $env{'form.embedded_item_'.$i}) {
10550: &Apache::lonnet::logthis('Failed to write to '.$dest);
10551: $output .= '<span class="LC_error">'.
10552: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10553: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10554: '</span><br />';
10555: } else {
10556: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10557: $url.'</span>').'<br />';
10558: unless ($context eq 'testbank') {
10559: $footer .= &mt('View embedded file: [_1]',
10560: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10561: }
10562: }
10563: close($fh);
10564: }
10565: }
10566: if ($env{'form.embedded_ref_'.$i}) {
10567: $pathchange{$i} = 1;
10568: }
10569: }
10570: if ($output) {
10571: $output = '<p>'.$output.'</p>';
10572: }
10573: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10574: $returnflag = 'ok';
10575: my $numpathchgs = scalar(keys(%pathchange));
10576: if ($numpathchgs > 0) {
10577: if ($context eq 'portfolio') {
10578: $output .= '<p>'.&mt('or').'</p>';
10579: } elsif ($context eq 'testbank') {
10580: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10581: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10582: $returnflag = 'modify_orightml';
10583: }
10584: }
10585: return ($output.$footer,$returnflag,$numpathchgs);
10586: }
10587:
10588: sub modify_html_form {
10589: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10590: my $end = 0;
10591: my $modifyform;
10592: if ($context eq 'upload_embedded') {
10593: return unless (ref($pathchange) eq 'HASH');
10594: if ($env{'form.number_embedded_items'}) {
10595: $end += $env{'form.number_embedded_items'};
10596: }
10597: if ($env{'form.number_pathchange_items'}) {
10598: $end += $env{'form.number_pathchange_items'};
10599: }
10600: if ($end) {
10601: for (my $i=0; $i<$end; $i++) {
10602: if ($i < $env{'form.number_embedded_items'}) {
10603: next unless($pathchange->{$i});
10604: }
10605: $modifyform .=
10606: &start_data_table_row().
10607: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10608: 'checked="checked" /></td>'.
10609: '<td>'.$env{'form.embedded_ref_'.$i}.
10610: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10611: &escape($env{'form.embedded_ref_'.$i}).'" />'.
10612: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10613: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10614: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10615: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10616: '<td>'.$env{'form.embedded_orig_'.$i}.
10617: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10618: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10619: &end_data_table_row();
10620: }
10621: }
10622: } else {
10623: $modifyform = $pathchgtable;
10624: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10625: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10626: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10627: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10628: }
10629: }
10630: if ($modifyform) {
10631: if ($actionurl eq '/adm/dependencies') {
10632: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10633: }
10634: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10635: '<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".
10636: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10637: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10638: '</ol></p>'."\n".'<p>'.
10639: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10640: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10641: &start_data_table()."\n".
10642: &start_data_table_header_row().
10643: '<th>'.&mt('Change?').'</th>'.
10644: '<th>'.&mt('Current reference').'</th>'.
10645: '<th>'.&mt('Required reference').'</th>'.
10646: &end_data_table_header_row()."\n".
10647: $modifyform.
10648: &end_data_table().'<br />'."\n".$hiddenstate.
10649: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10650: '</form>'."\n";
10651: }
10652: return;
10653: }
10654:
10655: sub modify_html_refs {
10656: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10657: my $container;
10658: if ($context eq 'portfolio') {
10659: $container = $env{'form.container'};
10660: } elsif ($context eq 'coursedoc') {
10661: $container = $env{'form.primaryurl'};
10662: } elsif ($context eq 'manage_dependencies') {
10663: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10664: $container = "/$container";
10665: } elsif ($context eq 'syllabus') {
10666: $container = $url;
10667: } else {
10668: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10669: }
10670: my (%allfiles,%codebase,$output,$content);
10671: my @changes = &get_env_multiple('form.namechange');
10672: unless ((@changes > 0) || ($context eq 'syllabus')) {
10673: if (wantarray) {
10674: return ('',0,0);
10675: } else {
10676: return;
10677: }
10678: }
10679: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10680: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10681: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10682: if (wantarray) {
10683: return ('',0,0);
10684: } else {
10685: return;
10686: }
10687: }
10688: $content = &Apache::lonnet::getfile($container);
10689: if ($content eq '-1') {
10690: if (wantarray) {
10691: return ('',0,0);
10692: } else {
10693: return;
10694: }
10695: }
10696: } else {
10697: unless ($container =~ /^\Q$dir_root\E/) {
10698: if (wantarray) {
10699: return ('',0,0);
10700: } else {
10701: return;
10702: }
10703: }
10704: if (open(my $fh,"<$container")) {
10705: $content = join('', <$fh>);
10706: close($fh);
10707: } else {
10708: if (wantarray) {
10709: return ('',0,0);
10710: } else {
10711: return;
10712: }
10713: }
10714: }
10715: my ($count,$codebasecount) = (0,0);
10716: my $mm = new File::MMagic;
10717: my $mime_type = $mm->checktype_contents($content);
10718: if ($mime_type eq 'text/html') {
10719: my $parse_result =
10720: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10721: \%codebase,\$content);
10722: if ($parse_result eq 'ok') {
10723: foreach my $i (@changes) {
10724: my $orig = &unescape($env{'form.embedded_orig_'.$i});
10725: my $ref = &unescape($env{'form.embedded_ref_'.$i});
10726: if ($allfiles{$ref}) {
10727: my $newname = $orig;
10728: my ($attrib_regexp,$codebase);
10729: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10730: if ($attrib_regexp =~ /:/) {
10731: $attrib_regexp =~ s/\:/|/g;
10732: }
10733: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10734: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10735: $count += $numchg;
10736: $allfiles{$newname} = $allfiles{$ref};
10737: delete($allfiles{$ref});
10738: }
10739: if ($env{'form.embedded_codebase_'.$i} ne '') {
10740: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10741: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10742: $codebasecount ++;
10743: }
10744: }
10745: }
10746: my $skiprewrites;
10747: if ($count || $codebasecount) {
10748: my $saveresult;
10749: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10750: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10751: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10752: if ($url eq $container) {
10753: my ($fname) = ($container =~ m{/([^/]+)$});
10754: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10755: $count,'<span class="LC_filename">'.
10756: $fname.'</span>').'</p>';
10757: } else {
10758: $output = '<p class="LC_error">'.
10759: &mt('Error: update failed for: [_1].',
10760: '<span class="LC_filename">'.
10761: $container.'</span>').'</p>';
10762: }
10763: if ($context eq 'syllabus') {
10764: unless ($saveresult eq 'ok') {
10765: $skiprewrites = 1;
10766: }
10767: }
10768: } else {
10769: if (open(my $fh,">$container")) {
10770: print $fh $content;
10771: close($fh);
10772: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10773: $count,'<span class="LC_filename">'.
10774: $container.'</span>').'</p>';
10775: } else {
10776: $output = '<p class="LC_error">'.
10777: &mt('Error: could not update [_1].',
10778: '<span class="LC_filename">'.
10779: $container.'</span>').'</p>';
10780: }
10781: }
10782: }
10783: if (($context eq 'syllabus') && (!$skiprewrites)) {
10784: my ($actionurl,$state);
10785: $actionurl = "/public/$udom/$uname/syllabus";
10786: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10787: &ask_for_embedded_content($actionurl,$state,\%allfiles,
10788: \%codebase,
10789: {'context' => 'rewrites',
10790: 'ignore_remote_references' => 1,});
10791: if (ref($mapping) eq 'HASH') {
10792: my $rewrites = 0;
10793: foreach my $key (keys(%{$mapping})) {
10794: next if ($key =~ m{^https?://});
10795: my $ref = $mapping->{$key};
10796: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10797: my $attrib;
10798: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10799: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10800: }
10801: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10802: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10803: $rewrites += $numchg;
10804: }
10805: }
10806: if ($rewrites) {
10807: my $saveresult;
10808: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10809: if ($url eq $container) {
10810: my ($fname) = ($container =~ m{/([^/]+)$});
10811: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10812: $count,'<span class="LC_filename">'.
10813: $fname.'</span>').'</p>';
10814: } else {
10815: $output .= '<p class="LC_error">'.
10816: &mt('Error: could not update links in [_1].',
10817: '<span class="LC_filename">'.
10818: $container.'</span>').'</p>';
10819:
10820: }
10821: }
10822: }
10823: }
10824: } else {
10825: &logthis('Failed to parse '.$container.
10826: ' to modify references: '.$parse_result);
10827: }
10828: }
10829: if (wantarray) {
10830: return ($output,$count,$codebasecount);
10831: } else {
10832: return $output;
10833: }
10834: }
10835:
10836: sub check_for_existing {
10837: my ($path,$fname,$element) = @_;
10838: my ($state,$msg);
10839: if (-d $path.'/'.$fname) {
10840: $state = 'exists';
10841: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10842: } elsif (-e $path.'/'.$fname) {
10843: $state = 'exists';
10844: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10845: }
10846: if ($state eq 'exists') {
10847: $msg = '<span class="LC_error">'.$msg.'</span><br />';
10848: }
10849: return ($state,$msg);
10850: }
10851:
10852: sub check_for_upload {
10853: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10854: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10855: my $filesize = length($env{'form.'.$element});
10856: if (!$filesize) {
10857: my $msg = '<span class="LC_error">'.
10858: &mt('Unable to upload [_1]. (size = [_2] bytes)',
10859: '<span class="LC_filename">'.$fname.'</span>',
10860: $filesize).'<br />'.
10861: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10862: '</span>';
10863: return ('zero_bytes',$msg);
10864: }
10865: $filesize = $filesize/1000; #express in k (1024?)
10866: my $getpropath = 1;
10867: my ($dirlistref,$listerror) =
10868: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10869: my $found_file = 0;
10870: my $locked_file = 0;
10871: my @lockers;
10872: my $navmap;
10873: if ($env{'request.course.id'}) {
10874: $navmap = Apache::lonnavmaps::navmap->new();
10875: }
10876: if (ref($dirlistref) eq 'ARRAY') {
10877: foreach my $line (@{$dirlistref}) {
10878: my ($file_name,$rest)=split(/\&/,$line,2);
10879: if ($file_name eq $fname){
10880: $file_name = $path.$file_name;
10881: if ($group ne '') {
10882: $file_name = $group.$file_name;
10883: }
10884: $found_file = 1;
10885: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10886: foreach my $lock (@lockers) {
10887: if (ref($lock) eq 'ARRAY') {
10888: my ($symb,$crsid) = @{$lock};
10889: if ($crsid eq $env{'request.course.id'}) {
10890: if (ref($navmap)) {
10891: my $res = $navmap->getBySymb($symb);
10892: foreach my $part (@{$res->parts()}) {
10893: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10894: unless (($slot_status == $res->RESERVED) ||
10895: ($slot_status == $res->RESERVED_LOCATION)) {
10896: $locked_file = 1;
10897: }
10898: }
10899: } else {
10900: $locked_file = 1;
10901: }
10902: } else {
10903: $locked_file = 1;
10904: }
10905: }
10906: }
10907: } else {
10908: my @info = split(/\&/,$rest);
10909: my $currsize = $info[6]/1000;
10910: if ($currsize < $filesize) {
10911: my $extra = $filesize - $currsize;
10912: if (($current_disk_usage + $extra) > $disk_quota) {
10913: my $msg = '<span class="LC_error">'.
10914: &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.',
10915: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10916: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10917: $disk_quota,$current_disk_usage);
10918: return ('will_exceed_quota',$msg);
10919: }
10920: }
10921: }
10922: }
10923: }
10924: }
10925: if (($current_disk_usage + $filesize) > $disk_quota){
10926: my $msg = '<span class="LC_error">'.
10927: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10928: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10929: return ('will_exceed_quota',$msg);
10930: } elsif ($found_file) {
10931: if ($locked_file) {
10932: my $msg = '<span class="LC_error">';
10933: $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>');
10934: $msg .= '</span><br />';
10935: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10936: return ('file_locked',$msg);
10937: } else {
10938: my $msg = '<span class="LC_error">';
10939: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10940: $msg .= '</span>';
10941: return ('existingfile',$msg);
10942: }
10943: }
10944: }
10945:
10946: sub check_for_traversal {
10947: my ($path,$url,$toplevel) = @_;
10948: my @parts=split(/\//,$path);
10949: my $cleanpath;
10950: my $fullpath = $url;
10951: for (my $i=0;$i<@parts;$i++) {
10952: next if ($parts[$i] eq '.');
10953: if ($parts[$i] eq '..') {
10954: $fullpath =~ s{([^/]+/)$}{};
10955: } else {
10956: $fullpath .= $parts[$i].'/';
10957: }
10958: }
10959: if ($fullpath =~ /^\Q$url\E(.*)$/) {
10960: $cleanpath = $1;
10961: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10962: my $curr_toprel = $1;
10963: my @parts = split(/\//,$curr_toprel);
10964: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10965: my @urlparts = split(/\//,$url_toprel);
10966: my $doubledots;
10967: my $startdiff = -1;
10968: for (my $i=0; $i<@urlparts; $i++) {
10969: if ($startdiff == -1) {
10970: unless ($urlparts[$i] eq $parts[$i]) {
10971: $startdiff = $i;
10972: $doubledots .= '../';
10973: }
10974: } else {
10975: $doubledots .= '../';
10976: }
10977: }
10978: if ($startdiff > -1) {
10979: $cleanpath = $doubledots;
10980: for (my $i=$startdiff; $i<@parts; $i++) {
10981: $cleanpath .= $parts[$i].'/';
10982: }
10983: }
10984: }
10985: $cleanpath =~ s{(/)$}{};
10986: return $cleanpath;
10987: }
10988:
10989: sub is_archive_file {
10990: my ($mimetype) = @_;
10991: if (($mimetype eq 'application/octet-stream') ||
10992: ($mimetype eq 'application/x-stuffit') ||
10993: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10994: return 1;
10995: }
10996: return;
10997: }
10998:
10999: sub decompress_form {
11000: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11001: my %lt = &Apache::lonlocal::texthash (
11002: this => 'This file is an archive file.',
11003: camt => 'This file is a Camtasia archive file.',
11004: itsc => 'Its contents are as follows:',
11005: youm => 'You may wish to extract its contents.',
11006: extr => 'Extract contents',
11007: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11008: proa => 'Process automatically?',
11009: yes => 'Yes',
11010: no => 'No',
11011: fold => 'Title for folder containing movie',
11012: movi => 'Title for page containing embedded movie',
11013: );
11014: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11015: my ($is_camtasia,$topdir,%toplevel,@paths);
11016: my $info = &list_archive_contents($fileloc,\@paths);
11017: if (@paths) {
11018: foreach my $path (@paths) {
11019: $path =~ s{^/}{};
11020: if ($path =~ m{^([^/]+)/$}) {
11021: $topdir = $1;
11022: }
11023: if ($path =~ m{^([^/]+)/}) {
11024: $toplevel{$1} = $path;
11025: } else {
11026: $toplevel{$path} = $path;
11027: }
11028: }
11029: }
11030: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11031: my @camtasia6 = ("$topdir/","$topdir/index.html",
11032: "$topdir/media/",
11033: "$topdir/media/$topdir.mp4",
11034: "$topdir/media/FirstFrame.png",
11035: "$topdir/media/player.swf",
11036: "$topdir/media/swfobject.js",
11037: "$topdir/media/expressInstall.swf");
11038: my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11039: "$topdir/$topdir.mp4",
11040: "$topdir/$topdir\_config.xml",
11041: "$topdir/$topdir\_controller.swf",
11042: "$topdir/$topdir\_embed.css",
11043: "$topdir/$topdir\_First_Frame.png",
11044: "$topdir/$topdir\_player.html",
11045: "$topdir/$topdir\_Thumbnails.png",
11046: "$topdir/playerProductInstall.swf",
11047: "$topdir/scripts/",
11048: "$topdir/scripts/config_xml.js",
11049: "$topdir/scripts/handlebars.js",
11050: "$topdir/scripts/jquery-1.7.1.min.js",
11051: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11052: "$topdir/scripts/modernizr.js",
11053: "$topdir/scripts/player-min.js",
11054: "$topdir/scripts/swfobject.js",
11055: "$topdir/skins/",
11056: "$topdir/skins/configuration_express.xml",
11057: "$topdir/skins/express_show/",
11058: "$topdir/skins/express_show/player-min.css",
11059: "$topdir/skins/express_show/spritesheet.png");
11060: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11061: if (@diffs == 0) {
11062: $is_camtasia = 6;
11063: } else {
11064: @diffs = &compare_arrays(\@paths,\@camtasia8);
11065: if (@diffs == 0) {
11066: $is_camtasia = 8;
11067: }
11068: }
11069: }
11070: my $output;
11071: if ($is_camtasia) {
11072: $output = <<"ENDCAM";
11073: <script type="text/javascript" language="Javascript">
11074: // <![CDATA[
11075:
11076: function camtasiaToggle() {
11077: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11078: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11079: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11080: document.getElementById('camtasia_titles').style.display='block';
11081: } else {
11082: document.getElementById('camtasia_titles').style.display='none';
11083: }
11084: }
11085: }
11086: return;
11087: }
11088:
11089: // ]]>
11090: </script>
11091: <p>$lt{'camt'}</p>
11092: ENDCAM
11093: } else {
11094: $output = '<p>'.$lt{'this'};
11095: if ($info eq '') {
11096: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11097: } else {
11098: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11099: '<div><pre>'.$info.'</pre></div>';
11100: }
11101: }
11102: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11103: my $duplicates;
11104: my $num = 0;
11105: if (ref($dirlist) eq 'ARRAY') {
11106: foreach my $item (@{$dirlist}) {
11107: if (ref($item) eq 'ARRAY') {
11108: if (exists($toplevel{$item->[0]})) {
11109: $duplicates .=
11110: &start_data_table_row().
11111: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11112: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11113: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11114: 'value="1" />'.&mt('Yes').'</label>'.
11115: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11116: '<td>'.$item->[0].'</td>';
11117: if ($item->[2]) {
11118: $duplicates .= '<td>'.&mt('Directory').'</td>';
11119: } else {
11120: $duplicates .= '<td>'.&mt('File').'</td>';
11121: }
11122: $duplicates .= '<td>'.$item->[3].'</td>'.
11123: '<td>'.
11124: &Apache::lonlocal::locallocaltime($item->[4]).
11125: '</td>'.
11126: &end_data_table_row();
11127: $num ++;
11128: }
11129: }
11130: }
11131: }
11132: my $itemcount;
11133: if (@paths > 0) {
11134: $itemcount = scalar(@paths);
11135: } else {
11136: $itemcount = 1;
11137: }
11138: if ($is_camtasia) {
11139: $output .= $lt{'auto'}.'<br />'.
11140: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11141: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11142: $lt{'yes'}.'</label> <label>'.
11143: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11144: $lt{'no'}.'</label></span><br />'.
11145: '<div id="camtasia_titles" style="display:block">'.
11146: &Apache::lonhtmlcommon::start_pick_box().
11147: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11148: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11149: &Apache::lonhtmlcommon::row_closure().
11150: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11151: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11152: &Apache::lonhtmlcommon::row_closure(1).
11153: &Apache::lonhtmlcommon::end_pick_box().
11154: '</div>';
11155: }
11156: $output .=
11157: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11158: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11159: "\n";
11160: if ($duplicates ne '') {
11161: $output .= '<p><span class="LC_warning">'.
11162: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
11163: &start_data_table().
11164: &start_data_table_header_row().
11165: '<th>'.&mt('Overwrite?').'</th>'.
11166: '<th>'.&mt('Name').'</th>'.
11167: '<th>'.&mt('Type').'</th>'.
11168: '<th>'.&mt('Size').'</th>'.
11169: '<th>'.&mt('Last modified').'</th>'.
11170: &end_data_table_header_row().
11171: $duplicates.
11172: &end_data_table().
11173: '</p>';
11174: }
11175: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11176: if (ref($hiddenelements) eq 'HASH') {
11177: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11178: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11179: }
11180: }
11181: $output .= <<"END";
11182: <br />
11183: <input type="submit" name="decompress" value="$lt{'extr'}" />
11184: </form>
11185: $noextract
11186: END
11187: return $output;
11188: }
11189:
11190: sub decompression_utility {
11191: my ($program) = @_;
11192: my @utilities = ('tar','gunzip','bunzip2','unzip');
11193: my $location;
11194: if (grep(/^\Q$program\E$/,@utilities)) {
11195: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11196: '/usr/sbin/') {
11197: if (-x $dir.$program) {
11198: $location = $dir.$program;
11199: last;
11200: }
11201: }
11202: }
11203: return $location;
11204: }
11205:
11206: sub list_archive_contents {
11207: my ($file,$pathsref) = @_;
11208: my (@cmd,$output);
11209: my $needsregexp;
11210: if ($file =~ /\.zip$/) {
11211: @cmd = (&decompression_utility('unzip'),"-l");
11212: $needsregexp = 1;
11213: } elsif (($file =~ m/\.tar\.gz$/) ||
11214: ($file =~ /\.tgz$/)) {
11215: @cmd = (&decompression_utility('tar'),"-ztf");
11216: } elsif ($file =~ /\.tar\.bz2$/) {
11217: @cmd = (&decompression_utility('tar'),"-jtf");
11218: } elsif ($file =~ m|\.tar$|) {
11219: @cmd = (&decompression_utility('tar'),"-tf");
11220: }
11221: if (@cmd) {
11222: undef($!);
11223: undef($@);
11224: if (open(my $fh,"-|", @cmd, $file)) {
11225: while (my $line = <$fh>) {
11226: $output .= $line;
11227: chomp($line);
11228: my $item;
11229: if ($needsregexp) {
11230: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
11231: } else {
11232: $item = $line;
11233: }
11234: if ($item ne '') {
11235: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11236: push(@{$pathsref},$item);
11237: }
11238: }
11239: }
11240: close($fh);
11241: }
11242: }
11243: return $output;
11244: }
11245:
11246: sub decompress_uploaded_file {
11247: my ($file,$dir) = @_;
11248: &Apache::lonnet::appenv({'cgi.file' => $file});
11249: &Apache::lonnet::appenv({'cgi.dir' => $dir});
11250: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11251: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11252: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11253: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11254: my $decompressed = $env{'cgi.decompressed'};
11255: &Apache::lonnet::delenv('cgi.file');
11256: &Apache::lonnet::delenv('cgi.dir');
11257: &Apache::lonnet::delenv('cgi.decompressed');
11258: return ($decompressed,$result);
11259: }
11260:
11261: sub process_decompression {
11262: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11263: my ($dir,$error,$warning,$output);
11264: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11265: $error = &mt('Filename not a supported archive file type.').
11266: '<br />'.&mt('Filename should end with one of: [_1].',
11267: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11268: } else {
11269: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11270: if ($docuhome eq 'no_host') {
11271: $error = &mt('Could not determine home server for course.');
11272: } else {
11273: my @ids=&Apache::lonnet::current_machine_ids();
11274: my $currdir = "$dir_root/$destination";
11275: if (grep(/^\Q$docuhome\E$/,@ids)) {
11276: $dir = &LONCAPA::propath($docudom,$docuname).
11277: "$dir_root/$destination";
11278: } else {
11279: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11280: "$dir_root/$docudom/$docuname/$destination";
11281: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11282: $error = &mt('Archive file not found.');
11283: }
11284: }
11285: my (@to_overwrite,@to_skip);
11286: if ($env{'form.archive_overwrite_total'} > 0) {
11287: my $total = $env{'form.archive_overwrite_total'};
11288: for (my $i=0; $i<$total; $i++) {
11289: if ($env{'form.archive_overwrite_'.$i} == 1) {
11290: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11291: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11292: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11293: }
11294: }
11295: }
11296: my $numskip = scalar(@to_skip);
11297: if (($numskip > 0) &&
11298: ($numskip == $env{'form.archive_itemcount'})) {
11299: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
11300: } elsif ($dir eq '') {
11301: $error = &mt('Directory containing archive file unavailable.');
11302: } elsif (!$error) {
11303: my ($decompressed,$display);
11304: if ($numskip > 0) {
11305: my $tempdir = time.'_'.$$.int(rand(10000));
11306: mkdir("$dir/$tempdir",0755);
11307: system("mv $dir/$file $dir/$tempdir/$file");
11308: ($decompressed,$display) =
11309: &decompress_uploaded_file($file,"$dir/$tempdir");
11310: foreach my $item (@to_skip) {
11311: if (($item ne '') && ($item !~ /\.\./)) {
11312: if (-f "$dir/$tempdir/$item") {
11313: unlink("$dir/$tempdir/$item");
11314: } elsif (-d "$dir/$tempdir/$item") {
11315: system("rm -rf $dir/$tempdir/$item");
11316: }
11317: }
11318: }
11319: system("mv $dir/$tempdir/* $dir");
11320: rmdir("$dir/$tempdir");
11321: } else {
11322: ($decompressed,$display) =
11323: &decompress_uploaded_file($file,$dir);
11324: }
11325: if ($decompressed eq 'ok') {
11326: $output = '<p class="LC_info">'.
11327: &mt('Files extracted successfully from archive.').
11328: '</p>'."\n";
11329: my ($warning,$result,@contents);
11330: my ($newdirlistref,$newlisterror) =
11331: &Apache::lonnet::dirlist($currdir,$docudom,
11332: $docuname,1);
11333: my (%is_dir,%changes,@newitems);
11334: my $dirptr = 16384;
11335: if (ref($newdirlistref) eq 'ARRAY') {
11336: foreach my $dir_line (@{$newdirlistref}) {
11337: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11338: unless (($item =~ /^\.+$/) || ($item eq $file) ||
11339: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11340: push(@newitems,$item);
11341: if ($dirptr&$testdir) {
11342: $is_dir{$item} = 1;
11343: }
11344: $changes{$item} = 1;
11345: }
11346: }
11347: }
11348: if (keys(%changes) > 0) {
11349: foreach my $item (sort(@newitems)) {
11350: if ($changes{$item}) {
11351: push(@contents,$item);
11352: }
11353: }
11354: }
11355: if (@contents > 0) {
11356: my $wantform;
11357: unless ($env{'form.autoextract_camtasia'}) {
11358: $wantform = 1;
11359: }
11360: my (%children,%parent,%dirorder,%titles);
11361: my ($count,$datatable) = &get_extracted($docudom,$docuname,
11362: $currdir,\%is_dir,
11363: \%children,\%parent,
11364: \@contents,\%dirorder,
11365: \%titles,$wantform);
11366: if ($datatable ne '') {
11367: $output .= &archive_options_form('decompressed',$datatable,
11368: $count,$hiddenelem);
11369: my $startcount = 6;
11370: $output .= &archive_javascript($startcount,$count,
11371: \%titles,\%children);
11372: }
11373: if ($env{'form.autoextract_camtasia'}) {
11374: my $version = $env{'form.autoextract_camtasia'};
11375: my %displayed;
11376: my $total = 1;
11377: $env{'form.archive_directory'} = [];
11378: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11379: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11380: $path =~ s{/$}{};
11381: my $item;
11382: if ($path ne '') {
11383: $item = "$path/$titles{$i}";
11384: } else {
11385: $item = $titles{$i};
11386: }
11387: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11388: if ($item eq $contents[0]) {
11389: push(@{$env{'form.archive_directory'}},$i);
11390: $env{'form.archive_'.$i} = 'display';
11391: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11392: $displayed{'folder'} = $i;
11393: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11394: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11395: $env{'form.archive_'.$i} = 'display';
11396: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11397: $displayed{'web'} = $i;
11398: } else {
11399: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11400: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11401: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11402: push(@{$env{'form.archive_directory'}},$i);
11403: }
11404: $env{'form.archive_'.$i} = 'dependency';
11405: }
11406: $total ++;
11407: }
11408: for (my $i=1; $i<$total; $i++) {
11409: next if ($i == $displayed{'web'});
11410: next if ($i == $displayed{'folder'});
11411: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11412: }
11413: $env{'form.phase'} = 'decompress_cleanup';
11414: $env{'form.archivedelete'} = 1;
11415: $env{'form.archive_count'} = $total-1;
11416: $output .=
11417: &process_extracted_files('coursedocs',$docudom,
11418: $docuname,$destination,
11419: $dir_root,$hiddenelem);
11420: }
11421: } else {
11422: $warning = &mt('No new items extracted from archive file.');
11423: }
11424: } else {
11425: $output = $display;
11426: $error = &mt('An error occurred during extraction from the archive file.');
11427: }
11428: }
11429: }
11430: }
11431: if ($error) {
11432: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11433: $error.'</p>'."\n";
11434: }
11435: if ($warning) {
11436: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11437: }
11438: return $output;
11439: }
11440:
11441: sub get_extracted {
11442: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11443: $titles,$wantform) = @_;
11444: my $count = 0;
11445: my $depth = 0;
11446: my $datatable;
11447: my @hierarchy;
11448: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11449: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11450: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11451: foreach my $item (@{$contents}) {
11452: $count ++;
11453: @{$dirorder->{$count}} = @hierarchy;
11454: $titles->{$count} = $item;
11455: &archive_hierarchy($depth,$count,$parent,$children);
11456: if ($wantform) {
11457: $datatable .= &archive_row($is_dir->{$item},$item,
11458: $currdir,$depth,$count);
11459: }
11460: if ($is_dir->{$item}) {
11461: $depth ++;
11462: push(@hierarchy,$count);
11463: $parent->{$depth} = $count;
11464: $datatable .=
11465: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11466: \$depth,\$count,\@hierarchy,$dirorder,
11467: $children,$parent,$titles,$wantform);
11468: $depth --;
11469: pop(@hierarchy);
11470: }
11471: }
11472: return ($count,$datatable);
11473: }
11474:
11475: sub recurse_extracted_archive {
11476: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11477: $children,$parent,$titles,$wantform) = @_;
11478: my $result='';
11479: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11480: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11481: (ref($dirorder) eq 'HASH')) {
11482: return $result;
11483: }
11484: my $dirptr = 16384;
11485: my ($newdirlistref,$newlisterror) =
11486: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11487: if (ref($newdirlistref) eq 'ARRAY') {
11488: foreach my $dir_line (@{$newdirlistref}) {
11489: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11490: unless ($item =~ /^\.+$/) {
11491: $$count ++;
11492: @{$dirorder->{$$count}} = @{$hierarchy};
11493: $titles->{$$count} = $item;
11494: &archive_hierarchy($$depth,$$count,$parent,$children);
11495:
11496: my $is_dir;
11497: if ($dirptr&$testdir) {
11498: $is_dir = 1;
11499: }
11500: if ($wantform) {
11501: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11502: }
11503: if ($is_dir) {
11504: $$depth ++;
11505: push(@{$hierarchy},$$count);
11506: $parent->{$$depth} = $$count;
11507: $result .=
11508: &recurse_extracted_archive("$currdir/$item",$docudom,
11509: $docuname,$depth,$count,
11510: $hierarchy,$dirorder,$children,
11511: $parent,$titles,$wantform);
11512: $$depth --;
11513: pop(@{$hierarchy});
11514: }
11515: }
11516: }
11517: }
11518: return $result;
11519: }
11520:
11521: sub archive_hierarchy {
11522: my ($depth,$count,$parent,$children) =@_;
11523: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11524: if (exists($parent->{$depth})) {
11525: $children->{$parent->{$depth}} .= $count.':';
11526: }
11527: }
11528: return;
11529: }
11530:
11531: sub archive_row {
11532: my ($is_dir,$item,$currdir,$depth,$count) = @_;
11533: my ($name) = ($item =~ m{([^/]+)$});
11534: my %choices = &Apache::lonlocal::texthash (
11535: 'display' => 'Add as file',
11536: 'dependency' => 'Include as dependency',
11537: 'discard' => 'Discard',
11538: );
11539: if ($is_dir) {
11540: $choices{'display'} = &mt('Add as folder');
11541: }
11542: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11543: my $offset = 0;
11544: foreach my $action ('display','dependency','discard') {
11545: $offset ++;
11546: if ($action ne 'display') {
11547: $offset ++;
11548: }
11549: $output .= '<td><span class="LC_nobreak">'.
11550: '<label><input type="radio" name="archive_'.$count.
11551: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11552: my $text = $choices{$action};
11553: if ($is_dir) {
11554: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11555: if ($action eq 'display') {
11556: $text = &mt('Add as folder');
11557: }
11558: } else {
11559: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11560:
11561: }
11562: $output .= ' /> '.$choices{$action}.'</label></span>';
11563: if ($action eq 'dependency') {
11564: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11565: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
11566: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11567: '<option value=""></option>'."\n".
11568: '</select>'."\n".
11569: '</div>';
11570: } elsif ($action eq 'display') {
11571: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11572: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11573: '</div>';
11574: }
11575: $output .= '</td>';
11576: }
11577: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11578: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
11579: for (my $i=0; $i<$depth; $i++) {
11580: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11581: }
11582: if ($is_dir) {
11583: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
11584: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11585: } else {
11586: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11587: }
11588: $output .= ' '.$name.'</td>'."\n".
11589: &end_data_table_row();
11590: return $output;
11591: }
11592:
11593: sub archive_options_form {
11594: my ($form,$display,$count,$hiddenelem) = @_;
11595: my %lt = &Apache::lonlocal::texthash(
11596: perm => 'Permanently remove archive file?',
11597: hows => 'How should each extracted item be incorporated in the course?',
11598: cont => 'Content actions for all',
11599: addf => 'Add as folder/file',
11600: incd => 'Include as dependency for a displayed file',
11601: disc => 'Discard',
11602: no => 'No',
11603: yes => 'Yes',
11604: save => 'Save',
11605: );
11606: my $output = <<"END";
11607: <form name="$form" method="post" action="">
11608: <p><span class="LC_nobreak">$lt{'perm'}
11609: <label>
11610: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11611: </label>
11612:
11613: <label>
11614: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11615: </span>
11616: </p>
11617: <input type="hidden" name="phase" value="decompress_cleanup" />
11618: <br />$lt{'hows'}
11619: <div class="LC_columnSection">
11620: <fieldset>
11621: <legend>$lt{'cont'}</legend>
11622: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
11623: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11624: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11625: </fieldset>
11626: </div>
11627: END
11628: return $output.
11629: &start_data_table()."\n".
11630: $display."\n".
11631: &end_data_table()."\n".
11632: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11633: $hiddenelem.
11634: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11635: '</form>';
11636: }
11637:
11638: sub archive_javascript {
11639: my ($startcount,$numitems,$titles,$children) = @_;
11640: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11641: my $maintitle = $env{'form.comment'};
11642: my $scripttag = <<START;
11643: <script type="text/javascript">
11644: // <![CDATA[
11645:
11646: function checkAll(form,prefix) {
11647: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
11648: for (var i=0; i < form.elements.length; i++) {
11649: var id = form.elements[i].id;
11650: if ((id != '') && (id != undefined)) {
11651: if (idstr.test(id)) {
11652: if (form.elements[i].type == 'radio') {
11653: form.elements[i].checked = true;
11654: var nostart = i-$startcount;
11655: var offset = nostart%7;
11656: var count = (nostart-offset)/7;
11657: dependencyCheck(form,count,offset);
11658: }
11659: }
11660: }
11661: }
11662: }
11663:
11664: function propagateCheck(form,count) {
11665: if (count > 0) {
11666: var startelement = $startcount + ((count-1) * 7);
11667: for (var j=1; j<6; j++) {
11668: if ((j != 2) && (j != 4)) {
11669: var item = startelement + j;
11670: if (form.elements[item].type == 'radio') {
11671: if (form.elements[item].checked) {
11672: containerCheck(form,count,j);
11673: break;
11674: }
11675: }
11676: }
11677: }
11678: }
11679: }
11680:
11681: numitems = $numitems
11682: var titles = new Array(numitems);
11683: var parents = new Array(numitems);
11684: for (var i=0; i<numitems; i++) {
11685: parents[i] = new Array;
11686: }
11687: var maintitle = '$maintitle';
11688:
11689: START
11690:
11691: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11692: my @contents = split(/:/,$children->{$container});
11693: for (my $i=0; $i<@contents; $i ++) {
11694: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11695: }
11696: }
11697:
11698: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11699: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11700: }
11701:
11702: $scripttag .= <<END;
11703:
11704: function containerCheck(form,count,offset) {
11705: if (count > 0) {
11706: dependencyCheck(form,count,offset);
11707: var item = (offset+$startcount)+7*(count-1);
11708: form.elements[item].checked = true;
11709: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11710: if (parents[count].length > 0) {
11711: for (var j=0; j<parents[count].length; j++) {
11712: containerCheck(form,parents[count][j],offset);
11713: }
11714: }
11715: }
11716: }
11717: }
11718:
11719: function dependencyCheck(form,count,offset) {
11720: if (count > 0) {
11721: var chosen = (offset+$startcount)+7*(count-1);
11722: var depitem = $startcount + ((count-1) * 7) + 4;
11723: var currtype = form.elements[depitem].type;
11724: if (form.elements[chosen].value == 'dependency') {
11725: document.getElementById('arc_depon_'+count).style.display='block';
11726: form.elements[depitem].options.length = 0;
11727: form.elements[depitem].options[0] = new Option('Select','',true,true);
11728: for (var i=1; i<=numitems; i++) {
11729: if (i == count) {
11730: continue;
11731: }
11732: var startelement = $startcount + (i-1) * 7;
11733: for (var j=1; j<6; j++) {
11734: if ((j != 2) && (j!= 4)) {
11735: var item = startelement + j;
11736: if (form.elements[item].type == 'radio') {
11737: if (form.elements[item].checked) {
11738: if (form.elements[item].value == 'display') {
11739: var n = form.elements[depitem].options.length;
11740: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11741: }
11742: }
11743: }
11744: }
11745: }
11746: }
11747: } else {
11748: document.getElementById('arc_depon_'+count).style.display='none';
11749: form.elements[depitem].options.length = 0;
11750: form.elements[depitem].options[0] = new Option('Select','',true,true);
11751: }
11752: titleCheck(form,count,offset);
11753: }
11754: }
11755:
11756: function propagateSelect(form,count,offset) {
11757: if (count > 0) {
11758: var item = (1+offset+$startcount)+7*(count-1);
11759: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
11760: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11761: if (parents[count].length > 0) {
11762: for (var j=0; j<parents[count].length; j++) {
11763: containerSelect(form,parents[count][j],offset,picked);
11764: }
11765: }
11766: }
11767: }
11768: }
11769:
11770: function containerSelect(form,count,offset,picked) {
11771: if (count > 0) {
11772: var item = (offset+$startcount)+7*(count-1);
11773: if (form.elements[item].type == 'radio') {
11774: if (form.elements[item].value == 'dependency') {
11775: if (form.elements[item+1].type == 'select-one') {
11776: for (var i=0; i<form.elements[item+1].options.length; i++) {
11777: if (form.elements[item+1].options[i].value == picked) {
11778: form.elements[item+1].selectedIndex = i;
11779: break;
11780: }
11781: }
11782: }
11783: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11784: if (parents[count].length > 0) {
11785: for (var j=0; j<parents[count].length; j++) {
11786: containerSelect(form,parents[count][j],offset,picked);
11787: }
11788: }
11789: }
11790: }
11791: }
11792: }
11793: }
11794:
11795: function titleCheck(form,count,offset) {
11796: if (count > 0) {
11797: var chosen = (offset+$startcount)+7*(count-1);
11798: var depitem = $startcount + ((count-1) * 7) + 2;
11799: var currtype = form.elements[depitem].type;
11800: if (form.elements[chosen].value == 'display') {
11801: document.getElementById('arc_title_'+count).style.display='block';
11802: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11803: document.getElementById('archive_title_'+count).value=maintitle;
11804: }
11805: } else {
11806: document.getElementById('arc_title_'+count).style.display='none';
11807: if (currtype == 'text') {
11808: document.getElementById('archive_title_'+count).value='';
11809: }
11810: }
11811: }
11812: return;
11813: }
11814:
11815: // ]]>
11816: </script>
11817: END
11818: return $scripttag;
11819: }
11820:
11821: sub process_extracted_files {
11822: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11823: my $numitems = $env{'form.archive_count'};
11824: return unless ($numitems);
11825: my @ids=&Apache::lonnet::current_machine_ids();
11826: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11827: %folders,%containers,%mapinner,%prompttofetch);
11828: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11829: if (grep(/^\Q$docuhome\E$/,@ids)) {
11830: $prefix = &LONCAPA::propath($docudom,$docuname);
11831: $pathtocheck = "$dir_root/$destination";
11832: $dir = $dir_root;
11833: $ishome = 1;
11834: } else {
11835: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11836: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11837: $dir = "$dir_root/$docudom/$docuname";
11838: }
11839: my $currdir = "$dir_root/$destination";
11840: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11841: if ($env{'form.folderpath'}) {
11842: my @items = split('&',$env{'form.folderpath'});
11843: $folders{'0'} = $items[-2];
11844: if ($env{'form.folderpath'} =~ /\:1$/) {
11845: $containers{'0'}='page';
11846: } else {
11847: $containers{'0'}='sequence';
11848: }
11849: }
11850: my @archdirs = &get_env_multiple('form.archive_directory');
11851: if ($numitems) {
11852: for (my $i=1; $i<=$numitems; $i++) {
11853: my $path = $env{'form.archive_content_'.$i};
11854: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11855: my $item = $1;
11856: $toplevelitems{$item} = $i;
11857: if (grep(/^\Q$i\E$/,@archdirs)) {
11858: $is_dir{$item} = 1;
11859: }
11860: }
11861: }
11862: }
11863: my ($output,%children,%parent,%titles,%dirorder,$result);
11864: if (keys(%toplevelitems) > 0) {
11865: my @contents = sort(keys(%toplevelitems));
11866: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11867: \%parent,\@contents,\%dirorder,\%titles);
11868: }
11869: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11870: if ($numitems) {
11871: for (my $i=1; $i<=$numitems; $i++) {
11872: next if ($env{'form.archive_'.$i} eq 'dependency');
11873: my $path = $env{'form.archive_content_'.$i};
11874: if ($path =~ /^\Q$pathtocheck\E/) {
11875: if ($env{'form.archive_'.$i} eq 'discard') {
11876: if ($prefix ne '' && $path ne '') {
11877: if (-e $prefix.$path) {
11878: if ((@archdirs > 0) &&
11879: (grep(/^\Q$i\E$/,@archdirs))) {
11880: $todeletedir{$prefix.$path} = 1;
11881: } else {
11882: $todelete{$prefix.$path} = 1;
11883: }
11884: }
11885: }
11886: } elsif ($env{'form.archive_'.$i} eq 'display') {
11887: my ($docstitle,$title,$url,$outer);
11888: ($title) = ($path =~ m{/([^/]+)$});
11889: $docstitle = $env{'form.archive_title_'.$i};
11890: if ($docstitle eq '') {
11891: $docstitle = $title;
11892: }
11893: $outer = 0;
11894: if (ref($dirorder{$i}) eq 'ARRAY') {
11895: if (@{$dirorder{$i}} > 0) {
11896: foreach my $item (reverse(@{$dirorder{$i}})) {
11897: if ($env{'form.archive_'.$item} eq 'display') {
11898: $outer = $item;
11899: last;
11900: }
11901: }
11902: }
11903: }
11904: my ($errtext,$fatal) =
11905: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11906: '/'.$folders{$outer}.'.'.
11907: $containers{$outer});
11908: next if ($fatal);
11909: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11910: if ($context eq 'coursedocs') {
11911: $mapinner{$i} = time;
11912: $folders{$i} = 'default_'.$mapinner{$i};
11913: $containers{$i} = 'sequence';
11914: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11915: $folders{$i}.'.'.$containers{$i};
11916: my $newidx = &LONCAPA::map::getresidx();
11917: $LONCAPA::map::resources[$newidx]=
11918: $docstitle.':'.$url.':false:normal:res';
11919: push(@LONCAPA::map::order,$newidx);
11920: my ($outtext,$errtext) =
11921: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11922: $docuname.'/'.$folders{$outer}.
11923: '.'.$containers{$outer},1,1);
11924: $newseqid{$i} = $newidx;
11925: unless ($errtext) {
11926: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11927: }
11928: }
11929: } else {
11930: if ($context eq 'coursedocs') {
11931: my $newidx=&LONCAPA::map::getresidx();
11932: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11933: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11934: $title;
11935: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11936: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11937: }
11938: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11939: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11940: }
11941: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11942: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11943: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11944: unless ($ishome) {
11945: my $fetch = "$newdest{$i}/$title";
11946: $fetch =~ s/^\Q$prefix$dir\E//;
11947: $prompttofetch{$fetch} = 1;
11948: }
11949: }
11950: $LONCAPA::map::resources[$newidx]=
11951: $docstitle.':'.$url.':false:normal:res';
11952: push(@LONCAPA::map::order, $newidx);
11953: my ($outtext,$errtext)=
11954: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11955: $docuname.'/'.$folders{$outer}.
11956: '.'.$containers{$outer},1,1);
11957: unless ($errtext) {
11958: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11959: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11960: }
11961: }
11962: }
11963: }
11964: }
11965: } else {
11966: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11967: }
11968: }
11969: for (my $i=1; $i<=$numitems; $i++) {
11970: next unless ($env{'form.archive_'.$i} eq 'dependency');
11971: my $path = $env{'form.archive_content_'.$i};
11972: if ($path =~ /^\Q$pathtocheck\E/) {
11973: my ($title) = ($path =~ m{/([^/]+)$});
11974: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11975: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11976: if (ref($dirorder{$i}) eq 'ARRAY') {
11977: my ($itemidx,$fullpath,$relpath);
11978: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11979: my $container = $dirorder{$referrer{$i}}->[-1];
11980: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11981: if ($dirorder{$i}->[$j] eq $container) {
11982: $itemidx = $j;
11983: }
11984: }
11985: }
11986: if ($itemidx eq '') {
11987: $itemidx = 0;
11988: }
11989: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11990: if ($mapinner{$referrer{$i}}) {
11991: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11992: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11993: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11994: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11995: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11996: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11997: if (!-e $fullpath) {
11998: mkdir($fullpath,0755);
11999: }
12000: }
12001: } else {
12002: last;
12003: }
12004: }
12005: }
12006: } elsif ($newdest{$referrer{$i}}) {
12007: $fullpath = $newdest{$referrer{$i}};
12008: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12009: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12010: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12011: last;
12012: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12013: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12014: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12015: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12016: if (!-e $fullpath) {
12017: mkdir($fullpath,0755);
12018: }
12019: }
12020: } else {
12021: last;
12022: }
12023: }
12024: }
12025: if ($fullpath ne '') {
12026: if (-e "$prefix$path") {
12027: system("mv $prefix$path $fullpath/$title");
12028: }
12029: if (-e "$fullpath/$title") {
12030: my $showpath;
12031: if ($relpath ne '') {
12032: $showpath = "$relpath/$title";
12033: } else {
12034: $showpath = "/$title";
12035: }
12036: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12037: }
12038: unless ($ishome) {
12039: my $fetch = "$fullpath/$title";
12040: $fetch =~ s/^\Q$prefix$dir\E//;
12041: $prompttofetch{$fetch} = 1;
12042: }
12043: }
12044: }
12045: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12046: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12047: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12048: }
12049: } else {
12050: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12051: }
12052: }
12053: if (keys(%todelete)) {
12054: foreach my $key (keys(%todelete)) {
12055: unlink($key);
12056: }
12057: }
12058: if (keys(%todeletedir)) {
12059: foreach my $key (keys(%todeletedir)) {
12060: rmdir($key);
12061: }
12062: }
12063: foreach my $dir (sort(keys(%is_dir))) {
12064: if (($pathtocheck ne '') && ($dir ne '')) {
12065: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12066: }
12067: }
12068: if ($result ne '') {
12069: $output .= '<ul>'."\n".
12070: $result."\n".
12071: '</ul>';
12072: }
12073: unless ($ishome) {
12074: my $replicationfail;
12075: foreach my $item (keys(%prompttofetch)) {
12076: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12077: unless ($fetchresult eq 'ok') {
12078: $replicationfail .= '<li>'.$item.'</li>'."\n";
12079: }
12080: }
12081: if ($replicationfail) {
12082: $output .= '<p class="LC_error">'.
12083: &mt('Course home server failed to retrieve:').'<ul>'.
12084: $replicationfail.
12085: '</ul></p>';
12086: }
12087: }
12088: } else {
12089: $warning = &mt('No items found in archive.');
12090: }
12091: if ($error) {
12092: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12093: $error.'</p>'."\n";
12094: }
12095: if ($warning) {
12096: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12097: }
12098: return $output;
12099: }
12100:
12101: sub cleanup_empty_dirs {
12102: my ($path) = @_;
12103: if (($path ne '') && (-d $path)) {
12104: if (opendir(my $dirh,$path)) {
12105: my @dircontents = grep(!/^\./,readdir($dirh));
12106: my $numitems = 0;
12107: foreach my $item (@dircontents) {
12108: if (-d "$path/$item") {
12109: &cleanup_empty_dirs("$path/$item");
12110: if (-e "$path/$item") {
12111: $numitems ++;
12112: }
12113: } else {
12114: $numitems ++;
12115: }
12116: }
12117: if ($numitems == 0) {
12118: rmdir($path);
12119: }
12120: closedir($dirh);
12121: }
12122: }
12123: return;
12124: }
12125:
12126: =pod
12127:
12128: =item * &get_folder_hierarchy()
12129:
12130: Provides hierarchy of names of folders/sub-folders containing the current
12131: item,
12132:
12133: Inputs: 3
12134: - $navmap - navmaps object
12135:
12136: - $map - url for map (either the trigger itself, or map containing
12137: the resource, which is the trigger).
12138:
12139: - $showitem - 1 => show title for map itself; 0 => do not show.
12140:
12141: Outputs: 1 @pathitems - array of folder/subfolder names.
12142:
12143: =cut
12144:
12145: sub get_folder_hierarchy {
12146: my ($navmap,$map,$showitem) = @_;
12147: my @pathitems;
12148: if (ref($navmap)) {
12149: my $mapres = $navmap->getResourceByUrl($map);
12150: if (ref($mapres)) {
12151: my $pcslist = $mapres->map_hierarchy();
12152: if ($pcslist ne '') {
12153: my @pcs = split(/,/,$pcslist);
12154: foreach my $pc (@pcs) {
12155: if ($pc == 1) {
12156: push(@pathitems,&mt('Main Content'));
12157: } else {
12158: my $res = $navmap->getByMapPc($pc);
12159: if (ref($res)) {
12160: my $title = $res->compTitle();
12161: $title =~ s/\W+/_/g;
12162: if ($title ne '') {
12163: push(@pathitems,$title);
12164: }
12165: }
12166: }
12167: }
12168: }
12169: if ($showitem) {
12170: if ($mapres->{ID} eq '0.0') {
12171: push(@pathitems,&mt('Main Content'));
12172: } else {
12173: my $maptitle = $mapres->compTitle();
12174: $maptitle =~ s/\W+/_/g;
12175: if ($maptitle ne '') {
12176: push(@pathitems,$maptitle);
12177: }
12178: }
12179: }
12180: }
12181: }
12182: return @pathitems;
12183: }
12184:
12185: =pod
12186:
12187: =item * &get_turnedin_filepath()
12188:
12189: Determines path in a user's portfolio file for storage of files uploaded
12190: to a specific essayresponse or dropbox item.
12191:
12192: Inputs: 3 required + 1 optional.
12193: $symb is symb for resource, $uname and $udom are for current user (required).
12194: $caller is optional (can be "submission", if routine is called when storing
12195: an upoaded file when "Submit Answer" button was pressed).
12196:
12197: Returns array containing $path and $multiresp.
12198: $path is path in portfolio. $multiresp is 1 if this resource contains more
12199: than one file upload item. Callers of routine should append partid as a
12200: subdirectory to $path in cases where $multiresp is 1.
12201:
12202: Called by: homework/essayresponse.pm and homework/structuretags.pm
12203:
12204: =cut
12205:
12206: sub get_turnedin_filepath {
12207: my ($symb,$uname,$udom,$caller) = @_;
12208: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12209: my $turnindir;
12210: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12211: $turnindir = $userhash{'turnindir'};
12212: my ($path,$multiresp);
12213: if ($turnindir eq '') {
12214: if ($caller eq 'submission') {
12215: $turnindir = &mt('turned in');
12216: $turnindir =~ s/\W+/_/g;
12217: my %newhash = (
12218: 'turnindir' => $turnindir,
12219: );
12220: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12221: }
12222: }
12223: if ($turnindir ne '') {
12224: $path = '/'.$turnindir.'/';
12225: my ($multipart,$turnin,@pathitems);
12226: my $navmap = Apache::lonnavmaps::navmap->new();
12227: if (defined($navmap)) {
12228: my $mapres = $navmap->getResourceByUrl($map);
12229: if (ref($mapres)) {
12230: my $pcslist = $mapres->map_hierarchy();
12231: if ($pcslist ne '') {
12232: foreach my $pc (split(/,/,$pcslist)) {
12233: my $res = $navmap->getByMapPc($pc);
12234: if (ref($res)) {
12235: my $title = $res->compTitle();
12236: $title =~ s/\W+/_/g;
12237: if ($title ne '') {
12238: if (($pc > 1) && (length($title) > 12)) {
12239: $title = substr($title,0,12);
12240: }
12241: push(@pathitems,$title);
12242: }
12243: }
12244: }
12245: }
12246: my $maptitle = $mapres->compTitle();
12247: $maptitle =~ s/\W+/_/g;
12248: if ($maptitle ne '') {
12249: if (length($maptitle) > 12) {
12250: $maptitle = substr($maptitle,0,12);
12251: }
12252: push(@pathitems,$maptitle);
12253: }
12254: unless ($env{'request.state'} eq 'construct') {
12255: my $res = $navmap->getBySymb($symb);
12256: if (ref($res)) {
12257: my $partlist = $res->parts();
12258: my $totaluploads = 0;
12259: if (ref($partlist) eq 'ARRAY') {
12260: foreach my $part (@{$partlist}) {
12261: my @types = $res->responseType($part);
12262: my @ids = $res->responseIds($part);
12263: for (my $i=0; $i < scalar(@ids); $i++) {
12264: if ($types[$i] eq 'essay') {
12265: my $partid = $part.'_'.$ids[$i];
12266: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12267: $totaluploads ++;
12268: }
12269: }
12270: }
12271: }
12272: if ($totaluploads > 1) {
12273: $multiresp = 1;
12274: }
12275: }
12276: }
12277: }
12278: } else {
12279: return;
12280: }
12281: } else {
12282: return;
12283: }
12284: my $restitle=&Apache::lonnet::gettitle($symb);
12285: $restitle =~ s/\W+/_/g;
12286: if ($restitle eq '') {
12287: $restitle = ($resurl =~ m{/[^/]+$});
12288: if ($restitle eq '') {
12289: $restitle = time;
12290: }
12291: }
12292: if (length($restitle) > 12) {
12293: $restitle = substr($restitle,0,12);
12294: }
12295: push(@pathitems,$restitle);
12296: $path .= join('/',@pathitems);
12297: }
12298: return ($path,$multiresp);
12299: }
12300:
12301: =pod
12302:
12303: =back
12304:
12305: =head1 CSV Upload/Handling functions
12306:
12307: =over 4
12308:
12309: =item * &upfile_store($r)
12310:
12311: Store uploaded file, $r should be the HTTP Request object,
12312: needs $env{'form.upfile'}
12313: returns $datatoken to be put into hidden field
12314:
12315: =cut
12316:
12317: sub upfile_store {
12318: my $r=shift;
12319: $env{'form.upfile'}=~s/\r/\n/gs;
12320: $env{'form.upfile'}=~s/\f/\n/gs;
12321: $env{'form.upfile'}=~s/\n+/\n/gs;
12322: $env{'form.upfile'}=~s/\n+$//gs;
12323:
12324: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12325: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12326: {
12327: my $datafile = $r->dir_config('lonDaemons').
12328: '/tmp/'.$datatoken.'.tmp';
12329: if ( open(my $fh,">$datafile") ) {
12330: print $fh $env{'form.upfile'};
12331: close($fh);
12332: }
12333: }
12334: return $datatoken;
12335: }
12336:
12337: =pod
12338:
12339: =item * &load_tmp_file($r)
12340:
12341: Load uploaded file from tmp, $r should be the HTTP Request object,
12342: needs $env{'form.datatoken'},
12343: sets $env{'form.upfile'} to the contents of the file
12344:
12345: =cut
12346:
12347: sub load_tmp_file {
12348: my $r=shift;
12349: my @studentdata=();
12350: {
12351: my $studentfile = $r->dir_config('lonDaemons').
12352: '/tmp/'.$env{'form.datatoken'}.'.tmp';
12353: if ( open(my $fh,"<$studentfile") ) {
12354: @studentdata=<$fh>;
12355: close($fh);
12356: }
12357: }
12358: $env{'form.upfile'}=join('',@studentdata);
12359: }
12360:
12361: =pod
12362:
12363: =item * &upfile_record_sep()
12364:
12365: Separate uploaded file into records
12366: returns array of records,
12367: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12368:
12369: =cut
12370:
12371: sub upfile_record_sep {
12372: if ($env{'form.upfiletype'} eq 'xml') {
12373: } else {
12374: my @records;
12375: foreach my $line (split(/\n/,$env{'form.upfile'})) {
12376: if ($line=~/^\s*$/) { next; }
12377: push(@records,$line);
12378: }
12379: return @records;
12380: }
12381: }
12382:
12383: =pod
12384:
12385: =item * &record_sep($record)
12386:
12387: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12388:
12389: =cut
12390:
12391: sub takeleft {
12392: my $index=shift;
12393: return substr('0000'.$index,-4,4);
12394: }
12395:
12396: sub record_sep {
12397: my $record=shift;
12398: my %components=();
12399: if ($env{'form.upfiletype'} eq 'xml') {
12400: } elsif ($env{'form.upfiletype'} eq 'space') {
12401: my $i=0;
12402: foreach my $field (split(/\s+/,$record)) {
12403: $field=~s/^(\"|\')//;
12404: $field=~s/(\"|\')$//;
12405: $components{&takeleft($i)}=$field;
12406: $i++;
12407: }
12408: } elsif ($env{'form.upfiletype'} eq 'tab') {
12409: my $i=0;
12410: foreach my $field (split(/\t/,$record)) {
12411: $field=~s/^(\"|\')//;
12412: $field=~s/(\"|\')$//;
12413: $components{&takeleft($i)}=$field;
12414: $i++;
12415: }
12416: } else {
12417: my $separator=',';
12418: if ($env{'form.upfiletype'} eq 'semisv') {
12419: $separator=';';
12420: }
12421: my $i=0;
12422: # the character we are looking for to indicate the end of a quote or a record
12423: my $looking_for=$separator;
12424: # do not add the characters to the fields
12425: my $ignore=0;
12426: # we just encountered a separator (or the beginning of the record)
12427: my $just_found_separator=1;
12428: # store the field we are working on here
12429: my $field='';
12430: # work our way through all characters in record
12431: foreach my $character ($record=~/(.)/g) {
12432: if ($character eq $looking_for) {
12433: if ($character ne $separator) {
12434: # Found the end of a quote, again looking for separator
12435: $looking_for=$separator;
12436: $ignore=1;
12437: } else {
12438: # Found a separator, store away what we got
12439: $components{&takeleft($i)}=$field;
12440: $i++;
12441: $just_found_separator=1;
12442: $ignore=0;
12443: $field='';
12444: }
12445: next;
12446: }
12447: # single or double quotation marks after a separator indicate beginning of a quote
12448: # we are now looking for the end of the quote and need to ignore separators
12449: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
12450: $looking_for=$character;
12451: next;
12452: }
12453: # ignore would be true after we reached the end of a quote
12454: if ($ignore) { next; }
12455: if (($just_found_separator) && ($character=~/\s/)) { next; }
12456: $field.=$character;
12457: $just_found_separator=0;
12458: }
12459: # catch the very last entry, since we never encountered the separator
12460: $components{&takeleft($i)}=$field;
12461: }
12462: return %components;
12463: }
12464:
12465: ######################################################
12466: ######################################################
12467:
12468: =pod
12469:
12470: =item * &upfile_select_html()
12471:
12472: Return HTML code to select a file from the users machine and specify
12473: the file type.
12474:
12475: =cut
12476:
12477: ######################################################
12478: ######################################################
12479: sub upfile_select_html {
12480: my %Types = (
12481: csv => &mt('CSV (comma separated values, spreadsheet)'),
12482: semisv => &mt('Semicolon separated values'),
12483: space => &mt('Space separated'),
12484: tab => &mt('Tabulator separated'),
12485: # xml => &mt('HTML/XML'),
12486: );
12487: my $Str = '<input type="file" name="upfile" size="50" />'.
12488: '<br />'.&mt('Type').': <select name="upfiletype">';
12489: foreach my $type (sort(keys(%Types))) {
12490: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12491: }
12492: $Str .= "</select>\n";
12493: return $Str;
12494: }
12495:
12496: sub get_samples {
12497: my ($records,$toget) = @_;
12498: my @samples=({});
12499: my $got=0;
12500: foreach my $rec (@$records) {
12501: my %temp = &record_sep($rec);
12502: if (! grep(/\S/, values(%temp))) { next; }
12503: if (%temp) {
12504: $samples[$got]=\%temp;
12505: $got++;
12506: if ($got == $toget) { last; }
12507: }
12508: }
12509: return \@samples;
12510: }
12511:
12512: ######################################################
12513: ######################################################
12514:
12515: =pod
12516:
12517: =item * &csv_print_samples($r,$records)
12518:
12519: Prints a table of sample values from each column uploaded $r is an
12520: Apache Request ref, $records is an arrayref from
12521: &Apache::loncommon::upfile_record_sep
12522:
12523: =cut
12524:
12525: ######################################################
12526: ######################################################
12527: sub csv_print_samples {
12528: my ($r,$records) = @_;
12529: my $samples = &get_samples($records,5);
12530:
12531: $r->print(&mt('Samples').'<br />'.&start_data_table().
12532: &start_data_table_header_row());
12533: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12534: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12535: $r->print(&end_data_table_header_row());
12536: foreach my $hash (@$samples) {
12537: $r->print(&start_data_table_row());
12538: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12539: $r->print('<td>');
12540: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12541: $r->print('</td>');
12542: }
12543: $r->print(&end_data_table_row());
12544: }
12545: $r->print(&end_data_table().'<br />'."\n");
12546: }
12547:
12548: ######################################################
12549: ######################################################
12550:
12551: =pod
12552:
12553: =item * &csv_print_select_table($r,$records,$d)
12554:
12555: Prints a table to create associations between values and table columns.
12556:
12557: $r is an Apache Request ref,
12558: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12559: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12560:
12561: =cut
12562:
12563: ######################################################
12564: ######################################################
12565: sub csv_print_select_table {
12566: my ($r,$records,$d) = @_;
12567: my $i=0;
12568: my $samples = &get_samples($records,1);
12569: $r->print(&mt('Associate columns with student attributes.')."\n".
12570: &start_data_table().&start_data_table_header_row().
12571: '<th>'.&mt('Attribute').'</th>'.
12572: '<th>'.&mt('Column').'</th>'.
12573: &end_data_table_header_row()."\n");
12574: foreach my $array_ref (@$d) {
12575: my ($value,$display,$defaultcol)=@{ $array_ref };
12576: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
12577:
12578: $r->print('<td><select name="f'.$i.'"'.
12579: ' onchange="javascript:flip(this.form,'.$i.');">');
12580: $r->print('<option value="none"></option>');
12581: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12582: $r->print('<option value="'.$sample.'"'.
12583: ($sample eq $defaultcol ? ' selected="selected" ' : '').
12584: '>'.&mt('Column [_1]',($sample+1)).'</option>');
12585: }
12586: $r->print('</select></td>'.&end_data_table_row()."\n");
12587: $i++;
12588: }
12589: $r->print(&end_data_table());
12590: $i--;
12591: return $i;
12592: }
12593:
12594: ######################################################
12595: ######################################################
12596:
12597: =pod
12598:
12599: =item * &csv_samples_select_table($r,$records,$d)
12600:
12601: Prints a table of sample values from the upload and can make associate samples to internal names.
12602:
12603: $r is an Apache Request ref,
12604: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12605: $d is an array of 2 element arrays (internal name, displayed name)
12606:
12607: =cut
12608:
12609: ######################################################
12610: ######################################################
12611: sub csv_samples_select_table {
12612: my ($r,$records,$d) = @_;
12613: my $i=0;
12614: #
12615: my $max_samples = 5;
12616: my $samples = &get_samples($records,$max_samples);
12617: $r->print(&start_data_table().
12618: &start_data_table_header_row().'<th>'.
12619: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12620: &end_data_table_header_row());
12621:
12622: foreach my $key (sort(keys(%{ $samples->[0] }))) {
12623: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12624: ' onchange="javascript:flip(this.form,'.$i.');">');
12625: foreach my $option (@$d) {
12626: my ($value,$display,$defaultcol)=@{ $option };
12627: $r->print('<option value="'.$value.'"'.
12628: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12629: $display.'</option>');
12630: }
12631: $r->print('</select></td><td>');
12632: foreach my $line (0..($max_samples-1)) {
12633: if (defined($samples->[$line]{$key})) {
12634: $r->print($samples->[$line]{$key}."<br />\n");
12635: }
12636: }
12637: $r->print('</td>'.&end_data_table_row());
12638: $i++;
12639: }
12640: $r->print(&end_data_table());
12641: $i--;
12642: return($i);
12643: }
12644:
12645: ######################################################
12646: ######################################################
12647:
12648: =pod
12649:
12650: =item * &clean_excel_name($name)
12651:
12652: Returns a replacement for $name which does not contain any illegal characters.
12653:
12654: =cut
12655:
12656: ######################################################
12657: ######################################################
12658: sub clean_excel_name {
12659: my ($name) = @_;
12660: $name =~ s/[:\*\?\/\\]//g;
12661: if (length($name) > 31) {
12662: $name = substr($name,0,31);
12663: }
12664: return $name;
12665: }
12666:
12667: =pod
12668:
12669: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12670:
12671: Returns either 1 or undef
12672:
12673: 1 if the part is to be hidden, undef if it is to be shown
12674:
12675: Arguments are:
12676:
12677: $id the id of the part to be checked
12678: $symb, optional the symb of the resource to check
12679: $udom, optional the domain of the user to check for
12680: $uname, optional the username of the user to check for
12681:
12682: =cut
12683:
12684: sub check_if_partid_hidden {
12685: my ($id,$symb,$udom,$uname) = @_;
12686: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12687: $symb,$udom,$uname);
12688: my $truth=1;
12689: #if the string starts with !, then the list is the list to show not hide
12690: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12691: my @hiddenlist=split(/,/,$hiddenparts);
12692: foreach my $checkid (@hiddenlist) {
12693: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12694: }
12695: return !$truth;
12696: }
12697:
12698:
12699: ############################################################
12700: ############################################################
12701:
12702: =pod
12703:
12704: =back
12705:
12706: =head1 cgi-bin script and graphing routines
12707:
12708: =over 4
12709:
12710: =item * &get_cgi_id()
12711:
12712: Inputs: none
12713:
12714: Returns an id which can be used to pass environment variables
12715: to various cgi-bin scripts. These environment variables will
12716: be removed from the users environment after a given time by
12717: the routine &Apache::lonnet::transfer_profile_to_env.
12718:
12719: =cut
12720:
12721: ############################################################
12722: ############################################################
12723: my $uniq=0;
12724: sub get_cgi_id {
12725: $uniq=($uniq+1)%100000;
12726: return (time.'_'.$$.'_'.$uniq);
12727: }
12728:
12729: ############################################################
12730: ############################################################
12731:
12732: =pod
12733:
12734: =item * &DrawBarGraph()
12735:
12736: Facilitates the plotting of data in a (stacked) bar graph.
12737: Puts plot definition data into the users environment in order for
12738: graph.png to plot it. Returns an <img> tag for the plot.
12739: The bars on the plot are labeled '1','2',...,'n'.
12740:
12741: Inputs:
12742:
12743: =over 4
12744:
12745: =item $Title: string, the title of the plot
12746:
12747: =item $xlabel: string, text describing the X-axis of the plot
12748:
12749: =item $ylabel: string, text describing the Y-axis of the plot
12750:
12751: =item $Max: scalar, the maximum Y value to use in the plot
12752: If $Max is < any data point, the graph will not be rendered.
12753:
12754: =item $colors: array ref holding the colors to be used for the data sets when
12755: they are plotted. If undefined, default values will be used.
12756:
12757: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12758:
12759: =item @Values: An array of array references. Each array reference holds data
12760: to be plotted in a stacked bar chart.
12761:
12762: =item If the final element of @Values is a hash reference the key/value
12763: pairs will be added to the graph definition.
12764:
12765: =back
12766:
12767: Returns:
12768:
12769: An <img> tag which references graph.png and the appropriate identifying
12770: information for the plot.
12771:
12772: =cut
12773:
12774: ############################################################
12775: ############################################################
12776: sub DrawBarGraph {
12777: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12778: #
12779: if (! defined($colors)) {
12780: $colors = ['#33ff00',
12781: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12782: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12783: ];
12784: }
12785: my $extra_settings = {};
12786: if (ref($Values[-1]) eq 'HASH') {
12787: $extra_settings = pop(@Values);
12788: }
12789: #
12790: my $identifier = &get_cgi_id();
12791: my $id = 'cgi.'.$identifier;
12792: if (! @Values || ref($Values[0]) ne 'ARRAY') {
12793: return '';
12794: }
12795: #
12796: my @Labels;
12797: if (defined($labels)) {
12798: @Labels = @$labels;
12799: } else {
12800: for (my $i=0;$i<@{$Values[0]};$i++) {
12801: push (@Labels,$i+1);
12802: }
12803: }
12804: #
12805: my $NumBars = scalar(@{$Values[0]});
12806: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12807: my %ValuesHash;
12808: my $NumSets=1;
12809: foreach my $array (@Values) {
12810: next if (! ref($array));
12811: $ValuesHash{$id.'.data.'.$NumSets++} =
12812: join(',',@$array);
12813: }
12814: #
12815: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12816: if ($NumBars < 3) {
12817: $width = 120+$NumBars*32;
12818: $xskip = 1;
12819: $bar_width = 30;
12820: } elsif ($NumBars < 5) {
12821: $width = 120+$NumBars*20;
12822: $xskip = 1;
12823: $bar_width = 20;
12824: } elsif ($NumBars < 10) {
12825: $width = 120+$NumBars*15;
12826: $xskip = 1;
12827: $bar_width = 15;
12828: } elsif ($NumBars <= 25) {
12829: $width = 120+$NumBars*11;
12830: $xskip = 5;
12831: $bar_width = 8;
12832: } elsif ($NumBars <= 50) {
12833: $width = 120+$NumBars*8;
12834: $xskip = 5;
12835: $bar_width = 4;
12836: } else {
12837: $width = 120+$NumBars*8;
12838: $xskip = 5;
12839: $bar_width = 4;
12840: }
12841: #
12842: $Max = 1 if ($Max < 1);
12843: if ( int($Max) < $Max ) {
12844: $Max++;
12845: $Max = int($Max);
12846: }
12847: $Title = '' if (! defined($Title));
12848: $xlabel = '' if (! defined($xlabel));
12849: $ylabel = '' if (! defined($ylabel));
12850: $ValuesHash{$id.'.title'} = &escape($Title);
12851: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
12852: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
12853: $ValuesHash{$id.'.y_max_value'} = $Max;
12854: $ValuesHash{$id.'.NumBars'} = $NumBars;
12855: $ValuesHash{$id.'.NumSets'} = $NumSets;
12856: $ValuesHash{$id.'.PlotType'} = 'bar';
12857: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12858: $ValuesHash{$id.'.height'} = $height;
12859: $ValuesHash{$id.'.width'} = $width;
12860: $ValuesHash{$id.'.xskip'} = $xskip;
12861: $ValuesHash{$id.'.bar_width'} = $bar_width;
12862: $ValuesHash{$id.'.labels'} = join(',',@Labels);
12863: #
12864: # Deal with other parameters
12865: while (my ($key,$value) = each(%$extra_settings)) {
12866: $ValuesHash{$id.'.'.$key} = $value;
12867: }
12868: #
12869: &Apache::lonnet::appenv(\%ValuesHash);
12870: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12871: }
12872:
12873: ############################################################
12874: ############################################################
12875:
12876: =pod
12877:
12878: =item * &DrawXYGraph()
12879:
12880: Facilitates the plotting of data in an XY graph.
12881: Puts plot definition data into the users environment in order for
12882: graph.png to plot it. Returns an <img> tag for the plot.
12883:
12884: Inputs:
12885:
12886: =over 4
12887:
12888: =item $Title: string, the title of the plot
12889:
12890: =item $xlabel: string, text describing the X-axis of the plot
12891:
12892: =item $ylabel: string, text describing the Y-axis of the plot
12893:
12894: =item $Max: scalar, the maximum Y value to use in the plot
12895: If $Max is < any data point, the graph will not be rendered.
12896:
12897: =item $colors: Array ref containing the hex color codes for the data to be
12898: plotted in. If undefined, default values will be used.
12899:
12900: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12901:
12902: =item $Ydata: Array ref containing Array refs.
12903: Each of the contained arrays will be plotted as a separate curve.
12904:
12905: =item %Values: hash indicating or overriding any default values which are
12906: passed to graph.png.
12907: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12908:
12909: =back
12910:
12911: Returns:
12912:
12913: An <img> tag which references graph.png and the appropriate identifying
12914: information for the plot.
12915:
12916: =cut
12917:
12918: ############################################################
12919: ############################################################
12920: sub DrawXYGraph {
12921: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12922: #
12923: # Create the identifier for the graph
12924: my $identifier = &get_cgi_id();
12925: my $id = 'cgi.'.$identifier;
12926: #
12927: $Title = '' if (! defined($Title));
12928: $xlabel = '' if (! defined($xlabel));
12929: $ylabel = '' if (! defined($ylabel));
12930: my %ValuesHash =
12931: (
12932: $id.'.title' => &escape($Title),
12933: $id.'.xlabel' => &escape($xlabel),
12934: $id.'.ylabel' => &escape($ylabel),
12935: $id.'.y_max_value'=> $Max,
12936: $id.'.labels' => join(',',@$Xlabels),
12937: $id.'.PlotType' => 'XY',
12938: );
12939: #
12940: if (defined($colors) && ref($colors) eq 'ARRAY') {
12941: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12942: }
12943: #
12944: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12945: return '';
12946: }
12947: my $NumSets=1;
12948: foreach my $array (@{$Ydata}){
12949: next if (! ref($array));
12950: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12951: }
12952: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12953: #
12954: # Deal with other parameters
12955: while (my ($key,$value) = each(%Values)) {
12956: $ValuesHash{$id.'.'.$key} = $value;
12957: }
12958: #
12959: &Apache::lonnet::appenv(\%ValuesHash);
12960: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12961: }
12962:
12963: ############################################################
12964: ############################################################
12965:
12966: =pod
12967:
12968: =item * &DrawXYYGraph()
12969:
12970: Facilitates the plotting of data in an XY graph with two Y axes.
12971: Puts plot definition data into the users environment in order for
12972: graph.png to plot it. Returns an <img> tag for the plot.
12973:
12974: Inputs:
12975:
12976: =over 4
12977:
12978: =item $Title: string, the title of the plot
12979:
12980: =item $xlabel: string, text describing the X-axis of the plot
12981:
12982: =item $ylabel: string, text describing the Y-axis of the plot
12983:
12984: =item $colors: Array ref containing the hex color codes for the data to be
12985: plotted in. If undefined, default values will be used.
12986:
12987: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12988:
12989: =item $Ydata1: The first data set
12990:
12991: =item $Min1: The minimum value of the left Y-axis
12992:
12993: =item $Max1: The maximum value of the left Y-axis
12994:
12995: =item $Ydata2: The second data set
12996:
12997: =item $Min2: The minimum value of the right Y-axis
12998:
12999: =item $Max2: The maximum value of the left Y-axis
13000:
13001: =item %Values: hash indicating or overriding any default values which are
13002: passed to graph.png.
13003: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13004:
13005: =back
13006:
13007: Returns:
13008:
13009: An <img> tag which references graph.png and the appropriate identifying
13010: information for the plot.
13011:
13012: =cut
13013:
13014: ############################################################
13015: ############################################################
13016: sub DrawXYYGraph {
13017: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13018: $Ydata2,$Min2,$Max2,%Values)=@_;
13019: #
13020: # Create the identifier for the graph
13021: my $identifier = &get_cgi_id();
13022: my $id = 'cgi.'.$identifier;
13023: #
13024: $Title = '' if (! defined($Title));
13025: $xlabel = '' if (! defined($xlabel));
13026: $ylabel = '' if (! defined($ylabel));
13027: my %ValuesHash =
13028: (
13029: $id.'.title' => &escape($Title),
13030: $id.'.xlabel' => &escape($xlabel),
13031: $id.'.ylabel' => &escape($ylabel),
13032: $id.'.labels' => join(',',@$Xlabels),
13033: $id.'.PlotType' => 'XY',
13034: $id.'.NumSets' => 2,
13035: $id.'.two_axes' => 1,
13036: $id.'.y1_max_value' => $Max1,
13037: $id.'.y1_min_value' => $Min1,
13038: $id.'.y2_max_value' => $Max2,
13039: $id.'.y2_min_value' => $Min2,
13040: );
13041: #
13042: if (defined($colors) && ref($colors) eq 'ARRAY') {
13043: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13044: }
13045: #
13046: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13047: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13048: return '';
13049: }
13050: my $NumSets=1;
13051: foreach my $array ($Ydata1,$Ydata2){
13052: next if (! ref($array));
13053: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13054: }
13055: #
13056: # Deal with other parameters
13057: while (my ($key,$value) = each(%Values)) {
13058: $ValuesHash{$id.'.'.$key} = $value;
13059: }
13060: #
13061: &Apache::lonnet::appenv(\%ValuesHash);
13062: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13063: }
13064:
13065: ############################################################
13066: ############################################################
13067:
13068: =pod
13069:
13070: =back
13071:
13072: =head1 Statistics helper routines?
13073:
13074: Bad place for them but what the hell.
13075:
13076: =over 4
13077:
13078: =item * &chartlink()
13079:
13080: Returns a link to the chart for a specific student.
13081:
13082: Inputs:
13083:
13084: =over 4
13085:
13086: =item $linktext: The text of the link
13087:
13088: =item $sname: The students username
13089:
13090: =item $sdomain: The students domain
13091:
13092: =back
13093:
13094: =back
13095:
13096: =cut
13097:
13098: ############################################################
13099: ############################################################
13100: sub chartlink {
13101: my ($linktext, $sname, $sdomain) = @_;
13102: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13103: '&SelectedStudent='.&escape($sname.':'.$sdomain).
13104: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
13105: '">'.$linktext.'</a>';
13106: }
13107:
13108: #######################################################
13109: #######################################################
13110:
13111: =pod
13112:
13113: =head1 Course Environment Routines
13114:
13115: =over 4
13116:
13117: =item * &restore_course_settings()
13118:
13119: =item * &store_course_settings()
13120:
13121: Restores/Store indicated form parameters from the course environment.
13122: Will not overwrite existing values of the form parameters.
13123:
13124: Inputs:
13125: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13126:
13127: a hash ref describing the data to be stored. For example:
13128:
13129: %Save_Parameters = ('Status' => 'scalar',
13130: 'chartoutputmode' => 'scalar',
13131: 'chartoutputdata' => 'scalar',
13132: 'Section' => 'array',
13133: 'Group' => 'array',
13134: 'StudentData' => 'array',
13135: 'Maps' => 'array');
13136:
13137: Returns: both routines return nothing
13138:
13139: =back
13140:
13141: =cut
13142:
13143: #######################################################
13144: #######################################################
13145: sub store_course_settings {
13146: return &store_settings($env{'request.course.id'},@_);
13147: }
13148:
13149: sub store_settings {
13150: # save to the environment
13151: # appenv the same items, just to be safe
13152: my $udom = $env{'user.domain'};
13153: my $uname = $env{'user.name'};
13154: my ($context,$prefix,$Settings) = @_;
13155: my %SaveHash;
13156: my %AppHash;
13157: while (my ($setting,$type) = each(%$Settings)) {
13158: my $basename = join('.','internal',$context,$prefix,$setting);
13159: my $envname = 'environment.'.$basename;
13160: if (exists($env{'form.'.$setting})) {
13161: # Save this value away
13162: if ($type eq 'scalar' &&
13163: (! exists($env{$envname}) ||
13164: $env{$envname} ne $env{'form.'.$setting})) {
13165: $SaveHash{$basename} = $env{'form.'.$setting};
13166: $AppHash{$envname} = $env{'form.'.$setting};
13167: } elsif ($type eq 'array') {
13168: my $stored_form;
13169: if (ref($env{'form.'.$setting})) {
13170: $stored_form = join(',',
13171: map {
13172: &escape($_);
13173: } sort(@{$env{'form.'.$setting}}));
13174: } else {
13175: $stored_form =
13176: &escape($env{'form.'.$setting});
13177: }
13178: # Determine if the array contents are the same.
13179: if ($stored_form ne $env{$envname}) {
13180: $SaveHash{$basename} = $stored_form;
13181: $AppHash{$envname} = $stored_form;
13182: }
13183: }
13184: }
13185: }
13186: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13187: $udom,$uname);
13188: if ($put_result !~ /^(ok|delayed)/) {
13189: &Apache::lonnet::logthis('unable to save form parameters, '.
13190: 'got error:'.$put_result);
13191: }
13192: # Make sure these settings stick around in this session, too
13193: &Apache::lonnet::appenv(\%AppHash);
13194: return;
13195: }
13196:
13197: sub restore_course_settings {
13198: return &restore_settings($env{'request.course.id'},@_);
13199: }
13200:
13201: sub restore_settings {
13202: my ($context,$prefix,$Settings) = @_;
13203: while (my ($setting,$type) = each(%$Settings)) {
13204: next if (exists($env{'form.'.$setting}));
13205: my $envname = 'environment.internal.'.$context.'.'.$prefix.
13206: '.'.$setting;
13207: if (exists($env{$envname})) {
13208: if ($type eq 'scalar') {
13209: $env{'form.'.$setting} = $env{$envname};
13210: } elsif ($type eq 'array') {
13211: $env{'form.'.$setting} = [
13212: map {
13213: &unescape($_);
13214: } split(',',$env{$envname})
13215: ];
13216: }
13217: }
13218: }
13219: }
13220:
13221: #######################################################
13222: #######################################################
13223:
13224: =pod
13225:
13226: =head1 Domain E-mail Routines
13227:
13228: =over 4
13229:
13230: =item * &build_recipient_list()
13231:
13232: Build recipient lists for following types of e-mail:
13233: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13234: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13235: module change checking, student/employee ID conflict checks, as
13236: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13237: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13238:
13239: Inputs:
13240: defmail (scalar - email address of default recipient),
13241: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13242: requestsmail, updatesmail, or idconflictsmail).
13243:
13244: defdom (domain for which to retrieve configuration settings),
13245:
13246: origmail (scalar - email address of recipient from loncapa.conf,
13247: i.e., predates configuration by DC via domainprefs.pm
13248:
13249: Returns: comma separated list of addresses to which to send e-mail.
13250:
13251: =back
13252:
13253: =cut
13254:
13255: ############################################################
13256: ############################################################
13257: sub build_recipient_list {
13258: my ($defmail,$mailing,$defdom,$origmail) = @_;
13259: my @recipients;
13260: my $otheremails;
13261: my %domconfig =
13262: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13263: if (ref($domconfig{'contacts'}) eq 'HASH') {
13264: if (exists($domconfig{'contacts'}{$mailing})) {
13265: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13266: my @contacts = ('adminemail','supportemail');
13267: foreach my $item (@contacts) {
13268: if ($domconfig{'contacts'}{$mailing}{$item}) {
13269: my $addr = $domconfig{'contacts'}{$item};
13270: if (!grep(/^\Q$addr\E$/,@recipients)) {
13271: push(@recipients,$addr);
13272: }
13273: }
13274: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13275: }
13276: }
13277: } elsif ($origmail ne '') {
13278: push(@recipients,$origmail);
13279: }
13280: } elsif ($origmail ne '') {
13281: push(@recipients,$origmail);
13282: }
13283: if (defined($defmail)) {
13284: if ($defmail ne '') {
13285: push(@recipients,$defmail);
13286: }
13287: }
13288: if ($otheremails) {
13289: my @others;
13290: if ($otheremails =~ /,/) {
13291: @others = split(/,/,$otheremails);
13292: } else {
13293: push(@others,$otheremails);
13294: }
13295: foreach my $addr (@others) {
13296: if (!grep(/^\Q$addr\E$/,@recipients)) {
13297: push(@recipients,$addr);
13298: }
13299: }
13300: }
13301: my $recipientlist = join(',',@recipients);
13302: return $recipientlist;
13303: }
13304:
13305: ############################################################
13306: ############################################################
13307:
13308: =pod
13309:
13310: =head1 Course Catalog Routines
13311:
13312: =over 4
13313:
13314: =item * &gather_categories()
13315:
13316: Converts category definitions - keys of categories hash stored in
13317: coursecategories in configuration.db on the primary library server in a
13318: domain - to an array. Also generates javascript and idx hash used to
13319: generate Domain Coordinator interface for editing Course Categories.
13320:
13321: Inputs:
13322:
13323: categories (reference to hash of category definitions).
13324:
13325: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13326: categories and subcategories).
13327:
13328: idx (reference to hash of counters used in Domain Coordinator interface for
13329: editing Course Categories).
13330:
13331: jsarray (reference to array of categories used to create Javascript arrays for
13332: Domain Coordinator interface for editing Course Categories).
13333:
13334: Returns: nothing
13335:
13336: Side effects: populates cats, idx and jsarray.
13337:
13338: =cut
13339:
13340: sub gather_categories {
13341: my ($categories,$cats,$idx,$jsarray) = @_;
13342: my %counters;
13343: my $num = 0;
13344: foreach my $item (keys(%{$categories})) {
13345: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13346: if ($container eq '' && $depth == 0) {
13347: $cats->[$depth][$categories->{$item}] = $cat;
13348: } else {
13349: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13350: }
13351: my ($escitem,$tail) = split(/:/,$item,2);
13352: if ($counters{$tail} eq '') {
13353: $counters{$tail} = $num;
13354: $num ++;
13355: }
13356: if (ref($idx) eq 'HASH') {
13357: $idx->{$item} = $counters{$tail};
13358: }
13359: if (ref($jsarray) eq 'ARRAY') {
13360: push(@{$jsarray->[$counters{$tail}]},$item);
13361: }
13362: }
13363: return;
13364: }
13365:
13366: =pod
13367:
13368: =item * &extract_categories()
13369:
13370: Used to generate breadcrumb trails for course categories.
13371:
13372: Inputs:
13373:
13374: categories (reference to hash of category definitions).
13375:
13376: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13377: categories and subcategories).
13378:
13379: trails (reference to array of breacrumb trails for each category).
13380:
13381: allitems (reference to hash - key is category key
13382: (format: escaped(name):escaped(parent category):depth in hierarchy).
13383:
13384: idx (reference to hash of counters used in Domain Coordinator interface for
13385: editing Course Categories).
13386:
13387: jsarray (reference to array of categories used to create Javascript arrays for
13388: Domain Coordinator interface for editing Course Categories).
13389:
13390: subcats (reference to hash of arrays containing all subcategories within each
13391: category, -recursive)
13392:
13393: Returns: nothing
13394:
13395: Side effects: populates trails and allitems hash references.
13396:
13397: =cut
13398:
13399: sub extract_categories {
13400: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13401: if (ref($categories) eq 'HASH') {
13402: &gather_categories($categories,$cats,$idx,$jsarray);
13403: if (ref($cats->[0]) eq 'ARRAY') {
13404: for (my $i=0; $i<@{$cats->[0]}; $i++) {
13405: my $name = $cats->[0][$i];
13406: my $item = &escape($name).'::0';
13407: my $trailstr;
13408: if ($name eq 'instcode') {
13409: $trailstr = &mt('Official courses (with institutional codes)');
13410: } elsif ($name eq 'communities') {
13411: $trailstr = &mt('Communities');
13412: } else {
13413: $trailstr = $name;
13414: }
13415: if ($allitems->{$item} eq '') {
13416: push(@{$trails},$trailstr);
13417: $allitems->{$item} = scalar(@{$trails})-1;
13418: }
13419: my @parents = ($name);
13420: if (ref($cats->[1]{$name}) eq 'ARRAY') {
13421: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13422: my $category = $cats->[1]{$name}[$j];
13423: if (ref($subcats) eq 'HASH') {
13424: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13425: }
13426: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13427: }
13428: } else {
13429: if (ref($subcats) eq 'HASH') {
13430: $subcats->{$item} = [];
13431: }
13432: }
13433: }
13434: }
13435: }
13436: return;
13437: }
13438:
13439: =pod
13440:
13441: =item * &recurse_categories()
13442:
13443: Recursively used to generate breadcrumb trails for course categories.
13444:
13445: Inputs:
13446:
13447: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13448: categories and subcategories).
13449:
13450: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13451:
13452: category (current course category, for which breadcrumb trail is being generated).
13453:
13454: trails (reference to array of breadcrumb trails for each category).
13455:
13456: allitems (reference to hash - key is category key
13457: (format: escaped(name):escaped(parent category):depth in hierarchy).
13458:
13459: parents (array containing containers directories for current category,
13460: back to top level).
13461:
13462: Returns: nothing
13463:
13464: Side effects: populates trails and allitems hash references
13465:
13466: =cut
13467:
13468: sub recurse_categories {
13469: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13470: my $shallower = $depth - 1;
13471: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13472: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13473: my $name = $cats->[$depth]{$category}[$k];
13474: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13475: my $trailstr = join(' -> ',(@{$parents},$category));
13476: if ($allitems->{$item} eq '') {
13477: push(@{$trails},$trailstr);
13478: $allitems->{$item} = scalar(@{$trails})-1;
13479: }
13480: my $deeper = $depth+1;
13481: push(@{$parents},$category);
13482: if (ref($subcats) eq 'HASH') {
13483: my $subcat = &escape($name).':'.$category.':'.$depth;
13484: for (my $j=@{$parents}; $j>=0; $j--) {
13485: my $higher;
13486: if ($j > 0) {
13487: $higher = &escape($parents->[$j]).':'.
13488: &escape($parents->[$j-1]).':'.$j;
13489: } else {
13490: $higher = &escape($parents->[$j]).'::'.$j;
13491: }
13492: push(@{$subcats->{$higher}},$subcat);
13493: }
13494: }
13495: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13496: $subcats);
13497: pop(@{$parents});
13498: }
13499: } else {
13500: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13501: my $trailstr = join(' -> ',(@{$parents},$category));
13502: if ($allitems->{$item} eq '') {
13503: push(@{$trails},$trailstr);
13504: $allitems->{$item} = scalar(@{$trails})-1;
13505: }
13506: }
13507: return;
13508: }
13509:
13510: =pod
13511:
13512: =item * &assign_categories_table()
13513:
13514: Create a datatable for display of hierarchical categories in a domain,
13515: with checkboxes to allow a course to be categorized.
13516:
13517: Inputs:
13518:
13519: cathash - reference to hash of categories defined for the domain (from
13520: configuration.db)
13521:
13522: currcat - scalar with an & separated list of categories assigned to a course.
13523:
13524: type - scalar contains course type (Course or Community).
13525:
13526: Returns: $output (markup to be displayed)
13527:
13528: =cut
13529:
13530: sub assign_categories_table {
13531: my ($cathash,$currcat,$type) = @_;
13532: my $output;
13533: if (ref($cathash) eq 'HASH') {
13534: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13535: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13536: $maxdepth = scalar(@cats);
13537: if (@cats > 0) {
13538: my $itemcount = 0;
13539: if (ref($cats[0]) eq 'ARRAY') {
13540: my @currcategories;
13541: if ($currcat ne '') {
13542: @currcategories = split('&',$currcat);
13543: }
13544: my $table;
13545: for (my $i=0; $i<@{$cats[0]}; $i++) {
13546: my $parent = $cats[0][$i];
13547: next if ($parent eq 'instcode');
13548: if ($type eq 'Community') {
13549: next unless ($parent eq 'communities');
13550: } else {
13551: next if ($parent eq 'communities');
13552: }
13553: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13554: my $item = &escape($parent).'::0';
13555: my $checked = '';
13556: if (@currcategories > 0) {
13557: if (grep(/^\Q$item\E$/,@currcategories)) {
13558: $checked = ' checked="checked"';
13559: }
13560: }
13561: my $parent_title = $parent;
13562: if ($parent eq 'communities') {
13563: $parent_title = &mt('Communities');
13564: }
13565: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13566: '<input type="checkbox" name="usecategory" value="'.
13567: $item.'"'.$checked.' />'.$parent_title.'</span>'.
13568: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13569: my $depth = 1;
13570: push(@path,$parent);
13571: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13572: pop(@path);
13573: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13574: $itemcount ++;
13575: }
13576: if ($itemcount) {
13577: $output = &Apache::loncommon::start_data_table().
13578: $table.
13579: &Apache::loncommon::end_data_table();
13580: }
13581: }
13582: }
13583: }
13584: return $output;
13585: }
13586:
13587: =pod
13588:
13589: =item * &assign_category_rows()
13590:
13591: Create a datatable row for display of nested categories in a domain,
13592: with checkboxes to allow a course to be categorized,called recursively.
13593:
13594: Inputs:
13595:
13596: itemcount - track row number for alternating colors
13597:
13598: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13599: categories and subcategories.
13600:
13601: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13602:
13603: parent - parent of current category item
13604:
13605: path - Array containing all categories back up through the hierarchy from the
13606: current category to the top level.
13607:
13608: currcategories - reference to array of current categories assigned to the course
13609:
13610: Returns: $output (markup to be displayed).
13611:
13612: =cut
13613:
13614: sub assign_category_rows {
13615: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13616: my ($text,$name,$item,$chgstr);
13617: if (ref($cats) eq 'ARRAY') {
13618: my $maxdepth = scalar(@{$cats});
13619: if (ref($cats->[$depth]) eq 'HASH') {
13620: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13621: my $numchildren = @{$cats->[$depth]{$parent}};
13622: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13623: $text .= '<td><table class="LC_data_table">';
13624: for (my $j=0; $j<$numchildren; $j++) {
13625: $name = $cats->[$depth]{$parent}[$j];
13626: $item = &escape($name).':'.&escape($parent).':'.$depth;
13627: my $deeper = $depth+1;
13628: my $checked = '';
13629: if (ref($currcategories) eq 'ARRAY') {
13630: if (@{$currcategories} > 0) {
13631: if (grep(/^\Q$item\E$/,@{$currcategories})) {
13632: $checked = ' checked="checked"';
13633: }
13634: }
13635: }
13636: $text .= '<tr><td><span class="LC_nobreak"><label>'.
13637: '<input type="checkbox" name="usecategory" value="'.
13638: $item.'"'.$checked.' />'.$name.'</label></span>'.
13639: '<input type="hidden" name="catname" value="'.$name.'" />'.
13640: '</td><td>';
13641: if (ref($path) eq 'ARRAY') {
13642: push(@{$path},$name);
13643: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13644: pop(@{$path});
13645: }
13646: $text .= '</td></tr>';
13647: }
13648: $text .= '</table></td>';
13649: }
13650: }
13651: }
13652: return $text;
13653: }
13654:
13655: ############################################################
13656: ############################################################
13657:
13658:
13659: sub commit_customrole {
13660: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13661: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13662: ($start?', '.&mt('starting').' '.localtime($start):'').
13663: ($end?', ending '.localtime($end):'').': <b>'.
13664: &Apache::lonnet::assigncustomrole(
13665: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13666: '</b><br />';
13667: return $output;
13668: }
13669:
13670: sub commit_standardrole {
13671: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13672: my ($output,$logmsg,$linefeed);
13673: if ($context eq 'auto') {
13674: $linefeed = "\n";
13675: } else {
13676: $linefeed = "<br />\n";
13677: }
13678: if ($three eq 'st') {
13679: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13680: $one,$two,$sec,$context,$credits);
13681: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
13682: ($result eq 'unknown_course') || ($result eq 'refused')) {
13683: $output = $logmsg.' '.&mt('Error: ').$result."\n";
13684: } else {
13685: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13686: ($start?', '.&mt('starting').' '.localtime($start):'').
13687: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13688: if ($context eq 'auto') {
13689: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13690: } else {
13691: $output .= '<b>'.$result.'</b>'.$linefeed.
13692: &mt('Add to classlist').': <b>ok</b>';
13693: }
13694: $output .= $linefeed;
13695: }
13696: } else {
13697: $output = &mt('Assigning').' '.$three.' in '.$url.
13698: ($start?', '.&mt('starting').' '.localtime($start):'').
13699: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13700: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13701: if ($context eq 'auto') {
13702: $output .= $result.$linefeed;
13703: } else {
13704: $output .= '<b>'.$result.'</b>'.$linefeed;
13705: }
13706: }
13707: return $output;
13708: }
13709:
13710: sub commit_studentrole {
13711: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13712: $credits) = @_;
13713: my ($result,$linefeed,$oldsecurl,$newsecurl);
13714: if ($context eq 'auto') {
13715: $linefeed = "\n";
13716: } else {
13717: $linefeed = '<br />'."\n";
13718: }
13719: if (defined($one) && defined($two)) {
13720: my $cid=$one.'_'.$two;
13721: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13722: my $secchange = 0;
13723: my $expire_role_result;
13724: my $modify_section_result;
13725: if ($oldsec ne '-1') {
13726: if ($oldsec ne $sec) {
13727: $secchange = 1;
13728: my $now = time;
13729: my $uurl='/'.$cid;
13730: $uurl=~s/\_/\//g;
13731: if ($oldsec) {
13732: $uurl.='/'.$oldsec;
13733: }
13734: $oldsecurl = $uurl;
13735: $expire_role_result =
13736: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13737: if ($env{'request.course.sec'} ne '') {
13738: if ($expire_role_result eq 'refused') {
13739: my @roles = ('st');
13740: my @statuses = ('previous');
13741: my @roledoms = ($one);
13742: my $withsec = 1;
13743: my %roleshash =
13744: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13745: \@statuses,\@roles,\@roledoms,$withsec);
13746: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13747: my ($oldstart,$oldend) =
13748: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13749: if ($oldend > 0 && $oldend <= $now) {
13750: $expire_role_result = 'ok';
13751: }
13752: }
13753: }
13754: }
13755: $result = $expire_role_result;
13756: }
13757: }
13758: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13759: $modify_section_result =
13760: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13761: undef,undef,undef,$sec,
13762: $end,$start,'','',$cid,
13763: '',$context,$credits);
13764: if ($modify_section_result =~ /^ok/) {
13765: if ($secchange == 1) {
13766: if ($sec eq '') {
13767: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13768: } else {
13769: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13770: }
13771: } elsif ($oldsec eq '-1') {
13772: if ($sec eq '') {
13773: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13774: } else {
13775: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13776: }
13777: } else {
13778: if ($sec eq '') {
13779: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13780: } else {
13781: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13782: }
13783: }
13784: } else {
13785: if ($secchange) {
13786: $$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;
13787: } else {
13788: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13789: }
13790: }
13791: $result = $modify_section_result;
13792: } elsif ($secchange == 1) {
13793: if ($oldsec eq '') {
13794: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13795: } else {
13796: $$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;
13797: }
13798: if ($expire_role_result eq 'refused') {
13799: my $newsecurl = '/'.$cid;
13800: $newsecurl =~ s/\_/\//g;
13801: if ($sec ne '') {
13802: $newsecurl.='/'.$sec;
13803: }
13804: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13805: if ($sec eq '') {
13806: $$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;
13807: } else {
13808: $$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;
13809: }
13810: }
13811: }
13812: }
13813: } else {
13814: $$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;
13815: $result = "error: incomplete course id\n";
13816: }
13817: return $result;
13818: }
13819:
13820: sub show_role_extent {
13821: my ($scope,$context,$role) = @_;
13822: $scope =~ s{^/}{};
13823: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13824: push(@courseroles,'co');
13825: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13826: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13827: $scope =~ s{/}{_};
13828: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13829: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13830: my ($audom,$auname) = split(/\//,$scope);
13831: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13832: &Apache::loncommon::plainname($auname,$audom).'</span>');
13833: } else {
13834: $scope =~ s{/$}{};
13835: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13836: &Apache::lonnet::domain($scope,'description').'</span>');
13837: }
13838: }
13839:
13840: ############################################################
13841: ############################################################
13842:
13843: sub check_clone {
13844: my ($args,$linefeed) = @_;
13845: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13846: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13847: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13848: my $clonemsg;
13849: my $can_clone = 0;
13850: my $lctype = lc($args->{'crstype'});
13851: if ($lctype ne 'community') {
13852: $lctype = 'course';
13853: }
13854: if ($clonehome eq 'no_host') {
13855: if ($args->{'crstype'} eq 'Community') {
13856: $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'});
13857: } else {
13858: $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'});
13859: }
13860: } else {
13861: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13862: if ($args->{'crstype'} eq 'Community') {
13863: if ($clonedesc{'type'} ne 'Community') {
13864: $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'});
13865: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13866: }
13867: }
13868: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
13869: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13870: $can_clone = 1;
13871: } else {
13872: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13873: $args->{'clonedomain'},$args->{'clonecourse'});
13874: my @cloners = split(/,/,$clonehash{'cloners'});
13875: if (grep(/^\*$/,@cloners)) {
13876: $can_clone = 1;
13877: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13878: $can_clone = 1;
13879: } else {
13880: my $ccrole = 'cc';
13881: if ($args->{'crstype'} eq 'Community') {
13882: $ccrole = 'co';
13883: }
13884: my %roleshash =
13885: &Apache::lonnet::get_my_roles($args->{'ccuname'},
13886: $args->{'ccdomain'},
13887: 'userroles',['active'],[$ccrole],
13888: [$args->{'clonedomain'}]);
13889: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13890: $can_clone = 1;
13891: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13892: $can_clone = 1;
13893: } else {
13894: if ($args->{'crstype'} eq 'Community') {
13895: $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'});
13896: } else {
13897: $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'});
13898: }
13899: }
13900: }
13901: }
13902: }
13903: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13904: }
13905:
13906: sub construct_course {
13907: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
13908: my $outcome;
13909: my $linefeed = '<br />'."\n";
13910: if ($context eq 'auto') {
13911: $linefeed = "\n";
13912: }
13913:
13914: #
13915: # Are we cloning?
13916: #
13917: my ($can_clone, $clonemsg, $cloneid, $clonehome);
13918: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13919: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13920: if ($context ne 'auto') {
13921: if ($clonemsg ne '') {
13922: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13923: }
13924: }
13925: $outcome .= $clonemsg.$linefeed;
13926:
13927: if (!$can_clone) {
13928: return (0,$outcome);
13929: }
13930: }
13931:
13932: #
13933: # Open course
13934: #
13935: my $crstype = lc($args->{'crstype'});
13936: my %cenv=();
13937: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13938: $args->{'cdescr'},
13939: $args->{'curl'},
13940: $args->{'course_home'},
13941: $args->{'nonstandard'},
13942: $args->{'crscode'},
13943: $args->{'ccuname'}.':'.
13944: $args->{'ccdomain'},
13945: $args->{'crstype'},
13946: $cnum,$context,$category);
13947:
13948: # Note: The testing routines depend on this being output; see
13949: # Utils::Course. This needs to at least be output as a comment
13950: # if anyone ever decides to not show this, and Utils::Course::new
13951: # will need to be suitably modified.
13952: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13953: if ($$courseid =~ /^error:/) {
13954: return (0,$outcome);
13955: }
13956:
13957: #
13958: # Check if created correctly
13959: #
13960: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13961: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13962: if ($crsuhome eq 'no_host') {
13963: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13964: return (0,$outcome);
13965: }
13966: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13967:
13968: #
13969: # Do the cloning
13970: #
13971: if ($can_clone && $cloneid) {
13972: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13973: if ($context ne 'auto') {
13974: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13975: }
13976: $outcome .= $clonemsg.$linefeed;
13977: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13978: # Copy all files
13979: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13980: # Restore URL
13981: $cenv{'url'}=$oldcenv{'url'};
13982: # Restore title
13983: $cenv{'description'}=$oldcenv{'description'};
13984: # Restore creation date, creator and creation context.
13985: $cenv{'internal.created'}=$oldcenv{'internal.created'};
13986: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13987: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13988: # Mark as cloned
13989: $cenv{'clonedfrom'}=$cloneid;
13990: # Need to clone grading mode
13991: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13992: $cenv{'grading'}=$newenv{'grading'};
13993: # Do not clone these environment entries
13994: &Apache::lonnet::del('environment',
13995: ['default_enrollment_start_date',
13996: 'default_enrollment_end_date',
13997: 'question.email',
13998: 'policy.email',
13999: 'comment.email',
14000: 'pch.users.denied',
14001: 'plc.users.denied',
14002: 'hidefromcat',
14003: 'checkforpriv',
14004: 'categories',
14005: 'internal.uniquecode'],
14006: $$crsudom,$$crsunum);
14007: }
14008:
14009: #
14010: # Set environment (will override cloned, if existing)
14011: #
14012: my @sections = ();
14013: my @xlists = ();
14014: if ($args->{'crstype'}) {
14015: $cenv{'type'}=$args->{'crstype'};
14016: }
14017: if ($args->{'crsid'}) {
14018: $cenv{'courseid'}=$args->{'crsid'};
14019: }
14020: if ($args->{'crscode'}) {
14021: $cenv{'internal.coursecode'}=$args->{'crscode'};
14022: }
14023: if ($args->{'crsquota'} ne '') {
14024: $cenv{'internal.coursequota'}=$args->{'crsquota'};
14025: } else {
14026: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14027: }
14028: if ($args->{'ccuname'}) {
14029: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14030: ':'.$args->{'ccdomain'};
14031: } else {
14032: $cenv{'internal.courseowner'} = $args->{'curruser'};
14033: }
14034: if ($args->{'defaultcredits'}) {
14035: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14036: }
14037: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14038: if ($args->{'crssections'}) {
14039: $cenv{'internal.sectionnums'} = '';
14040: if ($args->{'crssections'} =~ m/,/) {
14041: @sections = split/,/,$args->{'crssections'};
14042: } else {
14043: $sections[0] = $args->{'crssections'};
14044: }
14045: if (@sections > 0) {
14046: foreach my $item (@sections) {
14047: my ($sec,$gp) = split/:/,$item;
14048: my $class = $args->{'crscode'}.$sec;
14049: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14050: $cenv{'internal.sectionnums'} .= $item.',';
14051: unless ($addcheck eq 'ok') {
14052: push @badclasses, $class;
14053: }
14054: }
14055: $cenv{'internal.sectionnums'} =~ s/,$//;
14056: }
14057: }
14058: # do not hide course coordinator from staff listing,
14059: # even if privileged
14060: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14061: # add course coordinator's domain to domains to check for privileged users
14062: # if different to course domain
14063: if ($$crsudom ne $args->{'ccdomain'}) {
14064: $cenv{'checkforpriv'} = $args->{'ccdomain'};
14065: }
14066: # add crosslistings
14067: if ($args->{'crsxlist'}) {
14068: $cenv{'internal.crosslistings'}='';
14069: if ($args->{'crsxlist'} =~ m/,/) {
14070: @xlists = split/,/,$args->{'crsxlist'};
14071: } else {
14072: $xlists[0] = $args->{'crsxlist'};
14073: }
14074: if (@xlists > 0) {
14075: foreach my $item (@xlists) {
14076: my ($xl,$gp) = split/:/,$item;
14077: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14078: $cenv{'internal.crosslistings'} .= $item.',';
14079: unless ($addcheck eq 'ok') {
14080: push @badclasses, $xl;
14081: }
14082: }
14083: $cenv{'internal.crosslistings'} =~ s/,$//;
14084: }
14085: }
14086: if ($args->{'autoadds'}) {
14087: $cenv{'internal.autoadds'}=$args->{'autoadds'};
14088: }
14089: if ($args->{'autodrops'}) {
14090: $cenv{'internal.autodrops'}=$args->{'autodrops'};
14091: }
14092: # check for notification of enrollment changes
14093: my @notified = ();
14094: if ($args->{'notify_owner'}) {
14095: if ($args->{'ccuname'} ne '') {
14096: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14097: }
14098: }
14099: if ($args->{'notify_dc'}) {
14100: if ($uname ne '') {
14101: push(@notified,$uname.':'.$udom);
14102: }
14103: }
14104: if (@notified > 0) {
14105: my $notifylist;
14106: if (@notified > 1) {
14107: $notifylist = join(',',@notified);
14108: } else {
14109: $notifylist = $notified[0];
14110: }
14111: $cenv{'internal.notifylist'} = $notifylist;
14112: }
14113: if (@badclasses > 0) {
14114: my %lt=&Apache::lonlocal::texthash(
14115: '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',
14116: 'dnhr' => 'does not have rights to access enrollment in these classes',
14117: 'adby' => 'as determined by the policies of your institution on access to official classlists'
14118: );
14119: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14120: ' ('.$lt{'adby'}.')';
14121: if ($context eq 'auto') {
14122: $outcome .= $badclass_msg.$linefeed;
14123: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14124: foreach my $item (@badclasses) {
14125: if ($context eq 'auto') {
14126: $outcome .= " - $item\n";
14127: } else {
14128: $outcome .= "<li>$item</li>\n";
14129: }
14130: }
14131: if ($context eq 'auto') {
14132: $outcome .= $linefeed;
14133: } else {
14134: $outcome .= "</ul><br /><br /></div>\n";
14135: }
14136: }
14137: }
14138: if ($args->{'no_end_date'}) {
14139: $args->{'endaccess'} = 0;
14140: }
14141: $cenv{'internal.autostart'}=$args->{'enrollstart'};
14142: $cenv{'internal.autoend'}=$args->{'enrollend'};
14143: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14144: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14145: if ($args->{'showphotos'}) {
14146: $cenv{'internal.showphotos'}=$args->{'showphotos'};
14147: }
14148: $cenv{'internal.authtype'} = $args->{'authtype'};
14149: $cenv{'internal.autharg'} = $args->{'autharg'};
14150: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14151: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
14152: 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');
14153: if ($context eq 'auto') {
14154: $outcome .= $krb_msg;
14155: } else {
14156: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14157: }
14158: $outcome .= $linefeed;
14159: }
14160: }
14161: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14162: if ($args->{'setpolicy'}) {
14163: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14164: }
14165: if ($args->{'setcontent'}) {
14166: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14167: }
14168: }
14169: if ($args->{'reshome'}) {
14170: $cenv{'reshome'}=$args->{'reshome'}.'/';
14171: $cenv{'reshome'}=~s/\/+$/\//;
14172: }
14173: #
14174: # course has keyed access
14175: #
14176: if ($args->{'setkeys'}) {
14177: $cenv{'keyaccess'}='yes';
14178: }
14179: # if specified, key authority is not course, but user
14180: # only active if keyaccess is yes
14181: if ($args->{'keyauth'}) {
14182: my ($user,$domain) = split(':',$args->{'keyauth'});
14183: $user = &LONCAPA::clean_username($user);
14184: $domain = &LONCAPA::clean_username($domain);
14185: if ($user ne '' && $domain ne '') {
14186: $cenv{'keyauth'}=$user.':'.$domain;
14187: }
14188: }
14189:
14190: #
14191: # generate and store uniquecode (available to course requester), if course should have one.
14192: #
14193: if ($args->{'uniquecode'}) {
14194: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14195: if ($code) {
14196: $cenv{'internal.uniquecode'} = $code;
14197: my %crsinfo =
14198: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14199: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14200: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14201: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14202: }
14203: if (ref($coderef)) {
14204: $$coderef = $code;
14205: }
14206: }
14207: }
14208:
14209: if ($args->{'disresdis'}) {
14210: $cenv{'pch.roles.denied'}='st';
14211: }
14212: if ($args->{'disablechat'}) {
14213: $cenv{'plc.roles.denied'}='st';
14214: }
14215:
14216: # Record we've not yet viewed the Course Initialization Helper for this
14217: # course
14218: $cenv{'course.helper.not.run'} = 1;
14219: #
14220: # Use new Randomseed
14221: #
14222: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14223: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14224: #
14225: # The encryption code and receipt prefix for this course
14226: #
14227: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14228: $cenv{'internal.encpref'}=100+int(9*rand(99));
14229: #
14230: # By default, use standard grading
14231: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14232:
14233: $outcome .= $linefeed.&mt('Setting environment').': '.
14234: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14235: #
14236: # Open all assignments
14237: #
14238: if ($args->{'openall'}) {
14239: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14240: my %storecontent = ($storeunder => time,
14241: $storeunder.'.type' => 'date_start');
14242:
14243: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14244: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14245: }
14246: #
14247: # Set first page
14248: #
14249: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14250: || ($cloneid)) {
14251: use LONCAPA::map;
14252: $outcome .= &mt('Setting first resource').': ';
14253:
14254: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14255: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14256:
14257: $outcome .= ($fatal?$errtext:'read ok').' - ';
14258: my $title; my $url;
14259: if ($args->{'firstres'} eq 'syl') {
14260: $title=&mt('Syllabus');
14261: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14262: } else {
14263: $title=&mt('Table of Contents');
14264: $url='/adm/navmaps';
14265: }
14266:
14267: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14268: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14269:
14270: if ($errtext) { $fatal=2; }
14271: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14272: }
14273:
14274: return (1,$outcome);
14275: }
14276:
14277: sub make_unique_code {
14278: my ($cdom,$cnum) = @_;
14279: # get lock on uniquecodes db
14280: my $lockhash = {
14281: $cnum."\0".'uniquecodes' => $env{'user.name'}.
14282: ':'.$env{'user.domain'},
14283: };
14284: my $tries = 0;
14285: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14286: my ($code,$error);
14287:
14288: while (($gotlock ne 'ok') && ($tries<3)) {
14289: $tries ++;
14290: sleep 1;
14291: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14292: }
14293: if ($gotlock eq 'ok') {
14294: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14295: my $gotcode;
14296: my $attempts = 0;
14297: while ((!$gotcode) && ($attempts < 100)) {
14298: $code = &generate_code();
14299: if (!exists($currcodes{$code})) {
14300: $gotcode = 1;
14301: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14302: $error = 'nostore';
14303: }
14304: }
14305: $attempts ++;
14306: }
14307: my @del_lock = ($cnum."\0".'uniquecodes');
14308: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14309: } else {
14310: $error = 'nolock';
14311: }
14312: return ($code,$error);
14313: }
14314:
14315: sub generate_code {
14316: my $code;
14317: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14318: for (my $i=0; $i<6; $i++) {
14319: my $lettnum = int (rand 2);
14320: my $item = '';
14321: if ($lettnum) {
14322: $item = $letts[int( rand(18) )];
14323: } else {
14324: $item = 1+int( rand(8) );
14325: }
14326: $code .= $item;
14327: }
14328: return $code;
14329: }
14330:
14331: ############################################################
14332: ############################################################
14333:
14334: #SD
14335: # only Community and Course, or anything else?
14336: sub course_type {
14337: my ($cid) = @_;
14338: if (!defined($cid)) {
14339: $cid = $env{'request.course.id'};
14340: }
14341: if (defined($env{'course.'.$cid.'.type'})) {
14342: return $env{'course.'.$cid.'.type'};
14343: } else {
14344: return 'Course';
14345: }
14346: }
14347:
14348: sub group_term {
14349: my $crstype = &course_type();
14350: my %names = (
14351: 'Course' => 'group',
14352: 'Community' => 'group',
14353: );
14354: return $names{$crstype};
14355: }
14356:
14357: sub course_types {
14358: my @types = ('official','unofficial','community','textbook');
14359: my %typename = (
14360: official => 'Official course',
14361: unofficial => 'Unofficial course',
14362: community => 'Community',
14363: textbook => 'Textbook course',
14364: );
14365: return (\@types,\%typename);
14366: }
14367:
14368: sub icon {
14369: my ($file)=@_;
14370: my $curfext = lc((split(/\./,$file))[-1]);
14371: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14372: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14373: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14374: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14375: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14376: $curfext.".gif") {
14377: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14378: $curfext.".gif";
14379: }
14380: }
14381: return &lonhttpdurl($iconname);
14382: }
14383:
14384: sub lonhttpdurl {
14385: #
14386: # Had been used for "small fry" static images on separate port 8080.
14387: # Modify here if lightweight http functionality desired again.
14388: # Currently eliminated due to increasing firewall issues.
14389: #
14390: my ($url)=@_;
14391: return $url;
14392: }
14393:
14394: sub connection_aborted {
14395: my ($r)=@_;
14396: $r->print(" ");$r->rflush();
14397: my $c = $r->connection;
14398: return $c->aborted();
14399: }
14400:
14401: # Escapes strings that may have embedded 's that will be put into
14402: # strings as 'strings'.
14403: sub escape_single {
14404: my ($input) = @_;
14405: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
14406: $input =~ s/\'/\\\'/g; # Esacpe the 's....
14407: return $input;
14408: }
14409:
14410: # Same as escape_single, but escape's "'s This
14411: # can be used for "strings"
14412: sub escape_double {
14413: my ($input) = @_;
14414: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
14415: $input =~ s/\"/\\\"/g; # Esacpe the "s....
14416: return $input;
14417: }
14418:
14419: # Escapes the last element of a full URL.
14420: sub escape_url {
14421: my ($url) = @_;
14422: my @urlslices = split(/\//, $url,-1);
14423: my $lastitem = &escape(pop(@urlslices));
14424: return join('/',@urlslices).'/'.$lastitem;
14425: }
14426:
14427: sub compare_arrays {
14428: my ($arrayref1,$arrayref2) = @_;
14429: my (@difference,%count);
14430: @difference = ();
14431: %count = ();
14432: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14433: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14434: foreach my $element (keys(%count)) {
14435: if ($count{$element} == 1) {
14436: push(@difference,$element);
14437: }
14438: }
14439: }
14440: return @difference;
14441: }
14442:
14443: # -------------------------------------------------------- Initialize user login
14444: sub init_user_environment {
14445: my ($r, $username, $domain, $authhost, $form, $args) = @_;
14446: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14447:
14448: my $public=($username eq 'public' && $domain eq 'public');
14449:
14450: # See if old ID present, if so, remove
14451:
14452: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14453: my $now=time;
14454:
14455: if ($public) {
14456: my $max_public=100;
14457: my $oldest;
14458: my $oldest_time=0;
14459: for(my $next=1;$next<=$max_public;$next++) {
14460: if (-e $lonids."/publicuser_$next.id") {
14461: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14462: if ($mtime<$oldest_time || !$oldest_time) {
14463: $oldest_time=$mtime;
14464: $oldest=$next;
14465: }
14466: } else {
14467: $cookie="publicuser_$next";
14468: last;
14469: }
14470: }
14471: if (!$cookie) { $cookie="publicuser_$oldest"; }
14472: } else {
14473: # if this isn't a robot, kill any existing non-robot sessions
14474: if (!$args->{'robot'}) {
14475: opendir(DIR,$lonids);
14476: while ($filename=readdir(DIR)) {
14477: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14478: unlink($lonids.'/'.$filename);
14479: }
14480: }
14481: closedir(DIR);
14482: }
14483: # Give them a new cookie
14484: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14485: : $now.$$.int(rand(10000)));
14486: $cookie="$username\_$id\_$domain\_$authhost";
14487:
14488: # Initialize roles
14489:
14490: ($userroles,$firstaccenv,$timerintenv) =
14491: &Apache::lonnet::rolesinit($domain,$username,$authhost);
14492: }
14493: # ------------------------------------ Check browser type and MathML capability
14494:
14495: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14496: $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14497:
14498: # ------------------------------------------------------------- Get environment
14499:
14500: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14501: my ($tmp) = keys(%userenv);
14502: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14503: } else {
14504: undef(%userenv);
14505: }
14506: if (($userenv{'interface'}) && (!$form->{'interface'})) {
14507: $form->{'interface'}=$userenv{'interface'};
14508: }
14509: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14510:
14511: # --------------- Do not trust query string to be put directly into environment
14512: foreach my $option ('interface','localpath','localres') {
14513: $form->{$option}=~s/[\n\r\=]//gs;
14514: }
14515: # --------------------------------------------------------- Write first profile
14516:
14517: {
14518: my %initial_env =
14519: ("user.name" => $username,
14520: "user.domain" => $domain,
14521: "user.home" => $authhost,
14522: "browser.type" => $clientbrowser,
14523: "browser.version" => $clientversion,
14524: "browser.mathml" => $clientmathml,
14525: "browser.unicode" => $clientunicode,
14526: "browser.os" => $clientos,
14527: "browser.mobile" => $clientmobile,
14528: "browser.info" => $clientinfo,
14529: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
14530: "request.course.fn" => '',
14531: "request.course.uri" => '',
14532: "request.course.sec" => '',
14533: "request.role" => 'cm',
14534: "request.role.adv" => $env{'user.adv'},
14535: "request.host" => $ENV{'REMOTE_ADDR'},);
14536:
14537: if ($form->{'localpath'}) {
14538: $initial_env{"browser.localpath"} = $form->{'localpath'};
14539: $initial_env{"browser.localres"} = $form->{'localres'};
14540: }
14541:
14542: if ($form->{'interface'}) {
14543: $form->{'interface'}=~s/\W//gs;
14544: $initial_env{"browser.interface"} = $form->{'interface'};
14545: $env{'browser.interface'}=$form->{'interface'};
14546: }
14547:
14548: if ($form->{'iptoken'}) {
14549: my $lonhost = $r->dir_config('lonHostID');
14550: $initial_env{"user.noloadbalance"} = $lonhost;
14551: $env{'user.noloadbalance'} = $lonhost;
14552: }
14553:
14554: my %is_adv = ( is_adv => $env{'user.adv'} );
14555: my %domdef;
14556: unless ($domain eq 'public') {
14557: %domdef = &Apache::lonnet::get_domain_defaults($domain);
14558: }
14559:
14560: foreach my $tool ('aboutme','blog','webdav','portfolio') {
14561: $userenv{'availabletools.'.$tool} =
14562: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14563: undef,\%userenv,\%domdef,\%is_adv);
14564: }
14565:
14566: foreach my $crstype ('official','unofficial','community','textbook') {
14567: $userenv{'canrequest.'.$crstype} =
14568: &Apache::lonnet::usertools_access($username,$domain,$crstype,
14569: 'reload','requestcourses',
14570: \%userenv,\%domdef,\%is_adv);
14571: }
14572:
14573: $userenv{'canrequest.author'} =
14574: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14575: 'reload','requestauthor',
14576: \%userenv,\%domdef,\%is_adv);
14577: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14578: $domain,$username);
14579: my $reqstatus = $reqauthor{'author_status'};
14580: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14581: if (ref($reqauthor{'author'}) eq 'HASH') {
14582: $userenv{'requestauthorqueued'} = $reqstatus.':'.
14583: $reqauthor{'author'}{'timestamp'};
14584: }
14585: }
14586:
14587: $env{'user.environment'} = "$lonids/$cookie.id";
14588:
14589: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14590: &GDBM_WRCREAT(),0640)) {
14591: &_add_to_env(\%disk_env,\%initial_env);
14592: &_add_to_env(\%disk_env,\%userenv,'environment.');
14593: &_add_to_env(\%disk_env,$userroles);
14594: if (ref($firstaccenv) eq 'HASH') {
14595: &_add_to_env(\%disk_env,$firstaccenv);
14596: }
14597: if (ref($timerintenv) eq 'HASH') {
14598: &_add_to_env(\%disk_env,$timerintenv);
14599: }
14600: if (ref($args->{'extra_env'})) {
14601: &_add_to_env(\%disk_env,$args->{'extra_env'});
14602: }
14603: untie(%disk_env);
14604: } else {
14605: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14606: 'Could not create environment storage in lonauth: '.$!.'</span>');
14607: return 'error: '.$!;
14608: }
14609: }
14610: $env{'request.role'}='cm';
14611: $env{'request.role.adv'}=$env{'user.adv'};
14612: $env{'browser.type'}=$clientbrowser;
14613:
14614: return $cookie;
14615:
14616: }
14617:
14618: sub _add_to_env {
14619: my ($idf,$env_data,$prefix) = @_;
14620: if (ref($env_data) eq 'HASH') {
14621: while (my ($key,$value) = each(%$env_data)) {
14622: $idf->{$prefix.$key} = $value;
14623: $env{$prefix.$key} = $value;
14624: }
14625: }
14626: }
14627:
14628: # --- Get the symbolic name of a problem and the url
14629: sub get_symb {
14630: my ($request,$silent) = @_;
14631: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14632: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14633: if ($symb eq '') {
14634: if (!$silent) {
14635: if (ref($request)) {
14636: $request->print("Unable to handle ambiguous references:$url:.");
14637: }
14638: return ();
14639: }
14640: }
14641: &Apache::lonenc::check_decrypt(\$symb);
14642: return ($symb);
14643: }
14644:
14645: # --------------------------------------------------------------Get annotation
14646:
14647: sub get_annotation {
14648: my ($symb,$enc) = @_;
14649:
14650: my $key = $symb;
14651: if (!$enc) {
14652: $key =
14653: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14654: }
14655: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14656: return $annotation{$key};
14657: }
14658:
14659: sub clean_symb {
14660: my ($symb,$delete_enc) = @_;
14661:
14662: &Apache::lonenc::check_decrypt(\$symb);
14663: my $enc = $env{'request.enc'};
14664: if ($delete_enc) {
14665: delete($env{'request.enc'});
14666: }
14667:
14668: return ($symb,$enc);
14669: }
14670:
14671: sub build_release_hashes {
14672: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14673: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14674: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14675: (ref($randomizetry) eq 'HASH'));
14676: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14677: my ($item,$name,$value) = split(/:/,$key);
14678: if ($item eq 'parameter') {
14679: if (ref($checkparms->{$name}) eq 'ARRAY') {
14680: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14681: push(@{$checkparms->{$name}},$value);
14682: }
14683: } else {
14684: push(@{$checkparms->{$name}},$value);
14685: }
14686: } elsif ($item eq 'resourcetag') {
14687: if ($name eq 'responsetype') {
14688: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14689: }
14690: } elsif ($item eq 'course') {
14691: if ($name eq 'crstype') {
14692: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14693: }
14694: }
14695: }
14696: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14697: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14698: return;
14699: }
14700:
14701: sub update_content_constraints {
14702: my ($cdom,$cnum,$chome,$cid) = @_;
14703: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14704: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14705: my %checkresponsetypes;
14706: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14707: my ($item,$name,$value) = split(/:/,$key);
14708: if ($item eq 'resourcetag') {
14709: if ($name eq 'responsetype') {
14710: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14711: }
14712: }
14713: }
14714: my $navmap = Apache::lonnavmaps::navmap->new();
14715: if (defined($navmap)) {
14716: my %allresponses;
14717: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14718: my %responses = $res->responseTypes();
14719: foreach my $key (keys(%responses)) {
14720: next unless(exists($checkresponsetypes{$key}));
14721: $allresponses{$key} += $responses{$key};
14722: }
14723: }
14724: foreach my $key (keys(%allresponses)) {
14725: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14726: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14727: ($reqdmajor,$reqdminor) = ($major,$minor);
14728: }
14729: }
14730: undef($navmap);
14731: }
14732: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14733: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14734: }
14735: return;
14736: }
14737:
14738: sub allmaps_incourse {
14739: my ($cdom,$cnum,$chome,$cid) = @_;
14740: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14741: $cid = $env{'request.course.id'};
14742: $cdom = $env{'course.'.$cid.'.domain'};
14743: $cnum = $env{'course.'.$cid.'.num'};
14744: $chome = $env{'course.'.$cid.'.home'};
14745: }
14746: my %allmaps = ();
14747: my $lastchange =
14748: &Apache::lonnet::get_coursechange($cdom,$cnum);
14749: if ($lastchange > $env{'request.course.tied'}) {
14750: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14751: unless ($ferr) {
14752: &update_content_constraints($cdom,$cnum,$chome,$cid);
14753: }
14754: }
14755: my $navmap = Apache::lonnavmaps::navmap->new();
14756: if (defined($navmap)) {
14757: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14758: $allmaps{$res->src()} = 1;
14759: }
14760: }
14761: return \%allmaps;
14762: }
14763:
14764: sub parse_supplemental_title {
14765: my ($title) = @_;
14766:
14767: my ($foldertitle,$renametitle);
14768: if ($title =~ /&&&/) {
14769: $title = &HTML::Entites::decode($title);
14770: }
14771: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14772: $renametitle=$4;
14773: my ($time,$uname,$udom) = ($1,$2,$3);
14774: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14775: my $name = &plainname($uname,$udom);
14776: $name = &HTML::Entities::encode($name,'"<>&\'');
14777: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14778: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14779: $name.': <br />'.$foldertitle;
14780: }
14781: if (wantarray) {
14782: return ($title,$foldertitle,$renametitle);
14783: }
14784: return $title;
14785: }
14786:
14787: sub recurse_supplemental {
14788: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14789: if ($suppmap) {
14790: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14791: if ($fatal) {
14792: $errors ++;
14793: } else {
14794: if ($#LONCAPA::map::resources > 0) {
14795: foreach my $res (@LONCAPA::map::resources) {
14796: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14797: if (($src ne '') && ($status eq 'res')) {
14798: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14799: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14800: } else {
14801: $numfiles ++;
14802: }
14803: }
14804: }
14805: }
14806: }
14807: }
14808: return ($numfiles,$errors);
14809: }
14810:
14811: sub symb_to_docspath {
14812: my ($symb) = @_;
14813: return unless ($symb);
14814: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14815: if ($resurl=~/\.(sequence|page)$/) {
14816: $mapurl=$resurl;
14817: } elsif ($resurl eq 'adm/navmaps') {
14818: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14819: }
14820: my $mapresobj;
14821: my $navmap = Apache::lonnavmaps::navmap->new();
14822: if (ref($navmap)) {
14823: $mapresobj = $navmap->getResourceByUrl($mapurl);
14824: }
14825: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14826: my $type=$2;
14827: my $path;
14828: if (ref($mapresobj)) {
14829: my $pcslist = $mapresobj->map_hierarchy();
14830: if ($pcslist ne '') {
14831: foreach my $pc (split(/,/,$pcslist)) {
14832: next if ($pc <= 1);
14833: my $res = $navmap->getByMapPc($pc);
14834: if (ref($res)) {
14835: my $thisurl = $res->src();
14836: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14837: my $thistitle = $res->title();
14838: $path .= '&'.
14839: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14840: &escape($thistitle).
14841: ':'.$res->randompick().
14842: ':'.$res->randomout().
14843: ':'.$res->encrypted().
14844: ':'.$res->randomorder().
14845: ':'.$res->is_page();
14846: }
14847: }
14848: }
14849: $path =~ s/^\&//;
14850: my $maptitle = $mapresobj->title();
14851: if ($mapurl eq 'default') {
14852: $maptitle = 'Main Content';
14853: }
14854: $path .= (($path ne '')? '&' : '').
14855: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14856: &escape($maptitle).
14857: ':'.$mapresobj->randompick().
14858: ':'.$mapresobj->randomout().
14859: ':'.$mapresobj->encrypted().
14860: ':'.$mapresobj->randomorder().
14861: ':'.$mapresobj->is_page();
14862: } else {
14863: my $maptitle = &Apache::lonnet::gettitle($mapurl);
14864: my $ispage = (($type eq 'page')? 1 : '');
14865: if ($mapurl eq 'default') {
14866: $maptitle = 'Main Content';
14867: }
14868: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14869: &escape($maptitle).':::::'.$ispage;
14870: }
14871: unless ($mapurl eq 'default') {
14872: $path = 'default&'.
14873: &escape('Main Content').
14874: ':::::&'.$path;
14875: }
14876: return $path;
14877: }
14878:
14879: sub captcha_display {
14880: my ($context,$lonhost) = @_;
14881: my ($output,$error);
14882: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14883: if ($captcha eq 'original') {
14884: $output = &create_captcha();
14885: unless ($output) {
14886: $error = 'captcha';
14887: }
14888: } elsif ($captcha eq 'recaptcha') {
14889: $output = &create_recaptcha($pubkey);
14890: unless ($output) {
14891: $error = 'recaptcha';
14892: }
14893: }
14894: return ($output,$error);
14895: }
14896:
14897: sub captcha_response {
14898: my ($context,$lonhost) = @_;
14899: my ($captcha_chk,$captcha_error);
14900: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14901: if ($captcha eq 'original') {
14902: ($captcha_chk,$captcha_error) = &check_captcha();
14903: } elsif ($captcha eq 'recaptcha') {
14904: $captcha_chk = &check_recaptcha($privkey);
14905: } else {
14906: $captcha_chk = 1;
14907: }
14908: return ($captcha_chk,$captcha_error);
14909: }
14910:
14911: sub get_captcha_config {
14912: my ($context,$lonhost) = @_;
14913: my ($captcha,$pubkey,$privkey,$hashtocheck);
14914: my $hostname = &Apache::lonnet::hostname($lonhost);
14915: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14916: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14917: if ($context eq 'usercreation') {
14918: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14919: if (ref($domconfig{$context}) eq 'HASH') {
14920: $hashtocheck = $domconfig{$context}{'cancreate'};
14921: if (ref($hashtocheck) eq 'HASH') {
14922: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14923: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14924: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14925: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14926: }
14927: if ($privkey && $pubkey) {
14928: $captcha = 'recaptcha';
14929: } else {
14930: $captcha = 'original';
14931: }
14932: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14933: $captcha = 'original';
14934: }
14935: }
14936: } else {
14937: $captcha = 'captcha';
14938: }
14939: } elsif ($context eq 'login') {
14940: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14941: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14942: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14943: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14944: if ($privkey && $pubkey) {
14945: $captcha = 'recaptcha';
14946: } else {
14947: $captcha = 'original';
14948: }
14949: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14950: $captcha = 'original';
14951: }
14952: }
14953: return ($captcha,$pubkey,$privkey);
14954: }
14955:
14956: sub create_captcha {
14957: my %captcha_params = &captcha_settings();
14958: my ($output,$maxtries,$tries) = ('',10,0);
14959: while ($tries < $maxtries) {
14960: $tries ++;
14961: my $captcha = Authen::Captcha->new (
14962: output_folder => $captcha_params{'output_dir'},
14963: data_folder => $captcha_params{'db_dir'},
14964: );
14965: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14966:
14967: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14968: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14969: &mt('Type in the letters/numbers shown below').' '.
14970: '<input type="text" size="5" name="code" value="" /><br />'.
14971: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14972: last;
14973: }
14974: }
14975: return $output;
14976: }
14977:
14978: sub captcha_settings {
14979: my %captcha_params = (
14980: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14981: www_output_dir => "/captchaspool",
14982: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14983: numchars => '5',
14984: );
14985: return %captcha_params;
14986: }
14987:
14988: sub check_captcha {
14989: my ($captcha_chk,$captcha_error);
14990: my $code = $env{'form.code'};
14991: my $md5sum = $env{'form.crypt'};
14992: my %captcha_params = &captcha_settings();
14993: my $captcha = Authen::Captcha->new(
14994: output_folder => $captcha_params{'output_dir'},
14995: data_folder => $captcha_params{'db_dir'},
14996: );
14997: $captcha_chk = $captcha->check_code($code,$md5sum);
14998: my %captcha_hash = (
14999: 0 => 'Code not checked (file error)',
15000: -1 => 'Failed: code expired',
15001: -2 => 'Failed: invalid code (not in database)',
15002: -3 => 'Failed: invalid code (code does not match crypt)',
15003: );
15004: if ($captcha_chk != 1) {
15005: $captcha_error = $captcha_hash{$captcha_chk}
15006: }
15007: return ($captcha_chk,$captcha_error);
15008: }
15009:
15010: sub create_recaptcha {
15011: my ($pubkey) = @_;
15012: my $use_ssl;
15013: if ($ENV{'SERVER_PORT'} == 443) {
15014: $use_ssl = 1;
15015: }
15016: my $captcha = Captcha::reCAPTCHA->new;
15017: return $captcha->get_options_setter({theme => 'white'})."\n".
15018: $captcha->get_html($pubkey,undef,$use_ssl).
15019: &mt('If either word is hard to read, [_1] will replace them.',
15020: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15021: '<br /><br />';
15022: }
15023:
15024: sub check_recaptcha {
15025: my ($privkey) = @_;
15026: my $captcha_chk;
15027: my $captcha = Captcha::reCAPTCHA->new;
15028: my $captcha_result =
15029: $captcha->check_answer(
15030: $privkey,
15031: $ENV{'REMOTE_ADDR'},
15032: $env{'form.recaptcha_challenge_field'},
15033: $env{'form.recaptcha_response_field'},
15034: );
15035: if ($captcha_result->{is_valid}) {
15036: $captcha_chk = 1;
15037: }
15038: return $captcha_chk;
15039: }
15040:
15041: sub cleanup_html {
15042: my ($incoming) = @_;
15043: my $outgoing;
15044: if ($incoming ne '') {
15045: $outgoing = $incoming;
15046: $outgoing =~ s/;/;/g;
15047: $outgoing =~ s/\#/#/g;
15048: $outgoing =~ s/\&/&/g;
15049: $outgoing =~ s/</</g;
15050: $outgoing =~ s/>/>/g;
15051: $outgoing =~ s/\(/(/g;
15052: $outgoing =~ s/\)/)/g;
15053: $outgoing =~ s/"/"/g;
15054: $outgoing =~ s/'/'/g;
15055: $outgoing =~ s/\$/$/g;
15056: $outgoing =~ s{/}{/}g;
15057: $outgoing =~ s/=/=/g;
15058: $outgoing =~ s/\\/\/g
15059: }
15060: return $outgoing;
15061: }
15062:
15063: =pod
15064:
15065: =back
15066:
15067: =cut
15068:
15069: 1;
15070: __END__;
15071:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>