1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.134 2019/07/30 11:10:55 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 Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use DateTime::TimeZone;
75: use DateTime::Locale;
76: use Encode();
77: use Authen::Captcha;
78: use Captcha::reCAPTCHA;
79: use JSON::DWIW;
80: use LWP::UserAgent;
81: use Crypt::DES;
82: use DynaLoader; # for Crypt::DES version
83: use File::Copy();
84: use File::Path();
85:
86: # ---------------------------------------------- Designs
87: use vars qw(%defaultdesign);
88:
89: my $readit;
90:
91:
92: ##
93: ## Global Variables
94: ##
95:
96:
97: # ----------------------------------------------- SSI with retries:
98: #
99:
100: =pod
101:
102: =head1 Server Side include with retries:
103:
104: =over 4
105:
106: =item * &ssi_with_retries(resource,retries form)
107:
108: Performs an ssi with some number of retries. Retries continue either
109: until the result is ok or until the retry count supplied by the
110: caller is exhausted.
111:
112: Inputs:
113:
114: =over 4
115:
116: resource - Identifies the resource to insert.
117:
118: retries - Count of the number of retries allowed.
119:
120: form - Hash that identifies the rendering options.
121:
122: =back
123:
124: Returns:
125:
126: =over 4
127:
128: content - The content of the response. If retries were exhausted this is empty.
129:
130: response - The response from the last attempt (which may or may not have been successful.
131:
132: =back
133:
134: =back
135:
136: =cut
137:
138: sub ssi_with_retries {
139: my ($resource, $retries, %form) = @_;
140:
141:
142: my $ok = 0; # True if we got a good response.
143: my $content;
144: my $response;
145:
146: # Try to get the ssi done. within the retries count:
147:
148: do {
149: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
150: $ok = $response->is_success;
151: if (!$ok) {
152: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
153: }
154: $retries--;
155: } while (!$ok && ($retries > 0));
156:
157: if (!$ok) {
158: $content = ''; # On error return an empty content.
159: }
160: return ($content, $response);
161:
162: }
163:
164:
165:
166: # ----------------------------------------------- Filetypes/Languages/Copyright
167: my %language;
168: my %supported_language;
169: my %latex_language; # For choosing hyphenation in <transl..>
170: my %latex_language_bykey; # for choosing hyphenation from metadata
171: my %cprtag;
172: my %scprtag;
173: my %fe; my %fd; my %fm;
174: my %category_extensions;
175:
176: # ---------------------------------------------- Thesaurus variables
177: #
178: # %Keywords:
179: # A hash used by &keyword to determine if a word is considered a keyword.
180: # $thesaurus_db_file
181: # Scalar containing the full path to the thesaurus database.
182:
183: my %Keywords;
184: my $thesaurus_db_file;
185:
186: #
187: # Initialize values from language.tab, copyright.tab, filetypes.tab,
188: # thesaurus.tab, and filecategories.tab.
189: #
190: BEGIN {
191: # Variable initialization
192: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
193: #
194: unless ($readit) {
195: # ------------------------------------------------------------------- languages
196: {
197: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
198: '/language.tab';
199: if ( open(my $fh,'<',$langtabfile) ) {
200: while (my $line = <$fh>) {
201: next if ($line=~/^\#/);
202: chomp($line);
203: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
204: $language{$key}=$val.' - '.$enc;
205: if ($sup) {
206: $supported_language{$key}=$sup;
207: }
208: if ($latex) {
209: $latex_language_bykey{$key} = $latex;
210: $latex_language{$two} = $latex;
211: }
212: }
213: close($fh);
214: }
215: }
216: # ------------------------------------------------------------------ copyrights
217: {
218: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
219: '/copyright.tab';
220: if ( open (my $fh,'<',$copyrightfile) ) {
221: while (my $line = <$fh>) {
222: next if ($line=~/^\#/);
223: chomp($line);
224: my ($key,$val)=(split(/\s+/,$line,2));
225: $cprtag{$key}=$val;
226: }
227: close($fh);
228: }
229: }
230: # ----------------------------------------------------------- source copyrights
231: {
232: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
233: '/source_copyright.tab';
234: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
235: while (my $line = <$fh>) {
236: next if ($line =~ /^\#/);
237: chomp($line);
238: my ($key,$val)=(split(/\s+/,$line,2));
239: $scprtag{$key}=$val;
240: }
241: close($fh);
242: }
243: }
244:
245: # -------------------------------------------------------------- default domain designs
246: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
247: my $designfile = $designdir.'/default.tab';
248: if ( open (my $fh,'<',$designfile) ) {
249: while (my $line = <$fh>) {
250: next if ($line =~ /^\#/);
251: chomp($line);
252: my ($key,$val)=(split(/\=/,$line));
253: if ($val) { $defaultdesign{$key}=$val; }
254: }
255: close($fh);
256: }
257:
258: # ------------------------------------------------------------- file categories
259: {
260: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
261: '/filecategories.tab';
262: if ( open (my $fh,'<',$categoryfile) ) {
263: while (my $line = <$fh>) {
264: next if ($line =~ /^\#/);
265: chomp($line);
266: my ($extension,$category)=(split(/\s+/,$line,2));
267: push(@{$category_extensions{lc($category)}},$extension);
268: }
269: close($fh);
270: }
271:
272: }
273: # ------------------------------------------------------------------ file types
274: {
275: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
276: '/filetypes.tab';
277: if ( open (my $fh,'<',$typesfile) ) {
278: while (my $line = <$fh>) {
279: next if ($line =~ /^\#/);
280: chomp($line);
281: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
282: if ($descr ne '') {
283: $fe{$ending}=lc($emb);
284: $fd{$ending}=$descr;
285: if ($mime ne 'unk') { $fm{$ending}=$mime; }
286: }
287: }
288: close($fh);
289: }
290: }
291: &Apache::lonnet::logthis(
292: "<span style='color:yellow;'>INFO: Read file types</span>");
293: $readit=1;
294: } # end of unless($readit)
295:
296: }
297:
298: ###############################################################
299: ## HTML and Javascript Helper Functions ##
300: ###############################################################
301:
302: =pod
303:
304: =head1 HTML and Javascript Functions
305:
306: =over 4
307:
308: =item * &browser_and_searcher_javascript()
309:
310: X<browsing, javascript>X<searching, javascript>Returns a string
311: containing javascript with two functions, C<openbrowser> and
312: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
313: tags.
314:
315: =item * &openbrowser(formname,elementname,only,omit) [javascript]
316:
317: inputs: formname, elementname, only, omit
318:
319: formname and elementname indicate the name of the html form and name of
320: the element that the results of the browsing selection are to be placed in.
321:
322: Specifying 'only' will restrict the browser to displaying only files
323: with the given extension. Can be a comma separated list.
324:
325: Specifying 'omit' will restrict the browser to NOT displaying files
326: with the given extension. Can be a comma separated list.
327:
328: =item * &opensearcher(formname,elementname) [javascript]
329:
330: Inputs: formname, elementname
331:
332: formname and elementname specify the name of the html form and the name
333: of the element the selection from the search results will be placed in.
334:
335: =cut
336:
337: sub browser_and_searcher_javascript {
338: my ($mode)=@_;
339: if (!defined($mode)) { $mode='edit'; }
340: my $resurl=&escape_single(&lastresurl());
341: return <<END;
342: // <!-- BEGIN LON-CAPA Internal
343: var editbrowser = null;
344: function openbrowser(formname,elementname,only,omit,titleelement) {
345: var url = '$resurl/?';
346: if (editbrowser == null) {
347: url += 'launch=1&';
348: }
349: url += 'catalogmode=interactive&';
350: url += 'mode=$mode&';
351: url += 'inhibitmenu=yes&';
352: url += 'form=' + formname + '&';
353: if (only != null) {
354: url += 'only=' + only + '&';
355: } else {
356: url += 'only=&';
357: }
358: if (omit != null) {
359: url += 'omit=' + omit + '&';
360: } else {
361: url += 'omit=&';
362: }
363: if (titleelement != null) {
364: url += 'titleelement=' + titleelement + '&';
365: } else {
366: url += 'titleelement=&';
367: }
368: url += 'element=' + elementname + '';
369: var title = 'Browser';
370: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
371: options += ',width=700,height=600';
372: editbrowser = open(url,title,options,'1');
373: editbrowser.focus();
374: }
375: var editsearcher;
376: function opensearcher(formname,elementname,titleelement) {
377: var url = '/adm/searchcat?';
378: if (editsearcher == null) {
379: url += 'launch=1&';
380: }
381: url += 'catalogmode=interactive&';
382: url += 'mode=$mode&';
383: url += 'form=' + formname + '&';
384: if (titleelement != null) {
385: url += 'titleelement=' + titleelement + '&';
386: } else {
387: url += 'titleelement=&';
388: }
389: url += 'element=' + elementname + '';
390: var title = 'Search';
391: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
392: options += ',width=700,height=600';
393: editsearcher = open(url,title,options,'1');
394: editsearcher.focus();
395: }
396: // END LON-CAPA Internal -->
397: END
398: }
399:
400: sub lastresurl {
401: if ($env{'environment.lastresurl'}) {
402: return $env{'environment.lastresurl'}
403: } else {
404: return '/res';
405: }
406: }
407:
408: sub storeresurl {
409: my $resurl=&Apache::lonnet::clutter(shift);
410: unless ($resurl=~/^\/res/) { return 0; }
411: $resurl=~s/\/$//;
412: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
413: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
414: return 1;
415: }
416:
417: sub studentbrowser_javascript {
418: unless (
419: (($env{'request.course.id'}) &&
420: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
421: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
422: '/'.$env{'request.course.sec'})
423: ))
424: || ($env{'request.role'}=~/^(au|dc|su)/)
425: ) { return ''; }
426: return (<<'ENDSTDBRW');
427: <script type="text/javascript" language="Javascript">
428: // <![CDATA[
429: var stdeditbrowser;
430: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
431: var url = '/adm/pickstudent?';
432: var filter;
433: if (!ignorefilter) {
434: eval('filter=document.'+formname+'.'+uname+'.value;');
435: }
436: if (filter != null) {
437: if (filter != '') {
438: url += 'filter='+filter+'&';
439: }
440: }
441: url += 'form=' + formname + '&unameelement='+uname+
442: '&udomelement='+udom+
443: '&clicker='+clicker;
444: if (roleflag) { url+="&roles=1"; }
445: if (courseadvonly) { url+="&courseadvonly=1"; }
446: var title = 'Student_Browser';
447: var options = 'scrollbars=1,resizable=1,menubar=0';
448: options += ',width=700,height=600';
449: stdeditbrowser = open(url,title,options,'1');
450: stdeditbrowser.focus();
451: }
452: // ]]>
453: </script>
454: ENDSTDBRW
455: }
456:
457: sub resourcebrowser_javascript {
458: unless ($env{'request.course.id'}) { return ''; }
459: return (<<'ENDRESBRW');
460: <script type="text/javascript" language="Javascript">
461: // <![CDATA[
462: var reseditbrowser;
463: function openresbrowser(formname,reslink) {
464: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
465: var title = 'Resource_Browser';
466: var options = 'scrollbars=1,resizable=1,menubar=0';
467: options += ',width=700,height=500';
468: reseditbrowser = open(url,title,options,'1');
469: reseditbrowser.focus();
470: }
471: // ]]>
472: </script>
473: ENDRESBRW
474: }
475:
476: sub selectstudent_link {
477: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
478: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
479: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
480: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
481: if ($env{'request.course.id'}) {
482: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
483: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
484: '/'.$env{'request.course.sec'})) {
485: return '';
486: }
487: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
488: if ($courseadvonly) {
489: $callargs .= ",'',1,1";
490: }
491: return '<span class="LC_nobreak">'.
492: '<a href="javascript:openstdbrowser('.$callargs.');">'.
493: &mt('Select User').'</a></span>';
494: }
495: if ($env{'request.role'}=~/^(au|dc|su)/) {
496: $callargs .= ",'',1";
497: return '<span class="LC_nobreak">'.
498: '<a href="javascript:openstdbrowser('.$callargs.');">'.
499: &mt('Select User').'</a></span>';
500: }
501: return '';
502: }
503:
504: sub selectresource_link {
505: my ($form,$reslink,$arg)=@_;
506:
507: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
508: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
509: unless ($env{'request.course.id'}) { return $arg; }
510: return '<span class="LC_nobreak">'.
511: '<a href="javascript:openresbrowser('.$callargs.');">'.
512: $arg.'</a></span>';
513: }
514:
515:
516:
517: sub authorbrowser_javascript {
518: return <<"ENDAUTHORBRW";
519: <script type="text/javascript" language="JavaScript">
520: // <![CDATA[
521: var stdeditbrowser;
522:
523: function openauthorbrowser(formname,udom) {
524: var url = '/adm/pickauthor?';
525: url += 'form='+formname+'&roledom='+udom;
526: var title = 'Author_Browser';
527: var options = 'scrollbars=1,resizable=1,menubar=0';
528: options += ',width=700,height=600';
529: stdeditbrowser = open(url,title,options,'1');
530: stdeditbrowser.focus();
531: }
532:
533: // ]]>
534: </script>
535: ENDAUTHORBRW
536: }
537:
538: sub coursebrowser_javascript {
539: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
540: $credits_element,$instcode) = @_;
541: my $wintitle = 'Course_Browser';
542: if ($crstype eq 'Community') {
543: $wintitle = 'Community_Browser';
544: }
545: my $id_functions = &javascript_index_functions();
546: my $output = '
547: <script type="text/javascript" language="JavaScript">
548: // <![CDATA[
549: var stdeditbrowser;'."\n";
550:
551: $output .= <<"ENDSTDBRW";
552: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
553: var url = '/adm/pickcourse?';
554: var formid = getFormIdByName(formname);
555: var domainfilter = getDomainFromSelectbox(formname,udom);
556: if (domainfilter != null) {
557: if (domainfilter != '') {
558: url += 'domainfilter='+domainfilter+'&';
559: }
560: }
561: url += 'form=' + formname + '&cnumelement='+uname+
562: '&cdomelement='+udom+
563: '&cnameelement='+desc;
564: if (extra_element !=null && extra_element != '') {
565: if (formname == 'rolechoice' || formname == 'studentform') {
566: url += '&roleelement='+extra_element;
567: if (domainfilter == null || domainfilter == '') {
568: url += '&domainfilter='+extra_element;
569: }
570: }
571: else {
572: if (formname == 'portform') {
573: url += '&setroles='+extra_element;
574: } else {
575: if (formname == 'rules') {
576: url += '&fixeddom='+extra_element;
577: }
578: }
579: }
580: }
581: if (type != null && type != '') {
582: url += '&type='+type;
583: }
584: if (type_elem != null && type_elem != '') {
585: url += '&typeelement='+type_elem;
586: }
587: if (formname == 'ccrs') {
588: var ownername = document.forms[formid].ccuname.value;
589: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
590: url += '&cloner='+ownername+':'+ownerdom;
591: if (type == 'Course') {
592: url += '&crscode='+document.forms[formid].crscode.value;
593: }
594: }
595: if (formname == 'requestcrs') {
596: url += '&crsdom=$domainfilter&crscode=$instcode';
597: }
598: if (multflag !=null && multflag != '') {
599: url += '&multiple='+multflag;
600: }
601: var title = '$wintitle';
602: var options = 'scrollbars=1,resizable=1,menubar=0';
603: options += ',width=700,height=600';
604: stdeditbrowser = open(url,title,options,'1');
605: stdeditbrowser.focus();
606: }
607: $id_functions
608: ENDSTDBRW
609: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
610: $output .= &setsec_javascript($sec_element,$formname,$role_element,
611: $credits_element);
612: }
613: $output .= '
614: // ]]>
615: </script>';
616: return $output;
617: }
618:
619: sub javascript_index_functions {
620: return <<"ENDJS";
621:
622: function getFormIdByName(formname) {
623: for (var i=0;i<document.forms.length;i++) {
624: if (document.forms[i].name == formname) {
625: return i;
626: }
627: }
628: return -1;
629: }
630:
631: function getIndexByName(formid,item) {
632: for (var i=0;i<document.forms[formid].elements.length;i++) {
633: if (document.forms[formid].elements[i].name == item) {
634: return i;
635: }
636: }
637: return -1;
638: }
639:
640: function getDomainFromSelectbox(formname,udom) {
641: var userdom;
642: var formid = getFormIdByName(formname);
643: if (formid > -1) {
644: var domid = getIndexByName(formid,udom);
645: if (domid > -1) {
646: if (document.forms[formid].elements[domid].type == 'select-one') {
647: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
648: }
649: if (document.forms[formid].elements[domid].type == 'hidden') {
650: userdom=document.forms[formid].elements[domid].value;
651: }
652: }
653: }
654: return userdom;
655: }
656:
657: ENDJS
658:
659: }
660:
661: sub javascript_array_indexof {
662: return <<ENDJS;
663: <script type="text/javascript" language="JavaScript">
664: // <![CDATA[
665:
666: if (!Array.prototype.indexOf) {
667: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
668: "use strict";
669: if (this === void 0 || this === null) {
670: throw new TypeError();
671: }
672: var t = Object(this);
673: var len = t.length >>> 0;
674: if (len === 0) {
675: return -1;
676: }
677: var n = 0;
678: if (arguments.length > 0) {
679: n = Number(arguments[1]);
680: if (n !== n) { // shortcut for verifying if it's NaN
681: n = 0;
682: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
683: n = (n > 0 || -1) * Math.floor(Math.abs(n));
684: }
685: }
686: if (n >= len) {
687: return -1;
688: }
689: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
690: for (; k < len; k++) {
691: if (k in t && t[k] === searchElement) {
692: return k;
693: }
694: }
695: return -1;
696: }
697: }
698:
699: // ]]>
700: </script>
701:
702: ENDJS
703:
704: }
705:
706: sub userbrowser_javascript {
707: my $id_functions = &javascript_index_functions();
708: return <<"ENDUSERBRW";
709:
710: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
711: var url = '/adm/pickuser?';
712: var userdom = getDomainFromSelectbox(formname,udom);
713: if (userdom != null) {
714: if (userdom != '') {
715: url += 'srchdom='+userdom+'&';
716: }
717: }
718: url += 'form=' + formname + '&unameelement='+uname+
719: '&udomelement='+udom+
720: '&ulastelement='+ulast+
721: '&ufirstelement='+ufirst+
722: '&uemailelement='+uemail+
723: '&hideudomelement='+hideudom+
724: '&coursedom='+crsdom;
725: if ((caller != null) && (caller != undefined)) {
726: url += '&caller='+caller;
727: }
728: var title = 'User_Browser';
729: var options = 'scrollbars=1,resizable=1,menubar=0';
730: options += ',width=700,height=600';
731: var stdeditbrowser = open(url,title,options,'1');
732: stdeditbrowser.focus();
733: }
734:
735: function fix_domain (formname,udom,origdom,uname) {
736: var formid = getFormIdByName(formname);
737: if (formid > -1) {
738: var unameid = getIndexByName(formid,uname);
739: var domid = getIndexByName(formid,udom);
740: var hidedomid = getIndexByName(formid,origdom);
741: if (hidedomid > -1) {
742: var fixeddom = document.forms[formid].elements[hidedomid].value;
743: var unameval = document.forms[formid].elements[unameid].value;
744: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
745: if (domid > -1) {
746: var slct = document.forms[formid].elements[domid];
747: if (slct.type == 'select-one') {
748: var i;
749: for (i=0;i<slct.length;i++) {
750: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
751: }
752: }
753: if (slct.type == 'hidden') {
754: slct.value = fixeddom;
755: }
756: }
757: }
758: }
759: }
760: return;
761: }
762:
763: $id_functions
764: ENDUSERBRW
765: }
766:
767: sub setsec_javascript {
768: my ($sec_element,$formname,$role_element,$credits_element) = @_;
769: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
770: $communityrolestr);
771: if ($role_element ne '') {
772: my @allroles = ('st','ta','ep','in','ad');
773: foreach my $crstype ('Course','Community') {
774: if ($crstype eq 'Community') {
775: foreach my $role (@allroles) {
776: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
777: }
778: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
779: } else {
780: foreach my $role (@allroles) {
781: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
782: }
783: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
784: }
785: }
786: $rolestr = '"'.join('","',@allroles).'"';
787: $courserolestr = '"'.join('","',@courserolenames).'"';
788: $communityrolestr = '"'.join('","',@communityrolenames).'"';
789: }
790: my $setsections = qq|
791: function setSect(sectionlist) {
792: var sectionsArray = new Array();
793: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
794: sectionsArray = sectionlist.split(",");
795: }
796: var numSections = sectionsArray.length;
797: document.$formname.$sec_element.length = 0;
798: if (numSections == 0) {
799: document.$formname.$sec_element.multiple=false;
800: document.$formname.$sec_element.size=1;
801: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
802: } else {
803: if (numSections == 1) {
804: document.$formname.$sec_element.multiple=false;
805: document.$formname.$sec_element.size=1;
806: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
807: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
808: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
809: } else {
810: for (var i=0; i<numSections; i++) {
811: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
812: }
813: document.$formname.$sec_element.multiple=true
814: if (numSections < 3) {
815: document.$formname.$sec_element.size=numSections;
816: } else {
817: document.$formname.$sec_element.size=3;
818: }
819: document.$formname.$sec_element.options[0].selected = false
820: }
821: }
822: }
823:
824: function setRole(crstype) {
825: |;
826: if ($role_element eq '') {
827: $setsections .= ' return;
828: }
829: ';
830: } else {
831: $setsections .= qq|
832: var elementLength = document.$formname.$role_element.length;
833: var allroles = Array($rolestr);
834: var courserolenames = Array($courserolestr);
835: var communityrolenames = Array($communityrolestr);
836: if (elementLength != undefined) {
837: if (document.$formname.$role_element.options[5].value == 'cc') {
838: if (crstype == 'Course') {
839: return;
840: } else {
841: allroles[5] = 'co';
842: for (var i=0; i<6; i++) {
843: document.$formname.$role_element.options[i].value = allroles[i];
844: document.$formname.$role_element.options[i].text = communityrolenames[i];
845: }
846: }
847: } else {
848: if (crstype == 'Community') {
849: return;
850: } else {
851: allroles[5] = 'cc';
852: for (var i=0; i<6; i++) {
853: document.$formname.$role_element.options[i].value = allroles[i];
854: document.$formname.$role_element.options[i].text = courserolenames[i];
855: }
856: }
857: }
858: }
859: return;
860: }
861: |;
862: }
863: if ($credits_element) {
864: $setsections .= qq|
865: function setCredits(defaultcredits) {
866: document.$formname.$credits_element.value = defaultcredits;
867: return;
868: }
869: |;
870: }
871: return $setsections;
872: }
873:
874: sub selectcourse_link {
875: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
876: $typeelement) = @_;
877: my $type = $selecttype;
878: my $linktext = &mt('Select Course');
879: if ($selecttype eq 'Community') {
880: $linktext = &mt('Select Community');
881: } elsif ($selecttype eq 'Course/Community') {
882: $linktext = &mt('Select Course/Community');
883: $type = '';
884: } elsif ($selecttype eq 'Select') {
885: $linktext = &mt('Select');
886: $type = '';
887: }
888: return '<span class="LC_nobreak">'
889: ."<a href='"
890: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
891: .'","'.$udomele.'","'.$desc.'","'.$extra_element
892: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
893: ."'>".$linktext.'</a>'
894: .'</span>';
895: }
896:
897: sub selectauthor_link {
898: my ($form,$udom)=@_;
899: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
900: &mt('Select Author').'</a>';
901: }
902:
903: sub selectuser_link {
904: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
905: $coursedom,$linktext,$caller) = @_;
906: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
907: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
908: ');">'.$linktext.'</a>';
909: }
910:
911: sub check_uncheck_jscript {
912: my $jscript = <<"ENDSCRT";
913: function checkAll(field) {
914: if (field.length > 0) {
915: for (i = 0; i < field.length; i++) {
916: if (!field[i].disabled) {
917: field[i].checked = true;
918: }
919: }
920: } else {
921: if (!field.disabled) {
922: field.checked = true;
923: }
924: }
925: }
926:
927: function uncheckAll(field) {
928: if (field.length > 0) {
929: for (i = 0; i < field.length; i++) {
930: field[i].checked = false ;
931: }
932: } else {
933: field.checked = false ;
934: }
935: }
936: ENDSCRT
937: return $jscript;
938: }
939:
940: sub select_timezone {
941: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
942: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
943: if ($includeempty) {
944: $output .= '<option value=""';
945: if (($selected eq '') || ($selected eq 'local')) {
946: $output .= ' selected="selected" ';
947: }
948: $output .= '> </option>';
949: }
950: my @timezones = DateTime::TimeZone->all_names;
951: foreach my $tzone (@timezones) {
952: $output.= '<option value="'.$tzone.'"';
953: if ($tzone eq $selected) {
954: $output.=' selected="selected"';
955: }
956: $output.=">$tzone</option>\n";
957: }
958: $output.="</select>";
959: return $output;
960: }
961:
962: sub select_datelocale {
963: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
964: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
965: if ($includeempty) {
966: $output .= '<option value=""';
967: if ($selected eq '') {
968: $output .= ' selected="selected" ';
969: }
970: $output .= '> </option>';
971: }
972: my @languages = &Apache::lonlocal::preferred_languages();
973: my (@possibles,%locale_names);
974: my @locales = DateTime::Locale->ids();
975: foreach my $id (@locales) {
976: if ($id ne '') {
977: my ($en_terr,$native_terr);
978: my $loc = DateTime::Locale->load($id);
979: if (ref($loc)) {
980: $en_terr = $loc->name();
981: $native_terr = $loc->native_name();
982: if (grep(/^en$/,@languages) || !@languages) {
983: if ($en_terr ne '') {
984: $locale_names{$id} = '('.$en_terr.')';
985: } elsif ($native_terr ne '') {
986: $locale_names{$id} = $native_terr;
987: }
988: } else {
989: if ($native_terr ne '') {
990: $locale_names{$id} = $native_terr.' ';
991: } elsif ($en_terr ne '') {
992: $locale_names{$id} = '('.$en_terr.')';
993: }
994: }
995: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
996: push(@possibles,$id);
997: }
998: }
999: }
1000: foreach my $item (sort(@possibles)) {
1001: $output.= '<option value="'.$item.'"';
1002: if ($item eq $selected) {
1003: $output.=' selected="selected"';
1004: }
1005: $output.=">$item";
1006: if ($locale_names{$item} ne '') {
1007: $output.=' '.$locale_names{$item};
1008: }
1009: $output.="</option>\n";
1010: }
1011: $output.="</select>";
1012: return $output;
1013: }
1014:
1015: sub select_language {
1016: my ($name,$selected,$includeempty,$noedit) = @_;
1017: my %langchoices;
1018: if ($includeempty) {
1019: %langchoices = ('' => 'No language preference');
1020: }
1021: foreach my $id (&languageids()) {
1022: my $code = &supportedlanguagecode($id);
1023: if ($code) {
1024: $langchoices{$code} = &plainlanguagedescription($id);
1025: }
1026: }
1027: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1028: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1029: }
1030:
1031: =pod
1032:
1033: =item * &linked_select_forms(...)
1034:
1035: linked_select_forms returns a string containing a <script></script> block
1036: and html for two <select> menus. The select menus will be linked in that
1037: changing the value of the first menu will result in new values being placed
1038: in the second menu. The values in the select menu will appear in alphabetical
1039: order unless a defined order is provided.
1040:
1041: linked_select_forms takes the following ordered inputs:
1042:
1043: =over 4
1044:
1045: =item * $formname, the name of the <form> tag
1046:
1047: =item * $middletext, the text which appears between the <select> tags
1048:
1049: =item * $firstdefault, the default value for the first menu
1050:
1051: =item * $firstselectname, the name of the first <select> tag
1052:
1053: =item * $secondselectname, the name of the second <select> tag
1054:
1055: =item * $hashref, a reference to a hash containing the data for the menus.
1056:
1057: =item * $menuorder, the order of values in the first menu
1058:
1059: =item * $onchangefirst, additional javascript call to execute for an onchange
1060: event for the first <select> tag
1061:
1062: =item * $onchangesecond, additional javascript call to execute for an onchange
1063: event for the second <select> tag
1064:
1065: =back
1066:
1067: Below is an example of such a hash. Only the 'text', 'default', and
1068: 'select2' keys must appear as stated. keys(%menu) are the possible
1069: values for the first select menu. The text that coincides with the
1070: first menu value is given in $menu{$choice1}->{'text'}. The values
1071: and text for the second menu are given in the hash pointed to by
1072: $menu{$choice1}->{'select2'}.
1073:
1074: my %menu = ( A1 => { text =>"Choice A1" ,
1075: default => "B3",
1076: select2 => {
1077: B1 => "Choice B1",
1078: B2 => "Choice B2",
1079: B3 => "Choice B3",
1080: B4 => "Choice B4"
1081: },
1082: order => ['B4','B3','B1','B2'],
1083: },
1084: A2 => { text =>"Choice A2" ,
1085: default => "C2",
1086: select2 => {
1087: C1 => "Choice C1",
1088: C2 => "Choice C2",
1089: C3 => "Choice C3"
1090: },
1091: order => ['C2','C1','C3'],
1092: },
1093: A3 => { text =>"Choice A3" ,
1094: default => "D6",
1095: select2 => {
1096: D1 => "Choice D1",
1097: D2 => "Choice D2",
1098: D3 => "Choice D3",
1099: D4 => "Choice D4",
1100: D5 => "Choice D5",
1101: D6 => "Choice D6",
1102: D7 => "Choice D7"
1103: },
1104: order => ['D4','D3','D2','D1','D7','D6','D5'],
1105: }
1106: );
1107:
1108: =cut
1109:
1110: sub linked_select_forms {
1111: my ($formname,
1112: $middletext,
1113: $firstdefault,
1114: $firstselectname,
1115: $secondselectname,
1116: $hashref,
1117: $menuorder,
1118: $onchangefirst,
1119: $onchangesecond
1120: ) = @_;
1121: my $second = "document.$formname.$secondselectname";
1122: my $first = "document.$formname.$firstselectname";
1123: # output the javascript to do the changing
1124: my $result = '';
1125: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1126: $result.="// <![CDATA[\n";
1127: $result.="var select2data = new Object();\n";
1128: $" = '","';
1129: my $debug = '';
1130: foreach my $s1 (sort(keys(%$hashref))) {
1131: $result.="select2data.d_$s1 = new Object();\n";
1132: $result.="select2data.d_$s1.def = new String('".
1133: $hashref->{$s1}->{'default'}."');\n";
1134: $result.="select2data.d_$s1.values = new Array(";
1135: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1136: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1137: @s2values = @{$hashref->{$s1}->{'order'}};
1138: }
1139: $result.="\"@s2values\");\n";
1140: $result.="select2data.d_$s1.texts = new Array(";
1141: my @s2texts;
1142: foreach my $value (@s2values) {
1143: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1144: }
1145: $result.="\"@s2texts\");\n";
1146: }
1147: $"=' ';
1148: $result.= <<"END";
1149:
1150: function select1_changed() {
1151: // Determine new choice
1152: var newvalue = "d_" + $first.value;
1153: // update select2
1154: var values = select2data[newvalue].values;
1155: var texts = select2data[newvalue].texts;
1156: var select2def = select2data[newvalue].def;
1157: var i;
1158: // out with the old
1159: for (i = 0; i < $second.options.length; i++) {
1160: $second.options[i] = null;
1161: }
1162: // in with the nuclear
1163: for (i=0;i<values.length; i++) {
1164: $second.options[i] = new Option(values[i]);
1165: $second.options[i].value = values[i];
1166: $second.options[i].text = texts[i];
1167: if (values[i] == select2def) {
1168: $second.options[i].selected = true;
1169: }
1170: }
1171: }
1172: // ]]>
1173: </script>
1174: END
1175: # output the initial values for the selection lists
1176: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1177: my @order = sort(keys(%{$hashref}));
1178: if (ref($menuorder) eq 'ARRAY') {
1179: @order = @{$menuorder};
1180: }
1181: foreach my $value (@order) {
1182: $result.=" <option value=\"$value\" ";
1183: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1184: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1185: }
1186: $result .= "</select>\n";
1187: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1188: $result .= $middletext;
1189: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1190: if ($onchangesecond) {
1191: $result .= ' onchange="'.$onchangesecond.'"';
1192: }
1193: $result .= ">\n";
1194: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1195:
1196: my @secondorder = sort(keys(%select2));
1197: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1198: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1199: }
1200: foreach my $value (@secondorder) {
1201: $result.=" <option value=\"$value\" ";
1202: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1203: $result.=">".&mt($select2{$value})."</option>\n";
1204: }
1205: $result .= "</select>\n";
1206: # return $debug;
1207: return $result;
1208: } # end of sub linked_select_forms {
1209:
1210: =pod
1211:
1212: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1213:
1214: Returns a string corresponding to an HTML link to the given help
1215: $topic, where $topic corresponds to the name of a .tex file in
1216: /home/httpd/html/adm/help/tex, with underscores replaced by
1217: spaces.
1218:
1219: $text will optionally be linked to the same topic, allowing you to
1220: link text in addition to the graphic. If you do not want to link
1221: text, but wish to specify one of the later parameters, pass an
1222: empty string.
1223:
1224: $stayOnPage is a value that will be interpreted as a boolean. If true,
1225: the link will not open a new window. If false, the link will open
1226: a new window using Javascript. (Default is false.)
1227:
1228: $width and $height are optional numerical parameters that will
1229: override the width and height of the popped up window, which may
1230: be useful for certain help topics with big pictures included.
1231:
1232: $imgid is the id of the img tag used for the help icon. This may be
1233: used in a javascript call to switch the image src. See
1234: lonhtmlcommon::htmlareaselectactive() for an example.
1235:
1236: =cut
1237:
1238: sub help_open_topic {
1239: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1240: $text = "" if (not defined $text);
1241: $stayOnPage = 0 if (not defined $stayOnPage);
1242: $width = 500 if (not defined $width);
1243: $height = 400 if (not defined $height);
1244: my $filename = $topic;
1245: $filename =~ s/ /_/g;
1246:
1247: my $template = "";
1248: my $link;
1249:
1250: $topic=~s/\W/\_/g;
1251:
1252: if (!$stayOnPage) {
1253: if ($env{'browser.mobile'}) {
1254: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1255: } else {
1256: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1257: }
1258: } elsif ($stayOnPage eq 'popup') {
1259: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1260: } else {
1261: $link = "/adm/help/${filename}.hlp";
1262: }
1263:
1264: # Add the text
1265: if ($text ne "") {
1266: $template.='<span class="LC_help_open_topic">'
1267: .'<a target="_top" href="'.$link.'">'
1268: .$text.'</a>';
1269: }
1270:
1271: # (Always) Add the graphic
1272: my $title = &mt('Online Help');
1273: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1274: if ($imgid ne '') {
1275: $imgid = ' id="'.$imgid.'"';
1276: }
1277: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1278: .'<img src="'.$helpicon.'" border="0"'
1279: .' alt="'.&mt('Help: [_1]',$topic).'"'
1280: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1281: .' /></a>';
1282: if ($text ne "") {
1283: $template.='</span>';
1284: }
1285: return $template;
1286:
1287: }
1288:
1289: # This is a quicky function for Latex cheatsheet editing, since it
1290: # appears in at least four places
1291: sub helpLatexCheatsheet {
1292: my ($topic,$text,$not_author,$stayOnPage) = @_;
1293: my $out;
1294: my $addOther = '';
1295: if ($topic) {
1296: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1297: }
1298: $out = '<span>' # Start cheatsheet
1299: .$addOther
1300: .'<span>'
1301: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1302: .'</span> <span>'
1303: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1304: .'</span>';
1305: unless ($not_author) {
1306: $out .= ' <span>'
1307: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1308: .'</span> <span>'
1309: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1310: .'</span>';
1311: }
1312: $out .= '</span>'; # End cheatsheet
1313: return $out;
1314: }
1315:
1316: sub general_help {
1317: my $helptopic='Student_Intro';
1318: if ($env{'request.role'}=~/^(ca|au)/) {
1319: $helptopic='Authoring_Intro';
1320: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1321: $helptopic='Course_Coordination_Intro';
1322: } elsif ($env{'request.role'}=~/^dc/) {
1323: $helptopic='Domain_Coordination_Intro';
1324: }
1325: return $helptopic;
1326: }
1327:
1328: sub update_help_link {
1329: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1330: my $origurl = $ENV{'REQUEST_URI'};
1331: $origurl=~s|^/~|/priv/|;
1332: my $timestamp = time;
1333: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1334: $$datum = &escape($$datum);
1335: }
1336:
1337: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1338: my $output .= <<"ENDOUTPUT";
1339: <script type="text/javascript">
1340: // <![CDATA[
1341: banner_link = '$banner_link';
1342: // ]]>
1343: </script>
1344: ENDOUTPUT
1345: return $output;
1346: }
1347:
1348: # now just updates the help link and generates a blue icon
1349: sub help_open_menu {
1350: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1351: = @_;
1352: $stayOnPage = 1;
1353: my $output;
1354: if ($component_help) {
1355: if (!$text) {
1356: $output=&help_open_topic($component_help,undef,$stayOnPage,
1357: $width,$height);
1358: } else {
1359: my $help_text;
1360: $help_text=&unescape($topic);
1361: $output='<table><tr><td>'.
1362: &help_open_topic($component_help,$help_text,$stayOnPage,
1363: $width,$height).'</td></tr></table>';
1364: }
1365: }
1366: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1367: return $output.$banner_link;
1368: }
1369:
1370: sub top_nav_help {
1371: my ($text) = @_;
1372: $text = &mt($text);
1373: my $stay_on_page;
1374: unless ($env{'environment.remote'} eq 'on') {
1375: $stay_on_page = 1;
1376: }
1377: my ($link,$banner_link);
1378: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1379: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1380: : "javascript:helpMenu('open')";
1381: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1382: }
1383: my $title = &mt('Get help');
1384: if ($link) {
1385: return <<"END";
1386: $banner_link
1387: <a href="$link" title="$title">$text</a>
1388: END
1389: } else {
1390: return ' '.$text.' ';
1391: }
1392: }
1393:
1394: sub help_menu_js {
1395: my ($httphost) = @_;
1396: my $stayOnPage = 1;
1397: my $width = 620;
1398: my $height = 600;
1399: my $helptopic=&general_help();
1400: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1401: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1402: my $start_page =
1403: &Apache::loncommon::start_page('Help Menu', undef,
1404: {'frameset' => 1,
1405: 'js_ready' => 1,
1406: 'use_absolute' => $httphost,
1407: 'add_entries' => {
1408: 'border' => '0',
1409: 'rows' => "110,*",},});
1410: my $end_page =
1411: &Apache::loncommon::end_page({'frameset' => 1,
1412: 'js_ready' => 1,});
1413:
1414: my $template .= <<"ENDTEMPLATE";
1415: <script type="text/javascript">
1416: // <![CDATA[
1417: // <!-- BEGIN LON-CAPA Internal
1418: var banner_link = '';
1419: function helpMenu(target) {
1420: var caller = this;
1421: if (target == 'open') {
1422: var newWindow = null;
1423: try {
1424: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1425: }
1426: catch(error) {
1427: writeHelp(caller);
1428: return;
1429: }
1430: if (newWindow) {
1431: caller = newWindow;
1432: }
1433: }
1434: writeHelp(caller);
1435: return;
1436: }
1437: function writeHelp(caller) {
1438: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1439: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1440: caller.document.close();
1441: caller.focus();
1442: }
1443: // END LON-CAPA Internal -->
1444: // ]]>
1445: </script>
1446: ENDTEMPLATE
1447: return $template;
1448: }
1449:
1450: sub help_open_bug {
1451: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1452: unless ($env{'user.adv'}) { return ''; }
1453: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1454: $text = "" if (not defined $text);
1455: $stayOnPage=1;
1456: $width = 600 if (not defined $width);
1457: $height = 600 if (not defined $height);
1458:
1459: $topic=~s/\W+/\+/g;
1460: my $link='';
1461: my $template='';
1462: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1463: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1464: if (!$stayOnPage)
1465: {
1466: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1467: }
1468: else
1469: {
1470: $link = $url;
1471: }
1472: # Add the text
1473: if ($text ne "")
1474: {
1475: $template .=
1476: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1477: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1478: }
1479:
1480: # Add the graphic
1481: my $title = &mt('Report a Bug');
1482: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1483: $template .= <<"ENDTEMPLATE";
1484: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1485: ENDTEMPLATE
1486: if ($text ne '') { $template.='</td></tr></table>' };
1487: return $template;
1488:
1489: }
1490:
1491: sub help_open_faq {
1492: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1493: unless ($env{'user.adv'}) { return ''; }
1494: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1495: $text = "" if (not defined $text);
1496: $stayOnPage=1;
1497: $width = 350 if (not defined $width);
1498: $height = 400 if (not defined $height);
1499:
1500: $topic=~s/\W+/\+/g;
1501: my $link='';
1502: my $template='';
1503: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1504: if (!$stayOnPage)
1505: {
1506: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1507: }
1508: else
1509: {
1510: $link = $url;
1511: }
1512:
1513: # Add the text
1514: if ($text ne "")
1515: {
1516: $template .=
1517: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1518: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1519: }
1520:
1521: # Add the graphic
1522: my $title = &mt('View the FAQ');
1523: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1524: $template .= <<"ENDTEMPLATE";
1525: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1526: ENDTEMPLATE
1527: if ($text ne '') { $template.='</td></tr></table>' };
1528: return $template;
1529:
1530: }
1531:
1532: ###############################################################
1533: ###############################################################
1534:
1535: =pod
1536:
1537: =item * &change_content_javascript():
1538:
1539: This and the next function allow you to create small sections of an
1540: otherwise static HTML page that you can update on the fly with
1541: Javascript, even in Netscape 4.
1542:
1543: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1544: must be written to the HTML page once. It will prove the Javascript
1545: function "change(name, content)". Calling the change function with the
1546: name of the section
1547: you want to update, matching the name passed to C<changable_area>, and
1548: the new content you want to put in there, will put the content into
1549: that area.
1550:
1551: B<Note>: Netscape 4 only reserves enough space for the changable area
1552: to contain room for the original contents. You need to "make space"
1553: for whatever changes you wish to make, and be B<sure> to check your
1554: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1555: it's adequate for updating a one-line status display, but little more.
1556: This script will set the space to 100% width, so you only need to
1557: worry about height in Netscape 4.
1558:
1559: Modern browsers are much less limiting, and if you can commit to the
1560: user not using Netscape 4, this feature may be used freely with
1561: pretty much any HTML.
1562:
1563: =cut
1564:
1565: sub change_content_javascript {
1566: # If we're on Netscape 4, we need to use Layer-based code
1567: if ($env{'browser.type'} eq 'netscape' &&
1568: $env{'browser.version'} =~ /^4\./) {
1569: return (<<NETSCAPE4);
1570: function change(name, content) {
1571: doc = document.layers[name+"___escape"].layers[0].document;
1572: doc.open();
1573: doc.write(content);
1574: doc.close();
1575: }
1576: NETSCAPE4
1577: } else {
1578: # Otherwise, we need to use semi-standards-compliant code
1579: # (technically, "innerHTML" isn't standard but the equivalent
1580: # is really scary, and every useful browser supports it
1581: return (<<DOMBASED);
1582: function change(name, content) {
1583: element = document.getElementById(name);
1584: element.innerHTML = content;
1585: }
1586: DOMBASED
1587: }
1588: }
1589:
1590: =pod
1591:
1592: =item * &changable_area($name,$origContent):
1593:
1594: This provides a "changable area" that can be modified on the fly via
1595: the Javascript code provided in C<change_content_javascript>. $name is
1596: the name you will use to reference the area later; do not repeat the
1597: same name on a given HTML page more then once. $origContent is what
1598: the area will originally contain, which can be left blank.
1599:
1600: =cut
1601:
1602: sub changable_area {
1603: my ($name, $origContent) = @_;
1604:
1605: if ($env{'browser.type'} eq 'netscape' &&
1606: $env{'browser.version'} =~ /^4\./) {
1607: # If this is netscape 4, we need to use the Layer tag
1608: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1609: } else {
1610: return "<span id='$name'>$origContent</span>";
1611: }
1612: }
1613:
1614: =pod
1615:
1616: =item * &viewport_geometry_js
1617:
1618: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1619:
1620: =cut
1621:
1622:
1623: sub viewport_geometry_js {
1624: return <<"GEOMETRY";
1625: var Geometry = {};
1626: function init_geometry() {
1627: if (Geometry.init) { return };
1628: Geometry.init=1;
1629: if (window.innerHeight) {
1630: Geometry.getViewportHeight = function() { return window.innerHeight; };
1631: Geometry.getViewportWidth = function() { return window.innerWidth; };
1632: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1633: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1634: }
1635: else if (document.documentElement && document.documentElement.clientHeight) {
1636: Geometry.getViewportHeight =
1637: function() { return document.documentElement.clientHeight; };
1638: Geometry.getViewportWidth =
1639: function() { return document.documentElement.clientWidth; };
1640:
1641: Geometry.getHorizontalScroll =
1642: function() { return document.documentElement.scrollLeft; };
1643: Geometry.getVerticalScroll =
1644: function() { return document.documentElement.scrollTop; };
1645: }
1646: else if (document.body.clientHeight) {
1647: Geometry.getViewportHeight =
1648: function() { return document.body.clientHeight; };
1649: Geometry.getViewportWidth =
1650: function() { return document.body.clientWidth; };
1651: Geometry.getHorizontalScroll =
1652: function() { return document.body.scrollLeft; };
1653: Geometry.getVerticalScroll =
1654: function() { return document.body.scrollTop; };
1655: }
1656: }
1657:
1658: GEOMETRY
1659: }
1660:
1661: =pod
1662:
1663: =item * &viewport_size_js()
1664:
1665: 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.
1666:
1667: =cut
1668:
1669: sub viewport_size_js {
1670: my $geometry = &viewport_geometry_js();
1671: return <<"DIMS";
1672:
1673: $geometry
1674:
1675: function getViewportDims(width,height) {
1676: init_geometry();
1677: width.value = Geometry.getViewportWidth();
1678: height.value = Geometry.getViewportHeight();
1679: return;
1680: }
1681:
1682: DIMS
1683: }
1684:
1685: =pod
1686:
1687: =item * &resize_textarea_js()
1688:
1689: emits the needed javascript to resize a textarea to be as big as possible
1690:
1691: creates a function resize_textrea that takes two IDs first should be
1692: the id of the element to resize, second should be the id of a div that
1693: surrounds everything that comes after the textarea, this routine needs
1694: to be attached to the <body> for the onload and onresize events.
1695:
1696: =back
1697:
1698: =cut
1699:
1700: sub resize_textarea_js {
1701: my $geometry = &viewport_geometry_js();
1702: return <<"RESIZE";
1703: <script type="text/javascript">
1704: // <![CDATA[
1705: $geometry
1706:
1707: function getX(element) {
1708: var x = 0;
1709: while (element) {
1710: x += element.offsetLeft;
1711: element = element.offsetParent;
1712: }
1713: return x;
1714: }
1715: function getY(element) {
1716: var y = 0;
1717: while (element) {
1718: y += element.offsetTop;
1719: element = element.offsetParent;
1720: }
1721: return y;
1722: }
1723:
1724:
1725: function resize_textarea(textarea_id,bottom_id) {
1726: init_geometry();
1727: var textarea = document.getElementById(textarea_id);
1728: //alert(textarea);
1729:
1730: var textarea_top = getY(textarea);
1731: var textarea_height = textarea.offsetHeight;
1732: var bottom = document.getElementById(bottom_id);
1733: var bottom_top = getY(bottom);
1734: var bottom_height = bottom.offsetHeight;
1735: var window_height = Geometry.getViewportHeight();
1736: var fudge = 23;
1737: var new_height = window_height-fudge-textarea_top-bottom_height;
1738: if (new_height < 300) {
1739: new_height = 300;
1740: }
1741: textarea.style.height=new_height+'px';
1742: }
1743: // ]]>
1744: </script>
1745: RESIZE
1746:
1747: }
1748:
1749: sub colorfuleditor_js {
1750: return <<"COLORFULEDIT"
1751: <script type="text/javascript">
1752: // <![CDATA[>
1753: function fold_box(curDepth, lastresource){
1754:
1755: // we need a list because there can be several blocks you need to fold in one tag
1756: var block = document.getElementsByName('foldblock_'+curDepth);
1757: // but there is only one folding button per tag
1758: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1759:
1760: if(block.item(0).style.display == 'none'){
1761:
1762: foldbutton.value = '@{[&mt("Hide")]}';
1763: for (i = 0; i < block.length; i++){
1764: block.item(i).style.display = '';
1765: }
1766: }else{
1767:
1768: foldbutton.value = '@{[&mt("Show")]}';
1769: for (i = 0; i < block.length; i++){
1770: // block.item(i).style.visibility = 'collapse';
1771: block.item(i).style.display = 'none';
1772: }
1773: };
1774: saveState(lastresource);
1775: }
1776:
1777: function saveState (lastresource) {
1778:
1779: var tag_list = getTagList();
1780: if(tag_list != null){
1781: var timestamp = new Date().getTime();
1782: var key = lastresource;
1783:
1784: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1785: // starting with timestamp
1786: var value = timestamp+';';
1787:
1788: // building the list of key-value pairs
1789: for(var i = 0; i < tag_list.length; i++){
1790: value += tag_list[i]+',';
1791: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1792: }
1793:
1794: // only iterate whole storage if nothing to override
1795: if(localStorage.getItem(key) == null){
1796:
1797: // prevent storage from growing large
1798: if(localStorage.length > 50){
1799: var regex_getTimestamp = /^(?:\d)+;/;
1800: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1801: var oldest_key;
1802:
1803: for(var i = 1; i < localStorage.length; i++){
1804: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1805: oldest_key = localStorage.key(i);
1806: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1807: }
1808: }
1809: localStorage.removeItem(oldest_key);
1810: }
1811: }
1812: localStorage.setItem(key,value);
1813: }
1814: }
1815:
1816: // restore folding status of blocks (on page load)
1817: function restoreState (lastresource) {
1818: if(localStorage.getItem(lastresource) != null){
1819: var key = lastresource;
1820: var value = localStorage.getItem(key);
1821: var regex_delTimestamp = /^\d+;/;
1822:
1823: value.replace(regex_delTimestamp, '');
1824:
1825: var valueArr = value.split(';');
1826: var pairs;
1827: var elements;
1828: for (var i = 0; i < valueArr.length; i++){
1829: pairs = valueArr[i].split(',');
1830: elements = document.getElementsByName(pairs[0]);
1831:
1832: for (var j = 0; j < elements.length; j++){
1833: elements[j].style.display = pairs[1];
1834: if (pairs[1] == "none"){
1835: var regex_id = /([_\\d]+)\$/;
1836: regex_id.exec(pairs[0]);
1837: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
1838: }
1839: }
1840: }
1841: }
1842: }
1843:
1844: function getTagList () {
1845:
1846: var stringToSearch = document.lonhomework.innerHTML;
1847:
1848: var ret = new Array();
1849: var regex_findBlock = /(foldblock_.*?)"/g;
1850: var tag_list = stringToSearch.match(regex_findBlock);
1851:
1852: if(tag_list != null){
1853: for(var i = 0; i < tag_list.length; i++){
1854: ret.push(tag_list[i].replace(/"/, ''));
1855: }
1856: }
1857: return ret;
1858: }
1859:
1860: function saveScrollPosition (resource) {
1861: var tag_list = getTagList();
1862:
1863: // we dont always want to jump to the first block
1864: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
1865: if(\$(window).scrollTop() > 170){
1866: if(tag_list != null){
1867: var result;
1868: for(var i = 0; i < tag_list.length; i++){
1869: if(isElementInViewport(tag_list[i])){
1870: result += tag_list[i]+';';
1871: }
1872: }
1873: sessionStorage.setItem('anchor_'+resource, result);
1874: }
1875: } else {
1876: // we dont need to save zero, just delete the item to leave everything tidy
1877: sessionStorage.removeItem('anchor_'+resource);
1878: }
1879: }
1880:
1881: function restoreScrollPosition(resource){
1882:
1883: var elem = sessionStorage.getItem('anchor_'+resource);
1884: if(elem != null){
1885: var tag_list = elem.split(';');
1886: var elem_list;
1887:
1888: for(var i = 0; i < tag_list.length; i++){
1889: elem_list = document.getElementsByName(tag_list[i]);
1890:
1891: if(elem_list.length > 0){
1892: elem = elem_list[0];
1893: break;
1894: }
1895: }
1896: elem.scrollIntoView();
1897: }
1898: }
1899:
1900: function isElementInViewport(el) {
1901:
1902: // change to last element instead of first
1903: var elem = document.getElementsByName(el);
1904: var rect = elem[0].getBoundingClientRect();
1905:
1906: return (
1907: rect.top >= 0 &&
1908: rect.left >= 0 &&
1909: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
1910: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
1911: );
1912: }
1913:
1914: function autosize(depth){
1915: var cmInst = window['cm'+depth];
1916: var fitsizeButton = document.getElementById('fitsize'+depth);
1917:
1918: // is fixed size, switching to dynamic
1919: if (sessionStorage.getItem("autosized_"+depth) == null) {
1920: cmInst.setSize("","auto");
1921: fitsizeButton.value = "@{[&mt('Fixed size')]}";
1922: sessionStorage.setItem("autosized_"+depth, "yes");
1923:
1924: // is dynamic size, switching to fixed
1925: } else {
1926: cmInst.setSize("","300px");
1927: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
1928: sessionStorage.removeItem("autosized_"+depth);
1929: }
1930: }
1931:
1932:
1933:
1934: // ]]>
1935: </script>
1936: COLORFULEDIT
1937: }
1938:
1939: sub xmleditor_js {
1940: return <<XMLEDIT
1941: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
1942: <script type="text/javascript">
1943: // <![CDATA[>
1944:
1945: function saveScrollPosition (resource) {
1946:
1947: var scrollPos = \$(window).scrollTop();
1948: sessionStorage.setItem(resource,scrollPos);
1949: }
1950:
1951: function restoreScrollPosition(resource){
1952:
1953: var scrollPos = sessionStorage.getItem(resource);
1954: \$(window).scrollTop(scrollPos);
1955: }
1956:
1957: // unless internet explorer
1958: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
1959:
1960: \$(document).ready(function() {
1961: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
1962: });
1963: }
1964:
1965: // inserts text at cursor position into codemirror (xml editor only)
1966: function insertText(text){
1967: cm.focus();
1968: var curPos = cm.getCursor();
1969: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
1970: }
1971: // ]]>
1972: </script>
1973: XMLEDIT
1974: }
1975:
1976: sub insert_folding_button {
1977: my $curDepth = $Apache::lonxml::curdepth;
1978: my $lastresource = $env{'request.ambiguous'};
1979:
1980: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
1981: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
1982: }
1983:
1984:
1985: =pod
1986:
1987: =head1 Excel and CSV file utility routines
1988:
1989: =cut
1990:
1991: ###############################################################
1992: ###############################################################
1993:
1994: =pod
1995:
1996: =over 4
1997:
1998: =item * &csv_translate($text)
1999:
2000: Translate $text to allow it to be output as a 'comma separated values'
2001: format.
2002:
2003: =cut
2004:
2005: ###############################################################
2006: ###############################################################
2007: sub csv_translate {
2008: my $text = shift;
2009: $text =~ s/\"/\"\"/g;
2010: $text =~ s/\n/ /g;
2011: return $text;
2012: }
2013:
2014: ###############################################################
2015: ###############################################################
2016:
2017: =pod
2018:
2019: =item * &define_excel_formats()
2020:
2021: Define some commonly used Excel cell formats.
2022:
2023: Currently supported formats:
2024:
2025: =over 4
2026:
2027: =item header
2028:
2029: =item bold
2030:
2031: =item h1
2032:
2033: =item h2
2034:
2035: =item h3
2036:
2037: =item h4
2038:
2039: =item i
2040:
2041: =item date
2042:
2043: =back
2044:
2045: Inputs: $workbook
2046:
2047: Returns: $format, a hash reference.
2048:
2049:
2050: =cut
2051:
2052: ###############################################################
2053: ###############################################################
2054: sub define_excel_formats {
2055: my ($workbook) = @_;
2056: my $format;
2057: $format->{'header'} = $workbook->add_format(bold => 1,
2058: bottom => 1,
2059: align => 'center');
2060: $format->{'bold'} = $workbook->add_format(bold=>1);
2061: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2062: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2063: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2064: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2065: $format->{'i'} = $workbook->add_format(italic=>1);
2066: $format->{'date'} = $workbook->add_format(num_format=>
2067: 'mm/dd/yyyy hh:mm:ss');
2068: return $format;
2069: }
2070:
2071: ###############################################################
2072: ###############################################################
2073:
2074: =pod
2075:
2076: =item * &create_workbook()
2077:
2078: Create an Excel worksheet. If it fails, output message on the
2079: request object and return undefs.
2080:
2081: Inputs: Apache request object
2082:
2083: Returns (undef) on failure,
2084: Excel worksheet object, scalar with filename, and formats
2085: from &Apache::loncommon::define_excel_formats on success
2086:
2087: =cut
2088:
2089: ###############################################################
2090: ###############################################################
2091: sub create_workbook {
2092: my ($r) = @_;
2093: #
2094: # Create the excel spreadsheet
2095: my $filename = '/prtspool/'.
2096: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2097: time.'_'.rand(1000000000).'.xls';
2098: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2099: if (! defined($workbook)) {
2100: $r->log_error("Error creating excel spreadsheet $filename: $!");
2101: $r->print(
2102: '<p class="LC_error">'
2103: .&mt('Problems occurred in creating the new Excel file.')
2104: .' '.&mt('This error has been logged.')
2105: .' '.&mt('Please alert your LON-CAPA administrator.')
2106: .'</p>'
2107: );
2108: return (undef);
2109: }
2110: #
2111: $workbook->set_tempdir(LONCAPA::tempdir());
2112: #
2113: my $format = &Apache::loncommon::define_excel_formats($workbook);
2114: return ($workbook,$filename,$format);
2115: }
2116:
2117: ###############################################################
2118: ###############################################################
2119:
2120: =pod
2121:
2122: =item * &create_text_file()
2123:
2124: Create a file to write to and eventually make available to the user.
2125: If file creation fails, outputs an error message on the request object and
2126: return undefs.
2127:
2128: Inputs: Apache request object, and file suffix
2129:
2130: Returns (undef) on failure,
2131: Filehandle and filename on success.
2132:
2133: =cut
2134:
2135: ###############################################################
2136: ###############################################################
2137: sub create_text_file {
2138: my ($r,$suffix) = @_;
2139: if (! defined($suffix)) { $suffix = 'txt'; };
2140: my $fh;
2141: my $filename = '/prtspool/'.
2142: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2143: time.'_'.rand(1000000000).'.'.$suffix;
2144: $fh = Apache::File->new('>/home/httpd'.$filename);
2145: if (! defined($fh)) {
2146: $r->log_error("Couldn't open $filename for output $!");
2147: $r->print(
2148: '<p class="LC_error">'
2149: .&mt('Problems occurred in creating the output file.')
2150: .' '.&mt('This error has been logged.')
2151: .' '.&mt('Please alert your LON-CAPA administrator.')
2152: .'</p>'
2153: );
2154: }
2155: return ($fh,$filename)
2156: }
2157:
2158:
2159: =pod
2160:
2161: =back
2162:
2163: =cut
2164:
2165: ###############################################################
2166: ## Home server <option> list generating code ##
2167: ###############################################################
2168:
2169: # ------------------------------------------
2170:
2171: sub domain_select {
2172: my ($name,$value,$multiple)=@_;
2173: my %domains=map {
2174: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2175: } &Apache::lonnet::all_domains();
2176: if ($multiple) {
2177: $domains{''}=&mt('Any domain');
2178: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2179: return &multiple_select_form($name,$value,4,\%domains);
2180: } else {
2181: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2182: return &select_form($name,$value,\%domains);
2183: }
2184: }
2185:
2186: #-------------------------------------------
2187:
2188: =pod
2189:
2190: =head1 Routines for form select boxes
2191:
2192: =over 4
2193:
2194: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2195:
2196: Returns a string containing a <select> element int multiple mode
2197:
2198:
2199: Args:
2200: $name - name of the <select> element
2201: $value - scalar or array ref of values that should already be selected
2202: $size - number of rows long the select element is
2203: $hash - the elements should be 'option' => 'shown text'
2204: (shown text should already have been &mt())
2205: $order - (optional) array ref of the order to show the elements in
2206:
2207: =cut
2208:
2209: #-------------------------------------------
2210: sub multiple_select_form {
2211: my ($name,$value,$size,$hash,$order)=@_;
2212: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2213: my $output='';
2214: if (! defined($size)) {
2215: $size = 4;
2216: if (scalar(keys(%$hash))<4) {
2217: $size = scalar(keys(%$hash));
2218: }
2219: }
2220: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2221: my @order;
2222: if (ref($order) eq 'ARRAY') {
2223: @order = @{$order};
2224: } else {
2225: @order = sort(keys(%$hash));
2226: }
2227: if (exists($$hash{'select_form_order'})) {
2228: @order = @{$$hash{'select_form_order'}};
2229: }
2230:
2231: foreach my $key (@order) {
2232: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2233: $output.='selected="selected" ' if ($selected{$key});
2234: $output.='>'.$hash->{$key}."</option>\n";
2235: }
2236: $output.="</select>\n";
2237: return $output;
2238: }
2239:
2240: #-------------------------------------------
2241:
2242: =pod
2243:
2244: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2245:
2246: Returns a string containing a <select name='$name' size='1'> form to
2247: allow a user to select options from a ref to a hash containing:
2248: option_name => displayed text. An optional $onchange can include
2249: a javascript onchange item, e.g., onchange="this.form.submit();".
2250: An optional arg -- $readonly -- if true will cause the select form
2251: to be disabled, e.g., for the case where an instructor has a section-
2252: specific role, and is viewing/modifying parameters.
2253:
2254: See lonrights.pm for an example invocation and use.
2255:
2256: =cut
2257:
2258: #-------------------------------------------
2259: sub select_form {
2260: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2261: return unless (ref($hashref) eq 'HASH');
2262: if ($onchange) {
2263: $onchange = ' onchange="'.$onchange.'"';
2264: }
2265: my $disabled;
2266: if ($readonly) {
2267: $disabled = ' disabled="disabled"';
2268: }
2269: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2270: my @keys;
2271: if (exists($hashref->{'select_form_order'})) {
2272: @keys=@{$hashref->{'select_form_order'}};
2273: } else {
2274: @keys=sort(keys(%{$hashref}));
2275: }
2276: foreach my $key (@keys) {
2277: $selectform.=
2278: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2279: ($key eq $def ? 'selected="selected" ' : '').
2280: ">".$hashref->{$key}."</option>\n";
2281: }
2282: $selectform.="</select>";
2283: return $selectform;
2284: }
2285:
2286: # For display filters
2287:
2288: sub display_filter {
2289: my ($context) = @_;
2290: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2291: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2292: my $phraseinput = 'hidden';
2293: my $includeinput = 'hidden';
2294: my ($checked,$includetypestext);
2295: if ($env{'form.displayfilter'} eq 'containing') {
2296: $phraseinput = 'text';
2297: if ($context eq 'parmslog') {
2298: $includeinput = 'checkbox';
2299: if ($env{'form.includetypes'}) {
2300: $checked = ' checked="checked"';
2301: }
2302: $includetypestext = &mt('Include parameter types');
2303: }
2304: } else {
2305: $includetypestext = ' ';
2306: }
2307: my ($additional,$secondid,$thirdid);
2308: if ($context eq 'parmslog') {
2309: $additional =
2310: '<label><input type="'.$includeinput.'" name="includetypes"'.
2311: $checked.' name="includetypes" value="1" id="includetypes" />'.
2312: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2313: '</label>';
2314: $secondid = 'includetypes';
2315: $thirdid = 'includetypestext';
2316: }
2317: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2318: '$secondid','$thirdid')";
2319: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2320: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2321: (&mt('all'),10,20,50,100,1000,10000))).
2322: '</label></span> <span class="LC_nobreak">'.
2323: &mt('Filter: [_1]',
2324: &select_form($env{'form.displayfilter'},
2325: 'displayfilter',
2326: {'currentfolder' => 'Current folder/page',
2327: 'containing' => 'Containing phrase',
2328: 'none' => 'None'},$onchange)).' '.
2329: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2330: &HTML::Entities::encode($env{'form.containingphrase'}).
2331: '" />'.$additional;
2332: }
2333:
2334: sub display_filter_js {
2335: my $includetext = &mt('Include parameter types');
2336: return <<"ENDJS";
2337:
2338: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2339: var firstType = 'hidden';
2340: if (setter.options[setter.selectedIndex].value == 'containing') {
2341: firstType = 'text';
2342: }
2343: firstObject = document.getElementById(firstid);
2344: if (typeof(firstObject) == 'object') {
2345: if (firstObject.type != firstType) {
2346: changeInputType(firstObject,firstType);
2347: }
2348: }
2349: if (context == 'parmslog') {
2350: var secondType = 'hidden';
2351: if (firstType == 'text') {
2352: secondType = 'checkbox';
2353: }
2354: secondObject = document.getElementById(secondid);
2355: if (typeof(secondObject) == 'object') {
2356: if (secondObject.type != secondType) {
2357: changeInputType(secondObject,secondType);
2358: }
2359: }
2360: var textItem = document.getElementById(thirdid);
2361: var currtext = textItem.innerHTML;
2362: var newtext;
2363: if (firstType == 'text') {
2364: newtext = '$includetext';
2365: } else {
2366: newtext = ' ';
2367: }
2368: if (currtext != newtext) {
2369: textItem.innerHTML = newtext;
2370: }
2371: }
2372: return;
2373: }
2374:
2375: function changeInputType(oldObject,newType) {
2376: var newObject = document.createElement('input');
2377: newObject.type = newType;
2378: if (oldObject.size) {
2379: newObject.size = oldObject.size;
2380: }
2381: if (oldObject.value) {
2382: newObject.value = oldObject.value;
2383: }
2384: if (oldObject.name) {
2385: newObject.name = oldObject.name;
2386: }
2387: if (oldObject.id) {
2388: newObject.id = oldObject.id;
2389: }
2390: oldObject.parentNode.replaceChild(newObject,oldObject);
2391: return;
2392: }
2393:
2394: ENDJS
2395: }
2396:
2397: sub gradeleveldescription {
2398: my $gradelevel=shift;
2399: my %gradelevels=(0 => 'Not specified',
2400: 1 => 'Grade 1',
2401: 2 => 'Grade 2',
2402: 3 => 'Grade 3',
2403: 4 => 'Grade 4',
2404: 5 => 'Grade 5',
2405: 6 => 'Grade 6',
2406: 7 => 'Grade 7',
2407: 8 => 'Grade 8',
2408: 9 => 'Grade 9',
2409: 10 => 'Grade 10',
2410: 11 => 'Grade 11',
2411: 12 => 'Grade 12',
2412: 13 => 'Grade 13',
2413: 14 => '100 Level',
2414: 15 => '200 Level',
2415: 16 => '300 Level',
2416: 17 => '400 Level',
2417: 18 => 'Graduate Level');
2418: return &mt($gradelevels{$gradelevel});
2419: }
2420:
2421: sub select_level_form {
2422: my ($deflevel,$name)=@_;
2423: unless ($deflevel) { $deflevel=0; }
2424: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2425: for (my $i=0; $i<=18; $i++) {
2426: $selectform.="<option value=\"$i\" ".
2427: ($i==$deflevel ? 'selected="selected" ' : '').
2428: ">".&gradeleveldescription($i)."</option>\n";
2429: }
2430: $selectform.="</select>";
2431: return $selectform;
2432: }
2433:
2434: #-------------------------------------------
2435:
2436: =pod
2437:
2438: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2439:
2440: Returns a string containing a <select name='$name' size='1'> form to
2441: allow a user to select the domain to preform an operation in.
2442: See loncreateuser.pm for an example invocation and use.
2443:
2444: If the $includeempty flag is set, it also includes an empty choice ("no domain
2445: selected");
2446:
2447: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2448:
2449: 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.
2450:
2451: The optional $incdoms is a reference to an array of domains which will be the only available options.
2452:
2453: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2454:
2455: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2456:
2457: =cut
2458:
2459: #-------------------------------------------
2460: sub select_dom_form {
2461: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2462: if ($onchange) {
2463: $onchange = ' onchange="'.$onchange.'"';
2464: }
2465: if ($disabled) {
2466: $disabled = ' disabled="disabled"';
2467: }
2468: my (@domains,%exclude);
2469: if (ref($incdoms) eq 'ARRAY') {
2470: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2471: } else {
2472: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2473: }
2474: if ($includeempty) { @domains=('',@domains); }
2475: if (ref($excdoms) eq 'ARRAY') {
2476: map { $exclude{$_} = 1; } @{$excdoms};
2477: }
2478: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2479: foreach my $dom (@domains) {
2480: next if ($exclude{$dom});
2481: $selectdomain.="<option value=\"$dom\" ".
2482: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2483: if ($showdomdesc) {
2484: if ($dom ne '') {
2485: my $domdesc = &Apache::lonnet::domain($dom,'description');
2486: if ($domdesc ne '') {
2487: $selectdomain .= ' ('.$domdesc.')';
2488: }
2489: }
2490: }
2491: $selectdomain .= "</option>\n";
2492: }
2493: $selectdomain.="</select>";
2494: return $selectdomain;
2495: }
2496:
2497: #-------------------------------------------
2498:
2499: =pod
2500:
2501: =item * &home_server_form_item($domain,$name,$defaultflag)
2502:
2503: input: 4 arguments (two required, two optional) -
2504: $domain - domain of new user
2505: $name - name of form element
2506: $default - Value of 'default' causes a default item to be first
2507: option, and selected by default.
2508: $hide - Value of 'hide' causes hiding of the name of the server,
2509: if 1 server found, or default, if 0 found.
2510: output: returns 2 items:
2511: (a) form element which contains either:
2512: (i) <select name="$name">
2513: <option value="$hostid1">$hostid $servers{$hostid}</option>
2514: <option value="$hostid2">$hostid $servers{$hostid}</option>
2515: </select>
2516: form item if there are multiple library servers in $domain, or
2517: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2518: if there is only one library server in $domain.
2519:
2520: (b) number of library servers found.
2521:
2522: See loncreateuser.pm for example of use.
2523:
2524: =cut
2525:
2526: #-------------------------------------------
2527: sub home_server_form_item {
2528: my ($domain,$name,$default,$hide) = @_;
2529: my %servers = &Apache::lonnet::get_servers($domain,'library');
2530: my $result;
2531: my $numlib = keys(%servers);
2532: if ($numlib > 1) {
2533: $result .= '<select name="'.$name.'" />'."\n";
2534: if ($default) {
2535: $result .= '<option value="default" selected="selected">'.&mt('default').
2536: '</option>'."\n";
2537: }
2538: foreach my $hostid (sort(keys(%servers))) {
2539: $result.= '<option value="'.$hostid.'">'.
2540: $hostid.' '.$servers{$hostid}."</option>\n";
2541: }
2542: $result .= '</select>'."\n";
2543: } elsif ($numlib == 1) {
2544: my $hostid;
2545: foreach my $item (keys(%servers)) {
2546: $hostid = $item;
2547: }
2548: $result .= '<input type="hidden" name="'.$name.'" value="'.
2549: $hostid.'" />';
2550: if (!$hide) {
2551: $result .= $hostid.' '.$servers{$hostid};
2552: }
2553: $result .= "\n";
2554: } elsif ($default) {
2555: $result .= '<input type="hidden" name="'.$name.
2556: '" value="default" />';
2557: if (!$hide) {
2558: $result .= &mt('default');
2559: }
2560: $result .= "\n";
2561: }
2562: return ($result,$numlib);
2563: }
2564:
2565: =pod
2566:
2567: =back
2568:
2569: =cut
2570:
2571: ###############################################################
2572: ## Decoding User Agent ##
2573: ###############################################################
2574:
2575: =pod
2576:
2577: =head1 Decoding the User Agent
2578:
2579: =over 4
2580:
2581: =item * &decode_user_agent()
2582:
2583: Inputs: $r
2584:
2585: Outputs:
2586:
2587: =over 4
2588:
2589: =item * $httpbrowser
2590:
2591: =item * $clientbrowser
2592:
2593: =item * $clientversion
2594:
2595: =item * $clientmathml
2596:
2597: =item * $clientunicode
2598:
2599: =item * $clientos
2600:
2601: =item * $clientmobile
2602:
2603: =item * $clientinfo
2604:
2605: =item * $clientosversion
2606:
2607: =back
2608:
2609: =back
2610:
2611: =cut
2612:
2613: ###############################################################
2614: ###############################################################
2615: sub decode_user_agent {
2616: my ($r)=@_;
2617: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2618: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2619: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2620: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2621: my $clientbrowser='unknown';
2622: my $clientversion='0';
2623: my $clientmathml='';
2624: my $clientunicode='0';
2625: my $clientmobile=0;
2626: my $clientosversion='';
2627: for (my $i=0;$i<=$#browsertype;$i++) {
2628: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2629: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2630: $clientbrowser=$bname;
2631: $httpbrowser=~/$vreg/i;
2632: $clientversion=$1;
2633: $clientmathml=($clientversion>=$minv);
2634: $clientunicode=($clientversion>=$univ);
2635: }
2636: }
2637: my $clientos='unknown';
2638: my $clientinfo;
2639: if (($httpbrowser=~/linux/i) ||
2640: ($httpbrowser=~/unix/i) ||
2641: ($httpbrowser=~/ux/i) ||
2642: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2643: if (($httpbrowser=~/vax/i) ||
2644: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2645: if ($httpbrowser=~/next/i) { $clientos='next'; }
2646: if (($httpbrowser=~/mac/i) ||
2647: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2648: if ($httpbrowser=~/win/i) {
2649: $clientos='win';
2650: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2651: $clientosversion = $1;
2652: }
2653: }
2654: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2655: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2656: $clientmobile=lc($1);
2657: }
2658: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2659: $clientinfo = 'firefox-'.$1;
2660: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2661: $clientinfo = 'chromeframe-'.$1;
2662: }
2663: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2664: $clientunicode,$clientos,$clientmobile,$clientinfo,
2665: $clientosversion);
2666: }
2667:
2668: ###############################################################
2669: ## Authentication changing form generation subroutines ##
2670: ###############################################################
2671: ##
2672: ## All of the authform_xxxxxxx subroutines take their inputs in a
2673: ## hash, and have reasonable default values.
2674: ##
2675: ## formname = the name given in the <form> tag.
2676: #-------------------------------------------
2677:
2678: =pod
2679:
2680: =head1 Authentication Routines
2681:
2682: =over 4
2683:
2684: =item * &authform_xxxxxx()
2685:
2686: The authform_xxxxxx subroutines provide javascript and html forms which
2687: handle some of the conveniences required for authentication forms.
2688: This is not an optimal method, but it works.
2689:
2690: =over 4
2691:
2692: =item * authform_header
2693:
2694: =item * authform_authorwarning
2695:
2696: =item * authform_nochange
2697:
2698: =item * authform_kerberos
2699:
2700: =item * authform_internal
2701:
2702: =item * authform_filesystem
2703:
2704: =back
2705:
2706: See loncreateuser.pm for invocation and use examples.
2707:
2708: =cut
2709:
2710: #-------------------------------------------
2711: sub authform_header{
2712: my %in = (
2713: formname => 'cu',
2714: kerb_def_dom => '',
2715: @_,
2716: );
2717: $in{'formname'} = 'document.' . $in{'formname'};
2718: my $result='';
2719:
2720: #---------------------------------------------- Code for upper case translation
2721: my $Javascript_toUpperCase;
2722: unless ($in{kerb_def_dom}) {
2723: $Javascript_toUpperCase =<<"END";
2724: switch (choice) {
2725: case 'krb': currentform.elements[choicearg].value =
2726: currentform.elements[choicearg].value.toUpperCase();
2727: break;
2728: default:
2729: }
2730: END
2731: } else {
2732: $Javascript_toUpperCase = "";
2733: }
2734:
2735: my $radioval = "'nochange'";
2736: if (defined($in{'curr_authtype'})) {
2737: if ($in{'curr_authtype'} ne '') {
2738: $radioval = "'".$in{'curr_authtype'}."arg'";
2739: }
2740: }
2741: my $argfield = 'null';
2742: if (defined($in{'mode'})) {
2743: if ($in{'mode'} eq 'modifycourse') {
2744: if (defined($in{'curr_autharg'})) {
2745: if ($in{'curr_autharg'} ne '') {
2746: $argfield = "'$in{'curr_autharg'}'";
2747: }
2748: }
2749: }
2750: }
2751:
2752: $result.=<<"END";
2753: var current = new Object();
2754: current.radiovalue = $radioval;
2755: current.argfield = $argfield;
2756:
2757: function changed_radio(choice,currentform) {
2758: var choicearg = choice + 'arg';
2759: // If a radio button in changed, we need to change the argfield
2760: if (current.radiovalue != choice) {
2761: current.radiovalue = choice;
2762: if (current.argfield != null) {
2763: currentform.elements[current.argfield].value = '';
2764: }
2765: if (choice == 'nochange') {
2766: current.argfield = null;
2767: } else {
2768: current.argfield = choicearg;
2769: switch(choice) {
2770: case 'krb':
2771: currentform.elements[current.argfield].value =
2772: "$in{'kerb_def_dom'}";
2773: break;
2774: default:
2775: break;
2776: }
2777: }
2778: }
2779: return;
2780: }
2781:
2782: function changed_text(choice,currentform) {
2783: var choicearg = choice + 'arg';
2784: if (currentform.elements[choicearg].value !='') {
2785: $Javascript_toUpperCase
2786: // clear old field
2787: if ((current.argfield != choicearg) && (current.argfield != null)) {
2788: currentform.elements[current.argfield].value = '';
2789: }
2790: current.argfield = choicearg;
2791: }
2792: set_auth_radio_buttons(choice,currentform);
2793: return;
2794: }
2795:
2796: function set_auth_radio_buttons(newvalue,currentform) {
2797: var numauthchoices = currentform.login.length;
2798: if (typeof numauthchoices == "undefined") {
2799: return;
2800: }
2801: var i=0;
2802: while (i < numauthchoices) {
2803: if (currentform.login[i].value == newvalue) { break; }
2804: i++;
2805: }
2806: if (i == numauthchoices) {
2807: return;
2808: }
2809: current.radiovalue = newvalue;
2810: currentform.login[i].checked = true;
2811: return;
2812: }
2813: END
2814: return $result;
2815: }
2816:
2817: sub authform_authorwarning {
2818: my $result='';
2819: $result='<i>'.
2820: &mt('As a general rule, only authors or co-authors should be '.
2821: 'filesystem authenticated '.
2822: '(which allows access to the server filesystem).')."</i>\n";
2823: return $result;
2824: }
2825:
2826: sub authform_nochange {
2827: my %in = (
2828: formname => 'document.cu',
2829: kerb_def_dom => 'MSU.EDU',
2830: @_,
2831: );
2832: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2833: my $result;
2834: if (!$authnum) {
2835: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2836: } else {
2837: $result = '<label>'.&mt('[_1] Do not change login data',
2838: '<input type="radio" name="login" value="nochange" '.
2839: 'checked="checked" onclick="'.
2840: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2841: '</label>';
2842: }
2843: return $result;
2844: }
2845:
2846: sub authform_kerberos {
2847: my %in = (
2848: formname => 'document.cu',
2849: kerb_def_dom => 'MSU.EDU',
2850: kerb_def_auth => 'krb4',
2851: @_,
2852: );
2853: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2854: $autharg,$jscall,$disabled);
2855: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2856: if ($in{'kerb_def_auth'} eq 'krb5') {
2857: $check5 = ' checked="checked"';
2858: } else {
2859: $check4 = ' checked="checked"';
2860: }
2861: if ($in{'readonly'}) {
2862: $disabled = ' disabled="disabled"';
2863: }
2864: $krbarg = $in{'kerb_def_dom'};
2865: if (defined($in{'curr_authtype'})) {
2866: if ($in{'curr_authtype'} eq 'krb') {
2867: $krbcheck = ' checked="checked"';
2868: if (defined($in{'mode'})) {
2869: if ($in{'mode'} eq 'modifyuser') {
2870: $krbcheck = '';
2871: }
2872: }
2873: if (defined($in{'curr_kerb_ver'})) {
2874: if ($in{'curr_krb_ver'} eq '5') {
2875: $check5 = ' checked="checked"';
2876: $check4 = '';
2877: } else {
2878: $check4 = ' checked="checked"';
2879: $check5 = '';
2880: }
2881: }
2882: if (defined($in{'curr_autharg'})) {
2883: $krbarg = $in{'curr_autharg'};
2884: }
2885: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2886: if (defined($in{'curr_autharg'})) {
2887: $result =
2888: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2889: $in{'curr_autharg'},$krbver);
2890: } else {
2891: $result =
2892: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2893: }
2894: return $result;
2895: }
2896: }
2897: } else {
2898: if ($authnum == 1) {
2899: $authtype = '<input type="hidden" name="login" value="krb" />';
2900: }
2901: }
2902: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2903: return;
2904: } elsif ($authtype eq '') {
2905: if (defined($in{'mode'})) {
2906: if ($in{'mode'} eq 'modifycourse') {
2907: if ($authnum == 1) {
2908: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
2909: }
2910: }
2911: }
2912: }
2913: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2914: if ($authtype eq '') {
2915: $authtype = '<input type="radio" name="login" value="krb" '.
2916: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2917: $krbcheck.$disabled.' />';
2918: }
2919: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2920: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2921: $in{'curr_authtype'} eq 'krb5') ||
2922: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2923: $in{'curr_authtype'} eq 'krb4')) {
2924: $result .= &mt
2925: ('[_1] Kerberos authenticated with domain [_2] '.
2926: '[_3] Version 4 [_4] Version 5 [_5]',
2927: '<label>'.$authtype,
2928: '</label><input type="text" size="10" name="krbarg" '.
2929: 'value="'.$krbarg.'" '.
2930: 'onchange="'.$jscall.'"'.$disabled.' />',
2931: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
2932: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
2933: '</label>');
2934: } elsif ($can_assign{'krb4'}) {
2935: $result .= &mt
2936: ('[_1] Kerberos authenticated with domain [_2] '.
2937: '[_3] Version 4 [_4]',
2938: '<label>'.$authtype,
2939: '</label><input type="text" size="10" name="krbarg" '.
2940: 'value="'.$krbarg.'" '.
2941: 'onchange="'.$jscall.'"'.$disabled.' />',
2942: '<label><input type="hidden" name="krbver" value="4" />',
2943: '</label>');
2944: } elsif ($can_assign{'krb5'}) {
2945: $result .= &mt
2946: ('[_1] Kerberos authenticated with domain [_2] '.
2947: '[_3] Version 5 [_4]',
2948: '<label>'.$authtype,
2949: '</label><input type="text" size="10" name="krbarg" '.
2950: 'value="'.$krbarg.'" '.
2951: 'onchange="'.$jscall.'"'.$disabled.' />',
2952: '<label><input type="hidden" name="krbver" value="5" />',
2953: '</label>');
2954: }
2955: return $result;
2956: }
2957:
2958: sub authform_internal {
2959: my %in = (
2960: formname => 'document.cu',
2961: kerb_def_dom => 'MSU.EDU',
2962: @_,
2963: );
2964: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
2965: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2966: if ($in{'readonly'}) {
2967: $disabled = ' disabled="disabled"';
2968: }
2969: if (defined($in{'curr_authtype'})) {
2970: if ($in{'curr_authtype'} eq 'int') {
2971: if ($can_assign{'int'}) {
2972: $intcheck = 'checked="checked" ';
2973: if (defined($in{'mode'})) {
2974: if ($in{'mode'} eq 'modifyuser') {
2975: $intcheck = '';
2976: }
2977: }
2978: if (defined($in{'curr_autharg'})) {
2979: $intarg = $in{'curr_autharg'};
2980: }
2981: } else {
2982: $result = &mt('Currently internally authenticated.');
2983: return $result;
2984: }
2985: }
2986: } else {
2987: if ($authnum == 1) {
2988: $authtype = '<input type="hidden" name="login" value="int" />';
2989: }
2990: }
2991: if (!$can_assign{'int'}) {
2992: return;
2993: } elsif ($authtype eq '') {
2994: if (defined($in{'mode'})) {
2995: if ($in{'mode'} eq 'modifycourse') {
2996: if ($authnum == 1) {
2997: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
2998: }
2999: }
3000: }
3001: }
3002: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3003: if ($authtype eq '') {
3004: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3005: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3006: }
3007: $autharg = '<input type="password" size="10" name="intarg" value="'.
3008: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3009: $result = &mt
3010: ('[_1] Internally authenticated (with initial password [_2])',
3011: '<label>'.$authtype,'</label>'.$autharg);
3012: $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
3013: return $result;
3014: }
3015:
3016: sub authform_local {
3017: my %in = (
3018: formname => 'document.cu',
3019: kerb_def_dom => 'MSU.EDU',
3020: @_,
3021: );
3022: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3023: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3024: if ($in{'readonly'}) {
3025: $disabled = ' disabled="disabled"';
3026: }
3027: if (defined($in{'curr_authtype'})) {
3028: if ($in{'curr_authtype'} eq 'loc') {
3029: if ($can_assign{'loc'}) {
3030: $loccheck = 'checked="checked" ';
3031: if (defined($in{'mode'})) {
3032: if ($in{'mode'} eq 'modifyuser') {
3033: $loccheck = '';
3034: }
3035: }
3036: if (defined($in{'curr_autharg'})) {
3037: $locarg = $in{'curr_autharg'};
3038: }
3039: } else {
3040: $result = &mt('Currently using local (institutional) authentication.');
3041: return $result;
3042: }
3043: }
3044: } else {
3045: if ($authnum == 1) {
3046: $authtype = '<input type="hidden" name="login" value="loc" />';
3047: }
3048: }
3049: if (!$can_assign{'loc'}) {
3050: return;
3051: } elsif ($authtype eq '') {
3052: if (defined($in{'mode'})) {
3053: if ($in{'mode'} eq 'modifycourse') {
3054: if ($authnum == 1) {
3055: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3056: }
3057: }
3058: }
3059: }
3060: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3061: if ($authtype eq '') {
3062: $authtype = '<input type="radio" name="login" value="loc" '.
3063: $loccheck.' onchange="'.$jscall.'" onclick="'.
3064: $jscall.'"'.$disabled.' />';
3065: }
3066: $autharg = '<input type="text" size="10" name="locarg" value="'.
3067: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3068: $result = &mt('[_1] Local Authentication with argument [_2]',
3069: '<label>'.$authtype,'</label>'.$autharg);
3070: return $result;
3071: }
3072:
3073: sub authform_filesystem {
3074: my %in = (
3075: formname => 'document.cu',
3076: kerb_def_dom => 'MSU.EDU',
3077: @_,
3078: );
3079: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3080: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3081: if ($in{'readonly'}) {
3082: $disabled = ' disabled="disabled"';
3083: }
3084: if (defined($in{'curr_authtype'})) {
3085: if ($in{'curr_authtype'} eq 'fsys') {
3086: if ($can_assign{'fsys'}) {
3087: $fsyscheck = 'checked="checked" ';
3088: if (defined($in{'mode'})) {
3089: if ($in{'mode'} eq 'modifyuser') {
3090: $fsyscheck = '';
3091: }
3092: }
3093: } else {
3094: $result = &mt('Currently Filesystem Authenticated.');
3095: return $result;
3096: }
3097: }
3098: } else {
3099: if ($authnum == 1) {
3100: $authtype = '<input type="hidden" name="login" value="fsys" />';
3101: }
3102: }
3103: if (!$can_assign{'fsys'}) {
3104: return;
3105: } elsif ($authtype eq '') {
3106: if (defined($in{'mode'})) {
3107: if ($in{'mode'} eq 'modifycourse') {
3108: if ($authnum == 1) {
3109: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3110: }
3111: }
3112: }
3113: }
3114: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3115: if ($authtype eq '') {
3116: $authtype = '<input type="radio" name="login" value="fsys" '.
3117: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3118: $jscall.'"'.$disabled.' />';
3119: }
3120: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
3121: ' onchange="'.$jscall.'"'.$disabled.' />';
3122: $result = &mt
3123: ('[_1] Filesystem Authenticated (with initial password [_2])',
3124: '<label><input type="radio" name="login" value="fsys" '.
3125: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
3126: '</label><input type="password" size="10" name="fsysarg" value="" '.
3127: 'onchange="'.$jscall.'"'.$disabled.' />');
3128: return $result;
3129: }
3130:
3131: sub get_assignable_auth {
3132: my ($dom) = @_;
3133: if ($dom eq '') {
3134: $dom = $env{'request.role.domain'};
3135: }
3136: my %can_assign = (
3137: krb4 => 1,
3138: krb5 => 1,
3139: int => 1,
3140: loc => 1,
3141: );
3142: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3143: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3144: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3145: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3146: my $context;
3147: if ($env{'request.role'} =~ /^au/) {
3148: $context = 'author';
3149: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3150: $context = 'domain';
3151: } elsif ($env{'request.course.id'}) {
3152: $context = 'course';
3153: }
3154: if ($context) {
3155: if (ref($authhash->{$context}) eq 'HASH') {
3156: %can_assign = %{$authhash->{$context}};
3157: }
3158: }
3159: }
3160: }
3161: my $authnum = 0;
3162: foreach my $key (keys(%can_assign)) {
3163: if ($can_assign{$key}) {
3164: $authnum ++;
3165: }
3166: }
3167: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3168: $authnum --;
3169: }
3170: return ($authnum,%can_assign);
3171: }
3172:
3173: ###############################################################
3174: ## Get Kerberos Defaults for Domain ##
3175: ###############################################################
3176: ##
3177: ## Returns default kerberos version and an associated argument
3178: ## as listed in file domain.tab. If not listed, provides
3179: ## appropriate default domain and kerberos version.
3180: ##
3181: #-------------------------------------------
3182:
3183: =pod
3184:
3185: =item * &get_kerberos_defaults()
3186:
3187: get_kerberos_defaults($target_domain) returns the default kerberos
3188: version and domain. If not found, it defaults to version 4 and the
3189: domain of the server.
3190:
3191: =over 4
3192:
3193: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3194:
3195: =back
3196:
3197: =back
3198:
3199: =cut
3200:
3201: #-------------------------------------------
3202: sub get_kerberos_defaults {
3203: my $domain=shift;
3204: my ($krbdef,$krbdefdom);
3205: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3206: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3207: $krbdef = $domdefaults{'auth_def'};
3208: $krbdefdom = $domdefaults{'auth_arg_def'};
3209: } else {
3210: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3211: my $krbdefdom=$1;
3212: $krbdefdom=~tr/a-z/A-Z/;
3213: $krbdef = "krb4";
3214: }
3215: return ($krbdef,$krbdefdom);
3216: }
3217:
3218:
3219: ###############################################################
3220: ## Thesaurus Functions ##
3221: ###############################################################
3222:
3223: =pod
3224:
3225: =head1 Thesaurus Functions
3226:
3227: =over 4
3228:
3229: =item * &initialize_keywords()
3230:
3231: Initializes the package variable %Keywords if it is empty. Uses the
3232: package variable $thesaurus_db_file.
3233:
3234: =cut
3235:
3236: ###################################################
3237:
3238: sub initialize_keywords {
3239: return 1 if (scalar keys(%Keywords));
3240: # If we are here, %Keywords is empty, so fill it up
3241: # Make sure the file we need exists...
3242: if (! -e $thesaurus_db_file) {
3243: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3244: " failed because it does not exist");
3245: return 0;
3246: }
3247: # Set up the hash as a database
3248: my %thesaurus_db;
3249: if (! tie(%thesaurus_db,'GDBM_File',
3250: $thesaurus_db_file,&GDBM_READER(),0640)){
3251: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3252: $thesaurus_db_file);
3253: return 0;
3254: }
3255: # Get the average number of appearances of a word.
3256: my $avecount = $thesaurus_db{'average.count'};
3257: # Put keywords (those that appear > average) into %Keywords
3258: while (my ($word,$data)=each (%thesaurus_db)) {
3259: my ($count,undef) = split /:/,$data;
3260: $Keywords{$word}++ if ($count > $avecount);
3261: }
3262: untie %thesaurus_db;
3263: # Remove special values from %Keywords.
3264: foreach my $value ('total.count','average.count') {
3265: delete($Keywords{$value}) if (exists($Keywords{$value}));
3266: }
3267: return 1;
3268: }
3269:
3270: ###################################################
3271:
3272: =pod
3273:
3274: =item * &keyword($word)
3275:
3276: Returns true if $word is a keyword. A keyword is a word that appears more
3277: than the average number of times in the thesaurus database. Calls
3278: &initialize_keywords
3279:
3280: =cut
3281:
3282: ###################################################
3283:
3284: sub keyword {
3285: return if (!&initialize_keywords());
3286: my $word=lc(shift());
3287: $word=~s/\W//g;
3288: return exists($Keywords{$word});
3289: }
3290:
3291: ###############################################################
3292:
3293: =pod
3294:
3295: =item * &get_related_words()
3296:
3297: Look up a word in the thesaurus. Takes a scalar argument and returns
3298: an array of words. If the keyword is not in the thesaurus, an empty array
3299: will be returned. The order of the words returned is determined by the
3300: database which holds them.
3301:
3302: Uses global $thesaurus_db_file.
3303:
3304:
3305: =cut
3306:
3307: ###############################################################
3308: sub get_related_words {
3309: my $keyword = shift;
3310: my %thesaurus_db;
3311: if (! -e $thesaurus_db_file) {
3312: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3313: "failed because the file does not exist");
3314: return ();
3315: }
3316: if (! tie(%thesaurus_db,'GDBM_File',
3317: $thesaurus_db_file,&GDBM_READER(),0640)){
3318: return ();
3319: }
3320: my @Words=();
3321: my $count=0;
3322: if (exists($thesaurus_db{$keyword})) {
3323: # The first element is the number of times
3324: # the word appears. We do not need it now.
3325: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3326: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3327: my $threshold=$mostfrequentcount/10;
3328: foreach my $possibleword (@RelatedWords) {
3329: my ($word,$wordcount)=split(/\,/,$possibleword);
3330: if ($wordcount>$threshold) {
3331: push(@Words,$word);
3332: $count++;
3333: if ($count>10) { last; }
3334: }
3335: }
3336: }
3337: untie %thesaurus_db;
3338: return @Words;
3339: }
3340:
3341: =pod
3342:
3343: =back
3344:
3345: =cut
3346:
3347: # -------------------------------------------------------------- Plaintext name
3348: =pod
3349:
3350: =head1 User Name Functions
3351:
3352: =over 4
3353:
3354: =item * &plainname($uname,$udom,$first)
3355:
3356: Takes a users logon name and returns it as a string in
3357: "first middle last generation" form
3358: if $first is set to 'lastname' then it returns it as
3359: 'lastname generation, firstname middlename' if their is a lastname
3360:
3361: =cut
3362:
3363:
3364: ###############################################################
3365: sub plainname {
3366: my ($uname,$udom,$first)=@_;
3367: return if (!defined($uname) || !defined($udom));
3368: my %names=&getnames($uname,$udom);
3369: my $name=&Apache::lonnet::format_name($names{'firstname'},
3370: $names{'middlename'},
3371: $names{'lastname'},
3372: $names{'generation'},$first);
3373: $name=~s/^\s+//;
3374: $name=~s/\s+$//;
3375: $name=~s/\s+/ /g;
3376: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3377: return $name;
3378: }
3379:
3380: # -------------------------------------------------------------------- Nickname
3381: =pod
3382:
3383: =item * &nickname($uname,$udom)
3384:
3385: Gets a users name and returns it as a string as
3386:
3387: ""nickname""
3388:
3389: if the user has a nickname or
3390:
3391: "first middle last generation"
3392:
3393: if the user does not
3394:
3395: =cut
3396:
3397: sub nickname {
3398: my ($uname,$udom)=@_;
3399: return if (!defined($uname) || !defined($udom));
3400: my %names=&getnames($uname,$udom);
3401: my $name=$names{'nickname'};
3402: if ($name) {
3403: $name='"'.$name.'"';
3404: } else {
3405: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3406: $names{'lastname'}.' '.$names{'generation'};
3407: $name=~s/\s+$//;
3408: $name=~s/\s+/ /g;
3409: }
3410: return $name;
3411: }
3412:
3413: sub getnames {
3414: my ($uname,$udom)=@_;
3415: return if (!defined($uname) || !defined($udom));
3416: if ($udom eq 'public' && $uname eq 'public') {
3417: return ('lastname' => &mt('Public'));
3418: }
3419: my $id=$uname.':'.$udom;
3420: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3421: if ($cached) {
3422: return %{$names};
3423: } else {
3424: my %loadnames=&Apache::lonnet::get('environment',
3425: ['firstname','middlename','lastname','generation','nickname'],
3426: $udom,$uname);
3427: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3428: return %loadnames;
3429: }
3430: }
3431:
3432: # -------------------------------------------------------------------- getemails
3433:
3434: =pod
3435:
3436: =item * &getemails($uname,$udom)
3437:
3438: Gets a user's email information and returns it as a hash with keys:
3439: notification, critnotification, permanentemail
3440:
3441: For notification and critnotification, values are comma-separated lists
3442: of e-mail addresses; for permanentemail, value is a single e-mail address.
3443:
3444:
3445: =cut
3446:
3447:
3448: sub getemails {
3449: my ($uname,$udom)=@_;
3450: if ($udom eq 'public' && $uname eq 'public') {
3451: return;
3452: }
3453: if (!$udom) { $udom=$env{'user.domain'}; }
3454: if (!$uname) { $uname=$env{'user.name'}; }
3455: my $id=$uname.':'.$udom;
3456: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3457: if ($cached) {
3458: return %{$names};
3459: } else {
3460: my %loadnames=&Apache::lonnet::get('environment',
3461: ['notification','critnotification',
3462: 'permanentemail'],
3463: $udom,$uname);
3464: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3465: return %loadnames;
3466: }
3467: }
3468:
3469: sub flush_email_cache {
3470: my ($uname,$udom)=@_;
3471: if (!$udom) { $udom =$env{'user.domain'}; }
3472: if (!$uname) { $uname=$env{'user.name'}; }
3473: return if ($udom eq 'public' && $uname eq 'public');
3474: my $id=$uname.':'.$udom;
3475: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3476: }
3477:
3478: # -------------------------------------------------------------------- getlangs
3479:
3480: =pod
3481:
3482: =item * &getlangs($uname,$udom)
3483:
3484: Gets a user's language preference and returns it as a hash with key:
3485: language.
3486:
3487: =cut
3488:
3489:
3490: sub getlangs {
3491: my ($uname,$udom) = @_;
3492: if (!$udom) { $udom =$env{'user.domain'}; }
3493: if (!$uname) { $uname=$env{'user.name'}; }
3494: my $id=$uname.':'.$udom;
3495: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3496: if ($cached) {
3497: return %{$langs};
3498: } else {
3499: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3500: $udom,$uname);
3501: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3502: return %loadlangs;
3503: }
3504: }
3505:
3506: sub flush_langs_cache {
3507: my ($uname,$udom)=@_;
3508: if (!$udom) { $udom =$env{'user.domain'}; }
3509: if (!$uname) { $uname=$env{'user.name'}; }
3510: return if ($udom eq 'public' && $uname eq 'public');
3511: my $id=$uname.':'.$udom;
3512: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3513: }
3514:
3515: # ------------------------------------------------------------------ Screenname
3516:
3517: =pod
3518:
3519: =item * &screenname($uname,$udom)
3520:
3521: Gets a users screenname and returns it as a string
3522:
3523: =cut
3524:
3525: sub screenname {
3526: my ($uname,$udom)=@_;
3527: if ($uname eq $env{'user.name'} &&
3528: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3529: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3530: return $names{'screenname'};
3531: }
3532:
3533:
3534: # ------------------------------------------------------------- Confirm Wrapper
3535: =pod
3536:
3537: =item * &confirmwrapper($message)
3538:
3539: Wrap messages about completion of operation in box
3540:
3541: =cut
3542:
3543: sub confirmwrapper {
3544: my ($message)=@_;
3545: if ($message) {
3546: return "\n".'<div class="LC_confirm_box">'."\n"
3547: .$message."\n"
3548: .'</div>'."\n";
3549: } else {
3550: return $message;
3551: }
3552: }
3553:
3554: # ------------------------------------------------------------- Message Wrapper
3555:
3556: sub messagewrapper {
3557: my ($link,$username,$domain,$subject,$text)=@_;
3558: return
3559: '<a href="/adm/email?compose=individual&'.
3560: 'recname='.$username.'&recdom='.$domain.
3561: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3562: 'title="'.&mt('Send message').'">'.$link.'</a>';
3563: }
3564:
3565: # --------------------------------------------------------------- Notes Wrapper
3566:
3567: sub noteswrapper {
3568: my ($link,$un,$do)=@_;
3569: return
3570: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3571: }
3572:
3573: # ------------------------------------------------------------- Aboutme Wrapper
3574:
3575: sub aboutmewrapper {
3576: my ($link,$username,$domain,$target,$class)=@_;
3577: if (!defined($username) && !defined($domain)) {
3578: return;
3579: }
3580: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3581: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3582: }
3583:
3584: # ------------------------------------------------------------ Syllabus Wrapper
3585:
3586: sub syllabuswrapper {
3587: my ($linktext,$coursedir,$domain)=@_;
3588: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3589: }
3590:
3591: # -----------------------------------------------------------------------------
3592:
3593: sub track_student_link {
3594: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3595: my $link ="/adm/trackstudent?";
3596: my $title = 'View recent activity';
3597: if (defined($sname) && $sname !~ /^\s*$/ &&
3598: defined($sdom) && $sdom !~ /^\s*$/) {
3599: $link .= "selected_student=$sname:$sdom";
3600: $title .= ' of this student';
3601: }
3602: if (defined($target) && $target !~ /^\s*$/) {
3603: $target = qq{target="$target"};
3604: } else {
3605: $target = '';
3606: }
3607: if ($start) { $link.='&start='.$start; }
3608: if ($only_body) { $link .= '&only_body=1'; }
3609: $title = &mt($title);
3610: $linktext = &mt($linktext);
3611: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3612: &help_open_topic('View_recent_activity');
3613: }
3614:
3615: sub slot_reservations_link {
3616: my ($linktext,$sname,$sdom,$target) = @_;
3617: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3618: my $title = 'View slot reservation history';
3619: if (defined($sname) && $sname !~ /^\s*$/ &&
3620: defined($sdom) && $sdom !~ /^\s*$/) {
3621: $link .= "&uname=$sname&udom=$sdom";
3622: $title .= ' of this student';
3623: }
3624: if (defined($target) && $target !~ /^\s*$/) {
3625: $target = qq{target="$target"};
3626: } else {
3627: $target = '';
3628: }
3629: $title = &mt($title);
3630: $linktext = &mt($linktext);
3631: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3632: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3633:
3634: }
3635:
3636: # ===================================================== Display a student photo
3637:
3638:
3639: sub student_image_tag {
3640: my ($domain,$user)=@_;
3641: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3642: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3643: return '<img src="'.$imgsrc.'" align="right" />';
3644: } else {
3645: return '';
3646: }
3647: }
3648:
3649: =pod
3650:
3651: =back
3652:
3653: =head1 Access .tab File Data
3654:
3655: =over 4
3656:
3657: =item * &languageids()
3658:
3659: returns list of all language ids
3660:
3661: =cut
3662:
3663: sub languageids {
3664: return sort(keys(%language));
3665: }
3666:
3667: =pod
3668:
3669: =item * &languagedescription()
3670:
3671: returns description of a specified language id
3672:
3673: =cut
3674:
3675: sub languagedescription {
3676: my $code=shift;
3677: return ($supported_language{$code}?'* ':'').
3678: $language{$code}.
3679: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3680: }
3681:
3682: =pod
3683:
3684: =item * &plainlanguagedescription
3685:
3686: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3687: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3688:
3689: =cut
3690:
3691: sub plainlanguagedescription {
3692: my $code=shift;
3693: return $language{$code};
3694: }
3695:
3696: =pod
3697:
3698: =item * &supportedlanguagecode
3699:
3700: Returns the supported language code (e.g. sptutf maps to pt) given a language
3701: code.
3702:
3703: =cut
3704:
3705: sub supportedlanguagecode {
3706: my $code=shift;
3707: return $supported_language{$code};
3708: }
3709:
3710: =pod
3711:
3712: =item * &latexlanguage()
3713:
3714: Given a language key code returns the correspondnig language to use
3715: to select the correct hyphenation on LaTeX printouts. This is undef if there
3716: is no supported hyphenation for the language code.
3717:
3718: =cut
3719:
3720: sub latexlanguage {
3721: my $code = shift;
3722: return $latex_language{$code};
3723: }
3724:
3725: =pod
3726:
3727: =item * &latexhyphenation()
3728:
3729: Same as above but what's supplied is the language as it might be stored
3730: in the metadata.
3731:
3732: =cut
3733:
3734: sub latexhyphenation {
3735: my $key = shift;
3736: return $latex_language_bykey{$key};
3737: }
3738:
3739: =pod
3740:
3741: =item * ©rightids()
3742:
3743: returns list of all copyrights
3744:
3745: =cut
3746:
3747: sub copyrightids {
3748: return sort(keys(%cprtag));
3749: }
3750:
3751: =pod
3752:
3753: =item * ©rightdescription()
3754:
3755: returns description of a specified copyright id
3756:
3757: =cut
3758:
3759: sub copyrightdescription {
3760: return &mt($cprtag{shift(@_)});
3761: }
3762:
3763: =pod
3764:
3765: =item * &source_copyrightids()
3766:
3767: returns list of all source copyrights
3768:
3769: =cut
3770:
3771: sub source_copyrightids {
3772: return sort(keys(%scprtag));
3773: }
3774:
3775: =pod
3776:
3777: =item * &source_copyrightdescription()
3778:
3779: returns description of a specified source copyright id
3780:
3781: =cut
3782:
3783: sub source_copyrightdescription {
3784: return &mt($scprtag{shift(@_)});
3785: }
3786:
3787: =pod
3788:
3789: =item * &filecategories()
3790:
3791: returns list of all file categories
3792:
3793: =cut
3794:
3795: sub filecategories {
3796: return sort(keys(%category_extensions));
3797: }
3798:
3799: =pod
3800:
3801: =item * &filecategorytypes()
3802:
3803: returns list of file types belonging to a given file
3804: category
3805:
3806: =cut
3807:
3808: sub filecategorytypes {
3809: my ($cat) = @_;
3810: return @{$category_extensions{lc($cat)}};
3811: }
3812:
3813: =pod
3814:
3815: =item * &fileembstyle()
3816:
3817: returns embedding style for a specified file type
3818:
3819: =cut
3820:
3821: sub fileembstyle {
3822: return $fe{lc(shift(@_))};
3823: }
3824:
3825: sub filemimetype {
3826: return $fm{lc(shift(@_))};
3827: }
3828:
3829:
3830: sub filecategoryselect {
3831: my ($name,$value)=@_;
3832: return &select_form($value,$name,
3833: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3834: }
3835:
3836: =pod
3837:
3838: =item * &filedescription()
3839:
3840: returns description for a specified file type
3841:
3842: =cut
3843:
3844: sub filedescription {
3845: my $file_description = $fd{lc(shift())};
3846: $file_description =~ s:([\[\]]):~$1:g;
3847: return &mt($file_description);
3848: }
3849:
3850: =pod
3851:
3852: =item * &filedescriptionex()
3853:
3854: returns description for a specified file type with
3855: extra formatting
3856:
3857: =cut
3858:
3859: sub filedescriptionex {
3860: my $ex=shift;
3861: my $file_description = $fd{lc($ex)};
3862: $file_description =~ s:([\[\]]):~$1:g;
3863: return '.'.$ex.' '.&mt($file_description);
3864: }
3865:
3866: # End of .tab access
3867: =pod
3868:
3869: =back
3870:
3871: =cut
3872:
3873: # ------------------------------------------------------------------ File Types
3874: sub fileextensions {
3875: return sort(keys(%fe));
3876: }
3877:
3878: # ----------------------------------------------------------- Display Languages
3879: # returns a hash with all desired display languages
3880: #
3881:
3882: sub display_languages {
3883: my %languages=();
3884: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3885: $languages{$lang}=1;
3886: }
3887: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3888: if ($env{'form.displaylanguage'}) {
3889: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3890: $languages{$lang}=1;
3891: }
3892: }
3893: return %languages;
3894: }
3895:
3896: sub languages {
3897: my ($possible_langs) = @_;
3898: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3899: if (!ref($possible_langs)) {
3900: if( wantarray ) {
3901: return @preferred_langs;
3902: } else {
3903: return $preferred_langs[0];
3904: }
3905: }
3906: my %possibilities = map { $_ => 1 } (@$possible_langs);
3907: my @preferred_possibilities;
3908: foreach my $preferred_lang (@preferred_langs) {
3909: if (exists($possibilities{$preferred_lang})) {
3910: push(@preferred_possibilities, $preferred_lang);
3911: }
3912: }
3913: if( wantarray ) {
3914: return @preferred_possibilities;
3915: }
3916: return $preferred_possibilities[0];
3917: }
3918:
3919: sub user_lang {
3920: my ($touname,$toudom,$fromcid) = @_;
3921: my @userlangs;
3922: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3923: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3924: $env{'course.'.$fromcid.'.languages'}));
3925: } else {
3926: my %langhash = &getlangs($touname,$toudom);
3927: if ($langhash{'languages'} ne '') {
3928: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3929: } else {
3930: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3931: if ($domdefs{'lang_def'} ne '') {
3932: @userlangs = ($domdefs{'lang_def'});
3933: }
3934: }
3935: }
3936: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3937: my $user_lh = Apache::localize->get_handle(@languages);
3938: return $user_lh;
3939: }
3940:
3941:
3942: ###############################################################
3943: ## Student Answer Attempts ##
3944: ###############################################################
3945:
3946: =pod
3947:
3948: =head1 Alternate Problem Views
3949:
3950: =over 4
3951:
3952: =item * &get_previous_attempt($symb, $username, $domain, $course,
3953: $getattempt, $regexp, $gradesub, $usec, $identifier)
3954:
3955: Return string with previous attempt on problem. Arguments:
3956:
3957: =over 4
3958:
3959: =item * $symb: Problem, including path
3960:
3961: =item * $username: username of the desired student
3962:
3963: =item * $domain: domain of the desired student
3964:
3965: =item * $course: Course ID
3966:
3967: =item * $getattempt: Leave blank for all attempts, otherwise put
3968: something
3969:
3970: =item * $regexp: if string matches this regexp, the string will be
3971: sent to $gradesub
3972:
3973: =item * $gradesub: routine that processes the string if it matches $regexp
3974:
3975: =item * $usec: section of the desired student
3976:
3977: =item * $identifier: counter for student (multiple students one problem) or
3978: problem (one student; whole sequence).
3979:
3980: =back
3981:
3982: The output string is a table containing all desired attempts, if any.
3983:
3984: =cut
3985:
3986: sub get_previous_attempt {
3987: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
3988: my $prevattempts='';
3989: no strict 'refs';
3990: if ($symb) {
3991: my (%returnhash)=
3992: &Apache::lonnet::restore($symb,$course,$domain,$username);
3993: if ($returnhash{'version'}) {
3994: my %lasthash=();
3995: my $version;
3996: for ($version=1;$version<=$returnhash{'version'};$version++) {
3997: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
3998: if ($key =~ /\.rawrndseed$/) {
3999: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4000: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4001: } else {
4002: $lasthash{$key}=$returnhash{$version.':'.$key};
4003: }
4004: }
4005: }
4006: $prevattempts=&start_data_table().&start_data_table_header_row();
4007: $prevattempts.='<th>'.&mt('History').'</th>';
4008: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4009: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4010: foreach my $key (sort(keys(%lasthash))) {
4011: my ($ign,@parts) = split(/\./,$key);
4012: if ($#parts > 0) {
4013: my $data=$parts[-1];
4014: next if ($data eq 'foilorder');
4015: pop(@parts);
4016: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4017: if ($data eq 'type') {
4018: unless ($showsurv) {
4019: my $id = join(',',@parts);
4020: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4021: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4022: $lasthidden{$ign.'.'.$id} = 1;
4023: }
4024: }
4025: if ($identifier ne '') {
4026: my $id = join(',',@parts);
4027: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4028: $domain,$username,$usec,undef,$course) =~ /^no/) {
4029: $hidestatus{$ign.'.'.$id} = 1;
4030: }
4031: }
4032: } elsif ($data eq 'regrader') {
4033: if (($identifier ne '') && (@parts)) {
4034: my $id = join(',',@parts);
4035: $regraded{$ign.'.'.$id} = 1;
4036: }
4037: }
4038: } else {
4039: if ($#parts == 0) {
4040: $prevattempts.='<th>'.$parts[0].'</th>';
4041: } else {
4042: $prevattempts.='<th>'.$ign.'</th>';
4043: }
4044: }
4045: }
4046: $prevattempts.=&end_data_table_header_row();
4047: if ($getattempt eq '') {
4048: my (%solved,%resets,%probstatus);
4049: if (($identifier ne '') && (keys(%regraded) > 0)) {
4050: for ($version=1;$version<=$returnhash{'version'};$version++) {
4051: foreach my $id (keys(%regraded)) {
4052: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4053: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4054: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4055: push(@{$resets{$id}},$version);
4056: }
4057: }
4058: }
4059: }
4060: for ($version=1;$version<=$returnhash{'version'};$version++) {
4061: my (@hidden,@unsolved);
4062: if (%typeparts) {
4063: foreach my $id (keys(%typeparts)) {
4064: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4065: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4066: push(@hidden,$id);
4067: } elsif ($identifier ne '') {
4068: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4069: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4070: ($hidestatus{$id})) {
4071: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4072: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4073: push(@{$solved{$id}},$version);
4074: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4075: (ref($solved{$id}) eq 'ARRAY')) {
4076: my $skip;
4077: if (ref($resets{$id}) eq 'ARRAY') {
4078: foreach my $reset (@{$resets{$id}}) {
4079: if ($reset > $solved{$id}[-1]) {
4080: $skip=1;
4081: last;
4082: }
4083: }
4084: }
4085: unless ($skip) {
4086: my ($ign,$partslist) = split(/\./,$id,2);
4087: push(@unsolved,$partslist);
4088: }
4089: }
4090: }
4091: }
4092: }
4093: }
4094: $prevattempts.=&start_data_table_row().
4095: '<td>'.&mt('Transaction [_1]',$version);
4096: if (@unsolved) {
4097: $prevattempts .= '<span class="LC_nobreak"><label>'.
4098: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4099: &mt('Hide').'</label></span>';
4100: }
4101: $prevattempts .= '</td>';
4102: if (@hidden) {
4103: foreach my $key (sort(keys(%lasthash))) {
4104: next if ($key =~ /\.foilorder$/);
4105: my $hide;
4106: foreach my $id (@hidden) {
4107: if ($key =~ /^\Q$id\E/) {
4108: $hide = 1;
4109: last;
4110: }
4111: }
4112: if ($hide) {
4113: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4114: if (($data eq 'award') || ($data eq 'awarddetail')) {
4115: my $value = &format_previous_attempt_value($key,
4116: $returnhash{$version.':'.$key});
4117: $prevattempts.='<td>'.$value.' </td>';
4118: } else {
4119: $prevattempts.='<td> </td>';
4120: }
4121: } else {
4122: if ($key =~ /\./) {
4123: my $value = $returnhash{$version.':'.$key};
4124: if ($key =~ /\.rndseed$/) {
4125: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4126: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4127: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4128: }
4129: }
4130: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4131: ' </td>';
4132: } else {
4133: $prevattempts.='<td> </td>';
4134: }
4135: }
4136: }
4137: } else {
4138: foreach my $key (sort(keys(%lasthash))) {
4139: next if ($key =~ /\.foilorder$/);
4140: my $value = $returnhash{$version.':'.$key};
4141: if ($key =~ /\.rndseed$/) {
4142: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4143: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4144: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4145: }
4146: }
4147: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4148: ' </td>';
4149: }
4150: }
4151: $prevattempts.=&end_data_table_row();
4152: }
4153: }
4154: my @currhidden = keys(%lasthidden);
4155: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4156: foreach my $key (sort(keys(%lasthash))) {
4157: next if ($key =~ /\.foilorder$/);
4158: if (%typeparts) {
4159: my $hidden;
4160: foreach my $id (@currhidden) {
4161: if ($key =~ /^\Q$id\E/) {
4162: $hidden = 1;
4163: last;
4164: }
4165: }
4166: if ($hidden) {
4167: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4168: if (($data eq 'award') || ($data eq 'awarddetail')) {
4169: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4170: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4171: $value = &$gradesub($value);
4172: }
4173: $prevattempts.='<td>'.$value.' </td>';
4174: } else {
4175: $prevattempts.='<td> </td>';
4176: }
4177: } else {
4178: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4179: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4180: $value = &$gradesub($value);
4181: }
4182: $prevattempts.='<td>'.$value.' </td>';
4183: }
4184: } else {
4185: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4186: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4187: $value = &$gradesub($value);
4188: }
4189: $prevattempts.='<td>'.$value.' </td>';
4190: }
4191: }
4192: $prevattempts.= &end_data_table_row().&end_data_table();
4193: } else {
4194: $prevattempts=
4195: &start_data_table().&start_data_table_row().
4196: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
4197: &end_data_table_row().&end_data_table();
4198: }
4199: } else {
4200: $prevattempts=
4201: &start_data_table().&start_data_table_row().
4202: '<td>'.&mt('No data.').'</td>'.
4203: &end_data_table_row().&end_data_table();
4204: }
4205: }
4206:
4207: sub format_previous_attempt_value {
4208: my ($key,$value) = @_;
4209: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4210: $value = &Apache::lonlocal::locallocaltime($value);
4211: } elsif (ref($value) eq 'ARRAY') {
4212: $value = '('.join(', ', @{ $value }).')';
4213: } elsif ($key =~ /answerstring$/) {
4214: my %answers = &Apache::lonnet::str2hash($value);
4215: my @anskeys = sort(keys(%answers));
4216: if (@anskeys == 1) {
4217: my $answer = $answers{$anskeys[0]};
4218: if ($answer =~ m{\0}) {
4219: $answer =~ s{\0}{,}g;
4220: }
4221: my $tag_internal_answer_name = 'INTERNAL';
4222: if ($anskeys[0] eq $tag_internal_answer_name) {
4223: $value = $answer;
4224: } else {
4225: $value = $anskeys[0].'='.$answer;
4226: }
4227: } else {
4228: foreach my $ans (@anskeys) {
4229: my $answer = $answers{$ans};
4230: if ($answer =~ m{\0}) {
4231: $answer =~ s{\0}{,}g;
4232: }
4233: $value .= $ans.'='.$answer.'<br />';;
4234: }
4235: }
4236: } else {
4237: $value = &unescape($value);
4238: }
4239: return $value;
4240: }
4241:
4242:
4243: sub relative_to_absolute {
4244: my ($url,$output)=@_;
4245: my $parser=HTML::TokeParser->new(\$output);
4246: my $token;
4247: my $thisdir=$url;
4248: my @rlinks=();
4249: while ($token=$parser->get_token) {
4250: if ($token->[0] eq 'S') {
4251: if ($token->[1] eq 'a') {
4252: if ($token->[2]->{'href'}) {
4253: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4254: }
4255: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4256: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4257: } elsif ($token->[1] eq 'base') {
4258: $thisdir=$token->[2]->{'href'};
4259: }
4260: }
4261: }
4262: $thisdir=~s-/[^/]*$--;
4263: foreach my $link (@rlinks) {
4264: unless (($link=~/^https?\:\/\//i) ||
4265: ($link=~/^\//) ||
4266: ($link=~/^javascript:/i) ||
4267: ($link=~/^mailto:/i) ||
4268: ($link=~/^\#/)) {
4269: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4270: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4271: }
4272: }
4273: # -------------------------------------------------- Deal with Applet codebases
4274: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4275: return $output;
4276: }
4277:
4278: =pod
4279:
4280: =item * &get_student_view()
4281:
4282: show a snapshot of what student was looking at
4283:
4284: =cut
4285:
4286: sub get_student_view {
4287: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4288: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4289: my (%form);
4290: my @elements=('symb','courseid','domain','username');
4291: foreach my $element (@elements) {
4292: $form{'grade_'.$element}=eval '$'.$element #'
4293: }
4294: if (defined($moreenv)) {
4295: %form=(%form,%{$moreenv});
4296: }
4297: if (defined($target)) { $form{'grade_target'} = $target; }
4298: $feedurl=&Apache::lonnet::clutter($feedurl);
4299: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4300: $userview=~s/\<body[^\>]*\>//gi;
4301: $userview=~s/\<\/body\>//gi;
4302: $userview=~s/\<html\>//gi;
4303: $userview=~s/\<\/html\>//gi;
4304: $userview=~s/\<head\>//gi;
4305: $userview=~s/\<\/head\>//gi;
4306: $userview=~s/action\s*\=/would_be_action\=/gi;
4307: $userview=&relative_to_absolute($feedurl,$userview);
4308: if (wantarray) {
4309: return ($userview,$response);
4310: } else {
4311: return $userview;
4312: }
4313: }
4314:
4315: sub get_student_view_with_retries {
4316: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4317:
4318: my $ok = 0; # True if we got a good response.
4319: my $content;
4320: my $response;
4321:
4322: # Try to get the student_view done. within the retries count:
4323:
4324: do {
4325: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4326: $ok = $response->is_success;
4327: if (!$ok) {
4328: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4329: }
4330: $retries--;
4331: } while (!$ok && ($retries > 0));
4332:
4333: if (!$ok) {
4334: $content = ''; # On error return an empty content.
4335: }
4336: if (wantarray) {
4337: return ($content, $response);
4338: } else {
4339: return $content;
4340: }
4341: }
4342:
4343: =pod
4344:
4345: =item * &get_student_answers()
4346:
4347: show a snapshot of how student was answering problem
4348:
4349: =cut
4350:
4351: sub get_student_answers {
4352: my ($symb,$username,$domain,$courseid,%form) = @_;
4353: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4354: my (%moreenv);
4355: my @elements=('symb','courseid','domain','username');
4356: foreach my $element (@elements) {
4357: $moreenv{'grade_'.$element}=eval '$'.$element #'
4358: }
4359: $moreenv{'grade_target'}='answer';
4360: %moreenv=(%form,%moreenv);
4361: $feedurl = &Apache::lonnet::clutter($feedurl);
4362: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4363: return $userview;
4364: }
4365:
4366: =pod
4367:
4368: =item * &submlink()
4369:
4370: Inputs: $text $uname $udom $symb $target
4371:
4372: Returns: A link to grades.pm such as to see the SUBM view of a student
4373:
4374: =cut
4375:
4376: ###############################################
4377: sub submlink {
4378: my ($text,$uname,$udom,$symb,$target)=@_;
4379: if (!($uname && $udom)) {
4380: (my $cursymb, my $courseid,$udom,$uname)=
4381: &Apache::lonnet::whichuser($symb);
4382: if (!$symb) { $symb=$cursymb; }
4383: }
4384: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4385: $symb=&escape($symb);
4386: if ($target) { $target=" target=\"$target\""; }
4387: return
4388: '<a href="/adm/grades?command=submission'.
4389: '&symb='.$symb.
4390: '&student='.$uname.
4391: '&userdom='.$udom.'"'.
4392: $target.'>'.$text.'</a>';
4393: }
4394: ##############################################
4395:
4396: =pod
4397:
4398: =item * &pgrdlink()
4399:
4400: Inputs: $text $uname $udom $symb $target
4401:
4402: Returns: A link to grades.pm such as to see the PGRD view of a student
4403:
4404: =cut
4405:
4406: ###############################################
4407: sub pgrdlink {
4408: my $link=&submlink(@_);
4409: $link=~s/(&command=submission)/$1&showgrading=yes/;
4410: return $link;
4411: }
4412: ##############################################
4413:
4414: =pod
4415:
4416: =item * &pprmlink()
4417:
4418: Inputs: $text $uname $udom $symb $target
4419:
4420: Returns: A link to parmset.pm such as to see the PPRM view of a
4421: student and a specific resource
4422:
4423: =cut
4424:
4425: ###############################################
4426: sub pprmlink {
4427: my ($text,$uname,$udom,$symb,$target)=@_;
4428: if (!($uname && $udom)) {
4429: (my $cursymb, my $courseid,$udom,$uname)=
4430: &Apache::lonnet::whichuser($symb);
4431: if (!$symb) { $symb=$cursymb; }
4432: }
4433: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4434: $symb=&escape($symb);
4435: if ($target) { $target="target=\"$target\""; }
4436: return '<a href="/adm/parmset?command=set&'.
4437: 'symb='.$symb.'&uname='.$uname.
4438: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4439: }
4440: ##############################################
4441:
4442: =pod
4443:
4444: =back
4445:
4446: =cut
4447:
4448: ###############################################
4449:
4450:
4451: sub timehash {
4452: my ($thistime) = @_;
4453: my $timezone = &Apache::lonlocal::gettimezone();
4454: my $dt = DateTime->from_epoch(epoch => $thistime)
4455: ->set_time_zone($timezone);
4456: my $wday = $dt->day_of_week();
4457: if ($wday == 7) { $wday = 0; }
4458: return ( 'second' => $dt->second(),
4459: 'minute' => $dt->minute(),
4460: 'hour' => $dt->hour(),
4461: 'day' => $dt->day_of_month(),
4462: 'month' => $dt->month(),
4463: 'year' => $dt->year(),
4464: 'weekday' => $wday,
4465: 'dayyear' => $dt->day_of_year(),
4466: 'dlsav' => $dt->is_dst() );
4467: }
4468:
4469: sub utc_string {
4470: my ($date)=@_;
4471: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4472: }
4473:
4474: sub maketime {
4475: my %th=@_;
4476: my ($epoch_time,$timezone,$dt);
4477: $timezone = &Apache::lonlocal::gettimezone();
4478: eval {
4479: $dt = DateTime->new( year => $th{'year'},
4480: month => $th{'month'},
4481: day => $th{'day'},
4482: hour => $th{'hour'},
4483: minute => $th{'minute'},
4484: second => $th{'second'},
4485: time_zone => $timezone,
4486: );
4487: };
4488: if (!$@) {
4489: $epoch_time = $dt->epoch;
4490: if ($epoch_time) {
4491: return $epoch_time;
4492: }
4493: }
4494: return POSIX::mktime(
4495: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4496: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4497: }
4498:
4499: #########################################
4500:
4501: sub findallcourses {
4502: my ($roles,$uname,$udom) = @_;
4503: my %roles;
4504: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4505: my %courses;
4506: my $now=time;
4507: if (!defined($uname)) {
4508: $uname = $env{'user.name'};
4509: }
4510: if (!defined($udom)) {
4511: $udom = $env{'user.domain'};
4512: }
4513: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4514: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4515: if (!%roles) {
4516: %roles = (
4517: cc => 1,
4518: co => 1,
4519: in => 1,
4520: ep => 1,
4521: ta => 1,
4522: cr => 1,
4523: st => 1,
4524: );
4525: }
4526: foreach my $entry (keys(%roleshash)) {
4527: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4528: if ($trole =~ /^cr/) {
4529: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4530: } else {
4531: next if (!exists($roles{$trole}));
4532: }
4533: if ($tend) {
4534: next if ($tend < $now);
4535: }
4536: if ($tstart) {
4537: next if ($tstart > $now);
4538: }
4539: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4540: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4541: my $value = $trole.'/'.$cdom.'/';
4542: if ($secpart eq '') {
4543: ($cnum,$role) = split(/_/,$cnumpart);
4544: $sec = 'none';
4545: $value .= $cnum.'/';
4546: } else {
4547: $cnum = $cnumpart;
4548: ($sec,$role) = split(/_/,$secpart);
4549: $value .= $cnum.'/'.$sec;
4550: }
4551: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4552: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4553: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4554: }
4555: } else {
4556: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4557: }
4558: }
4559: } else {
4560: foreach my $key (keys(%env)) {
4561: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4562: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4563: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4564: next if ($role eq 'ca' || $role eq 'aa');
4565: next if (%roles && !exists($roles{$role}));
4566: my ($starttime,$endtime)=split(/\./,$env{$key});
4567: my $active=1;
4568: if ($starttime) {
4569: if ($now<$starttime) { $active=0; }
4570: }
4571: if ($endtime) {
4572: if ($now>$endtime) { $active=0; }
4573: }
4574: if ($active) {
4575: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4576: if ($sec eq '') {
4577: $sec = 'none';
4578: } else {
4579: $value .= $sec;
4580: }
4581: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4582: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4583: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4584: }
4585: } else {
4586: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4587: }
4588: }
4589: }
4590: }
4591: }
4592: return %courses;
4593: }
4594:
4595: ###############################################
4596:
4597: sub blockcheck {
4598: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
4599:
4600: if (defined($udom) && defined($uname)) {
4601: # If uname and udom are for a course, check for blocks in the course.
4602: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4603: my ($startblock,$endblock,$triggerblock) =
4604: &get_blocks($setters,$activity,$udom,$uname,$url);
4605: return ($startblock,$endblock,$triggerblock);
4606: }
4607: } else {
4608: $udom = $env{'user.domain'};
4609: $uname = $env{'user.name'};
4610: }
4611:
4612: my $startblock = 0;
4613: my $endblock = 0;
4614: my $triggerblock = '';
4615: my %live_courses = &findallcourses(undef,$uname,$udom);
4616:
4617: # If uname is for a user, and activity is course-specific, i.e.,
4618: # boards, chat or groups, check for blocking in current course only.
4619:
4620: if (($activity eq 'boards' || $activity eq 'chat' ||
4621: $activity eq 'groups' || $activity eq 'printout') &&
4622: ($env{'request.course.id'})) {
4623: foreach my $key (keys(%live_courses)) {
4624: if ($key ne $env{'request.course.id'}) {
4625: delete($live_courses{$key});
4626: }
4627: }
4628: }
4629:
4630: my $otheruser = 0;
4631: my %own_courses;
4632: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4633: # Resource belongs to user other than current user.
4634: $otheruser = 1;
4635: # Gather courses for current user
4636: %own_courses =
4637: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4638: }
4639:
4640: # Gather active course roles - course coordinator, instructor,
4641: # exam proctor, ta, student, or custom role.
4642:
4643: foreach my $course (keys(%live_courses)) {
4644: my ($cdom,$cnum);
4645: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4646: $cdom = $env{'course.'.$course.'.domain'};
4647: $cnum = $env{'course.'.$course.'.num'};
4648: } else {
4649: ($cdom,$cnum) = split(/_/,$course);
4650: }
4651: my $no_ownblock = 0;
4652: my $no_userblock = 0;
4653: if ($otheruser && $activity ne 'com') {
4654: # Check if current user has 'evb' priv for this
4655: if (defined($own_courses{$course})) {
4656: foreach my $sec (keys(%{$own_courses{$course}})) {
4657: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4658: if ($sec ne 'none') {
4659: $checkrole .= '/'.$sec;
4660: }
4661: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4662: $no_ownblock = 1;
4663: last;
4664: }
4665: }
4666: }
4667: # if they have 'evb' priv and are currently not playing student
4668: next if (($no_ownblock) &&
4669: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4670: }
4671: foreach my $sec (keys(%{$live_courses{$course}})) {
4672: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4673: if ($sec ne 'none') {
4674: $checkrole .= '/'.$sec;
4675: }
4676: if ($otheruser) {
4677: # Resource belongs to user other than current user.
4678: # Assemble privs for that user, and check for 'evb' priv.
4679: my (%allroles,%userroles);
4680: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4681: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4682: my ($trole,$tdom,$tnum,$tsec);
4683: if ($entry =~ /^cr/) {
4684: ($trole,$tdom,$tnum,$tsec) =
4685: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4686: } else {
4687: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4688: }
4689: my ($spec,$area,$trest);
4690: $area = '/'.$tdom.'/'.$tnum;
4691: $trest = $tnum;
4692: if ($tsec ne '') {
4693: $area .= '/'.$tsec;
4694: $trest .= '/'.$tsec;
4695: }
4696: $spec = $trole.'.'.$area;
4697: if ($trole =~ /^cr/) {
4698: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4699: $tdom,$spec,$trest,$area);
4700: } else {
4701: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4702: $tdom,$spec,$trest,$area);
4703: }
4704: }
4705: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4706: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4707: if ($1) {
4708: $no_userblock = 1;
4709: last;
4710: }
4711: }
4712: }
4713: } else {
4714: # Resource belongs to current user
4715: # Check for 'evb' priv via lonnet::allowed().
4716: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4717: $no_ownblock = 1;
4718: last;
4719: }
4720: }
4721: }
4722: # if they have the evb priv and are currently not playing student
4723: next if (($no_ownblock) &&
4724: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4725: next if ($no_userblock);
4726:
4727: # Retrieve blocking times and identity of blocker for course
4728: # of specified user, unless user has 'evb' privilege.
4729:
4730: my ($start,$end,$trigger) =
4731: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4732: if (($start != 0) &&
4733: (($startblock == 0) || ($startblock > $start))) {
4734: $startblock = $start;
4735: if ($trigger ne '') {
4736: $triggerblock = $trigger;
4737: }
4738: }
4739: if (($end != 0) &&
4740: (($endblock == 0) || ($endblock < $end))) {
4741: $endblock = $end;
4742: if ($trigger ne '') {
4743: $triggerblock = $trigger;
4744: }
4745: }
4746: }
4747: return ($startblock,$endblock,$triggerblock);
4748: }
4749:
4750: sub get_blocks {
4751: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4752: my $startblock = 0;
4753: my $endblock = 0;
4754: my $triggerblock = '';
4755: my $course = $cdom.'_'.$cnum;
4756: $setters->{$course} = {};
4757: $setters->{$course}{'staff'} = [];
4758: $setters->{$course}{'times'} = [];
4759: $setters->{$course}{'triggers'} = [];
4760: my (@blockers,%triggered);
4761: my $now = time;
4762: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4763: if ($activity eq 'docs') {
4764: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4765: foreach my $block (@blockers) {
4766: if ($block =~ /^firstaccess____(.+)$/) {
4767: my $item = $1;
4768: my $type = 'map';
4769: my $timersymb = $item;
4770: if ($item eq 'course') {
4771: $type = 'course';
4772: } elsif ($item =~ /___\d+___/) {
4773: $type = 'resource';
4774: } else {
4775: $timersymb = &Apache::lonnet::symbread($item);
4776: }
4777: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4778: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4779: $triggered{$block} = {
4780: start => $start,
4781: end => $end,
4782: type => $type,
4783: };
4784: }
4785: }
4786: } else {
4787: foreach my $block (keys(%commblocks)) {
4788: if ($block =~ m/^(\d+)____(\d+)$/) {
4789: my ($start,$end) = ($1,$2);
4790: if ($start <= time && $end >= time) {
4791: if (ref($commblocks{$block}) eq 'HASH') {
4792: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4793: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4794: unless(grep(/^\Q$block\E$/,@blockers)) {
4795: push(@blockers,$block);
4796: }
4797: }
4798: }
4799: }
4800: }
4801: } elsif ($block =~ /^firstaccess____(.+)$/) {
4802: my $item = $1;
4803: my $timersymb = $item;
4804: my $type = 'map';
4805: if ($item eq 'course') {
4806: $type = 'course';
4807: } elsif ($item =~ /___\d+___/) {
4808: $type = 'resource';
4809: } else {
4810: $timersymb = &Apache::lonnet::symbread($item);
4811: }
4812: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4813: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4814: if ($start && $end) {
4815: if (($start <= time) && ($end >= time)) {
4816: unless (grep(/^\Q$block\E$/,@blockers)) {
4817: push(@blockers,$block);
4818: $triggered{$block} = {
4819: start => $start,
4820: end => $end,
4821: type => $type,
4822: };
4823: }
4824: }
4825: }
4826: }
4827: }
4828: }
4829: foreach my $blocker (@blockers) {
4830: my ($staff_name,$staff_dom,$title,$blocks) =
4831: &parse_block_record($commblocks{$blocker});
4832: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4833: my ($start,$end,$triggertype);
4834: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4835: ($start,$end) = ($1,$2);
4836: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4837: $start = $triggered{$blocker}{'start'};
4838: $end = $triggered{$blocker}{'end'};
4839: $triggertype = $triggered{$blocker}{'type'};
4840: }
4841: if ($start) {
4842: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4843: if ($triggertype) {
4844: push(@{$$setters{$course}{'triggers'}},$triggertype);
4845: } else {
4846: push(@{$$setters{$course}{'triggers'}},0);
4847: }
4848: if ( ($startblock == 0) || ($startblock > $start) ) {
4849: $startblock = $start;
4850: if ($triggertype) {
4851: $triggerblock = $blocker;
4852: }
4853: }
4854: if ( ($endblock == 0) || ($endblock < $end) ) {
4855: $endblock = $end;
4856: if ($triggertype) {
4857: $triggerblock = $blocker;
4858: }
4859: }
4860: }
4861: }
4862: return ($startblock,$endblock,$triggerblock);
4863: }
4864:
4865: sub parse_block_record {
4866: my ($record) = @_;
4867: my ($setuname,$setudom,$title,$blocks);
4868: if (ref($record) eq 'HASH') {
4869: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4870: $title = &unescape($record->{'event'});
4871: $blocks = $record->{'blocks'};
4872: } else {
4873: my @data = split(/:/,$record,3);
4874: if (scalar(@data) eq 2) {
4875: $title = $data[1];
4876: ($setuname,$setudom) = split(/@/,$data[0]);
4877: } else {
4878: ($setuname,$setudom,$title) = @data;
4879: }
4880: $blocks = { 'com' => 'on' };
4881: }
4882: return ($setuname,$setudom,$title,$blocks);
4883: }
4884:
4885: sub blocking_status {
4886: my ($activity,$uname,$udom,$url,$is_course) = @_;
4887: my %setters;
4888:
4889: # check for active blocking
4890: my ($startblock,$endblock,$triggerblock) =
4891: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
4892: my $blocked = 0;
4893: if ($startblock && $endblock) {
4894: $blocked = 1;
4895: }
4896:
4897: # caller just wants to know whether a block is active
4898: if (!wantarray) { return $blocked; }
4899:
4900: # build a link to a popup window containing the details
4901: my $querystring = "?activity=$activity";
4902: # $uname and $udom decide whose portfolio the user is trying to look at
4903: if (($activity eq 'port') || ($activity eq 'passwd')) {
4904: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
4905: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
4906: } elsif ($activity eq 'docs') {
4907: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4908: }
4909:
4910: my $output .= <<'END_MYBLOCK';
4911: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4912: var options = "width=" + w + ",height=" + h + ",";
4913: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4914: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4915: var newWin = window.open(url, wdwName, options);
4916: newWin.focus();
4917: }
4918: END_MYBLOCK
4919:
4920: $output = Apache::lonhtmlcommon::scripttag($output);
4921:
4922: my $popupUrl = "/adm/blockingstatus/$querystring";
4923: my $text = &mt('Communication Blocked');
4924: my $class = 'LC_comblock';
4925: if ($activity eq 'docs') {
4926: $text = &mt('Content Access Blocked');
4927: $class = '';
4928: } elsif ($activity eq 'printout') {
4929: $text = &mt('Printing Blocked');
4930: } elsif ($activity eq 'passwd') {
4931: $text = &mt('Password Changing Blocked');
4932: }
4933: $output .= <<"END_BLOCK";
4934: <div class='$class'>
4935: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4936: title='$text'>
4937: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4938: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4939: title='$text'>$text</a>
4940: </div>
4941:
4942: END_BLOCK
4943:
4944: return ($blocked, $output);
4945: }
4946:
4947: ###############################################
4948:
4949: sub check_ip_acc {
4950: my ($acc,$clientip)=@_;
4951: &Apache::lonxml::debug("acc is $acc");
4952: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4953: return 1;
4954: }
4955: my $allowed=0;
4956: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
4957:
4958: my $name;
4959: foreach my $pattern (split(',',$acc)) {
4960: $pattern =~ s/^\s*//;
4961: $pattern =~ s/\s*$//;
4962: if ($pattern =~ /\*$/) {
4963: #35.8.*
4964: $pattern=~s/\*//;
4965: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4966: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4967: #35.8.3.[34-56]
4968: my $low=$2;
4969: my $high=$3;
4970: $pattern=$1;
4971: if ($ip =~ /^\Q$pattern\E/) {
4972: my $last=(split(/\./,$ip))[3];
4973: if ($last <=$high && $last >=$low) { $allowed=1; }
4974: }
4975: } elsif ($pattern =~ /^\*/) {
4976: #*.msu.edu
4977: $pattern=~s/\*//;
4978: if (!defined($name)) {
4979: use Socket;
4980: my $netaddr=inet_aton($ip);
4981: ($name)=gethostbyaddr($netaddr,AF_INET);
4982: }
4983: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4984: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4985: #127.0.0.1
4986: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4987: } else {
4988: #some.name.com
4989: if (!defined($name)) {
4990: use Socket;
4991: my $netaddr=inet_aton($ip);
4992: ($name)=gethostbyaddr($netaddr,AF_INET);
4993: }
4994: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4995: }
4996: if ($allowed) { last; }
4997: }
4998: return $allowed;
4999: }
5000:
5001: ###############################################
5002:
5003: =pod
5004:
5005: =head1 Domain Template Functions
5006:
5007: =over 4
5008:
5009: =item * &determinedomain()
5010:
5011: Inputs: $domain (usually will be undef)
5012:
5013: Returns: Determines which domain should be used for designs
5014:
5015: =cut
5016:
5017: ###############################################
5018: sub determinedomain {
5019: my $domain=shift;
5020: if (! $domain) {
5021: # Determine domain if we have not been given one
5022: $domain = &Apache::lonnet::default_login_domain();
5023: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5024: if ($env{'request.role.domain'}) {
5025: $domain=$env{'request.role.domain'};
5026: }
5027: }
5028: return $domain;
5029: }
5030: ###############################################
5031:
5032: sub devalidate_domconfig_cache {
5033: my ($udom)=@_;
5034: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5035: }
5036:
5037: # ---------------------- Get domain configuration for a domain
5038: sub get_domainconf {
5039: my ($udom) = @_;
5040: my $cachetime=1800;
5041: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5042: if (defined($cached)) { return %{$result}; }
5043:
5044: my %domconfig = &Apache::lonnet::get_dom('configuration',
5045: ['login','rolecolors','autoenroll'],$udom);
5046: my (%designhash,%legacy);
5047: if (keys(%domconfig) > 0) {
5048: if (ref($domconfig{'login'}) eq 'HASH') {
5049: if (keys(%{$domconfig{'login'}})) {
5050: foreach my $key (keys(%{$domconfig{'login'}})) {
5051: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5052: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5053: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5054: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5055: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5056: if ($key eq 'loginvia') {
5057: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5058: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5059: $designhash{$udom.'.login.loginvia'} = $server;
5060: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5061: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5062: } else {
5063: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5064: }
5065: }
5066: } elsif ($key eq 'headtag') {
5067: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5068: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5069: }
5070: }
5071: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5072: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5073: }
5074: }
5075: }
5076: }
5077: } else {
5078: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5079: $designhash{$udom.'.login.'.$key.'_'.$img} =
5080: $domconfig{'login'}{$key}{$img};
5081: }
5082: }
5083: } else {
5084: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5085: }
5086: }
5087: } else {
5088: $legacy{'login'} = 1;
5089: }
5090: } else {
5091: $legacy{'login'} = 1;
5092: }
5093: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5094: if (keys(%{$domconfig{'rolecolors'}})) {
5095: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5096: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5097: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5098: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5099: }
5100: }
5101: }
5102: } else {
5103: $legacy{'rolecolors'} = 1;
5104: }
5105: } else {
5106: $legacy{'rolecolors'} = 1;
5107: }
5108: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5109: if ($domconfig{'autoenroll'}{'co-owners'}) {
5110: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5111: }
5112: }
5113: if (keys(%legacy) > 0) {
5114: my %legacyhash = &get_legacy_domconf($udom);
5115: foreach my $item (keys(%legacyhash)) {
5116: if ($item =~ /^\Q$udom\E\.login/) {
5117: if ($legacy{'login'}) {
5118: $designhash{$item} = $legacyhash{$item};
5119: }
5120: } else {
5121: if ($legacy{'rolecolors'}) {
5122: $designhash{$item} = $legacyhash{$item};
5123: }
5124: }
5125: }
5126: }
5127: } else {
5128: %designhash = &get_legacy_domconf($udom);
5129: }
5130: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5131: $cachetime);
5132: return %designhash;
5133: }
5134:
5135: sub get_legacy_domconf {
5136: my ($udom) = @_;
5137: my %legacyhash;
5138: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5139: my $designfile = $designdir.'/'.$udom.'.tab';
5140: if (-e $designfile) {
5141: if ( open (my $fh,'<',$designfile) ) {
5142: while (my $line = <$fh>) {
5143: next if ($line =~ /^\#/);
5144: chomp($line);
5145: my ($key,$val)=(split(/\=/,$line));
5146: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5147: }
5148: close($fh);
5149: }
5150: }
5151: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5152: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5153: }
5154: return %legacyhash;
5155: }
5156:
5157: =pod
5158:
5159: =item * &domainlogo()
5160:
5161: Inputs: $domain (usually will be undef)
5162:
5163: Returns: A link to a domain logo, if the domain logo exists.
5164: If the domain logo does not exist, a description of the domain.
5165:
5166: =cut
5167:
5168: ###############################################
5169: sub domainlogo {
5170: my $domain = &determinedomain(shift);
5171: my %designhash = &get_domainconf($domain);
5172: # See if there is a logo
5173: if ($designhash{$domain.'.login.domlogo'} ne '') {
5174: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5175: if ($imgsrc =~ m{^/(adm|res)/}) {
5176: if ($imgsrc =~ m{^/res/}) {
5177: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5178: &Apache::lonnet::repcopy($local_name);
5179: }
5180: $imgsrc = &lonhttpdurl($imgsrc);
5181: }
5182: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5183: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5184: return &Apache::lonnet::domain($domain,'description');
5185: } else {
5186: return '';
5187: }
5188: }
5189: ##############################################
5190:
5191: =pod
5192:
5193: =item * &designparm()
5194:
5195: Inputs: $which parameter; $domain (usually will be undef)
5196:
5197: Returns: value of designparamter $which
5198:
5199: =cut
5200:
5201:
5202: ##############################################
5203: sub designparm {
5204: my ($which,$domain)=@_;
5205: if (exists($env{'environment.color.'.$which})) {
5206: return $env{'environment.color.'.$which};
5207: }
5208: $domain=&determinedomain($domain);
5209: my %domdesign;
5210: unless ($domain eq 'public') {
5211: %domdesign = &get_domainconf($domain);
5212: }
5213: my $output;
5214: if ($domdesign{$domain.'.'.$which} ne '') {
5215: $output = $domdesign{$domain.'.'.$which};
5216: } else {
5217: $output = $defaultdesign{$which};
5218: }
5219: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5220: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5221: if ($output =~ m{^/(adm|res)/}) {
5222: if ($output =~ m{^/res/}) {
5223: my $local_name = &Apache::lonnet::filelocation('',$output);
5224: &Apache::lonnet::repcopy($local_name);
5225: }
5226: $output = &lonhttpdurl($output);
5227: }
5228: }
5229: return $output;
5230: }
5231:
5232: ##############################################
5233: =pod
5234:
5235: =item * &authorspace()
5236:
5237: Inputs: $url (usually will be undef).
5238:
5239: Returns: Path to Authoring Space containing the resource or
5240: directory being viewed (or for which action is being taken).
5241: If $url is provided, and begins /priv/<domain>/<uname>
5242: the path will be that portion of the $context argument.
5243: Otherwise the path will be for the author space of the current
5244: user when the current role is author, or for that of the
5245: co-author/assistant co-author space when the current role
5246: is co-author or assistant co-author.
5247:
5248: =cut
5249:
5250: sub authorspace {
5251: my ($url) = @_;
5252: if ($url ne '') {
5253: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5254: return $1;
5255: }
5256: }
5257: my $caname = '';
5258: my $cadom = '';
5259: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5260: ($cadom,$caname) =
5261: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5262: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5263: $caname = $env{'user.name'};
5264: $cadom = $env{'user.domain'};
5265: }
5266: if (($caname ne '') && ($cadom ne '')) {
5267: return "/priv/$cadom/$caname/";
5268: }
5269: return;
5270: }
5271:
5272: ##############################################
5273: =pod
5274:
5275: =item * &head_subbox()
5276:
5277: Inputs: $content (contains HTML code with page functions, etc.)
5278:
5279: Returns: HTML div with $content
5280: To be included in page header
5281:
5282: =cut
5283:
5284: sub head_subbox {
5285: my ($content)=@_;
5286: my $output =
5287: '<div class="LC_head_subbox">'
5288: .$content
5289: .'</div>'
5290: }
5291:
5292: ##############################################
5293: =pod
5294:
5295: =item * &CSTR_pageheader()
5296:
5297: Input: (optional) filename from which breadcrumb trail is built.
5298: In most cases no input as needed, as $env{'request.filename'}
5299: is appropriate for use in building the breadcrumb trail.
5300:
5301: Returns: HTML div with CSTR path and recent box
5302: To be included on Authoring Space pages
5303:
5304: =cut
5305:
5306: sub CSTR_pageheader {
5307: my ($trailfile) = @_;
5308: if ($trailfile eq '') {
5309: $trailfile = $env{'request.filename'};
5310: }
5311:
5312: # this is for resources; directories have customtitle, and crumbs
5313: # and select recent are created in lonpubdir.pm
5314:
5315: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5316: my ($udom,$uname,$thisdisfn)=
5317: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5318: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5319: $formaction =~ s{/+}{/}g;
5320:
5321: my $parentpath = '';
5322: my $lastitem = '';
5323: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5324: $parentpath = $1;
5325: $lastitem = $2;
5326: } else {
5327: $lastitem = $thisdisfn;
5328: }
5329:
5330: my $output =
5331: '<div>'
5332: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5333: .'<b>'.&mt('Authoring Space:').'</b> '
5334: .'<form name="dirs" method="post" action="'.$formaction
5335: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5336: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5337:
5338: if ($lastitem) {
5339: $output .=
5340: '<span class="LC_filename">'
5341: .$lastitem
5342: .'</span>';
5343: }
5344: $output .=
5345: '<br />'
5346: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5347: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5348: .'</form>'
5349: .&Apache::lonmenu::constspaceform()
5350: .'</div>';
5351:
5352: return $output;
5353: }
5354:
5355: ###############################################
5356: ###############################################
5357:
5358: =pod
5359:
5360: =back
5361:
5362: =head1 HTML Helpers
5363:
5364: =over 4
5365:
5366: =item * &bodytag()
5367:
5368: Returns a uniform header for LON-CAPA web pages.
5369:
5370: Inputs:
5371:
5372: =over 4
5373:
5374: =item * $title, A title to be displayed on the page.
5375:
5376: =item * $function, the current role (can be undef).
5377:
5378: =item * $addentries, extra parameters for the <body> tag.
5379:
5380: =item * $bodyonly, if defined, only return the <body> tag.
5381:
5382: =item * $domain, if defined, force a given domain.
5383:
5384: =item * $forcereg, if page should register as content page (relevant for
5385: text interface only)
5386:
5387: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5388: navigational links
5389:
5390: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5391:
5392: =item * $no_inline_link, if true and in remote mode, don't show the
5393: 'Switch To Inline Menu' link
5394:
5395: =item * $args, optional argument valid values are
5396: no_auto_mt_title -> prevents &mt()ing the title arg
5397: use_absolute -> for external resource or syllabus, this will
5398: contain https://<hostname> if server uses
5399: https (as per hosts.tab), but request is for http
5400: hostname -> hostname, from $r->hostname().
5401:
5402: =item * $advtoolsref, optional argument, ref to an array containing
5403: inlineremote items to be added in "Functions" menu below
5404: breadcrumbs.
5405:
5406: =back
5407:
5408: Returns: A uniform header for LON-CAPA web pages.
5409: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5410: If $bodyonly is undef or zero, an html string containing a <body> tag and
5411: other decorations will be returned.
5412:
5413: =cut
5414:
5415: sub bodytag {
5416: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5417: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
5418:
5419: my $public;
5420: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5421: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5422: $public = 1;
5423: }
5424: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5425: my $httphost = $args->{'use_absolute'};
5426: my $hostname = $args->{'hostname'};
5427:
5428: $function = &get_users_function() if (!$function);
5429: my $img = &designparm($function.'.img',$domain);
5430: my $font = &designparm($function.'.font',$domain);
5431: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5432:
5433: my %design = ( 'style' => 'margin-top: 0',
5434: 'bgcolor' => $pgbg,
5435: 'text' => $font,
5436: 'alink' => &designparm($function.'.alink',$domain),
5437: 'vlink' => &designparm($function.'.vlink',$domain),
5438: 'link' => &designparm($function.'.link',$domain),);
5439: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5440:
5441: # role and realm
5442: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5443: if ($realm) {
5444: $realm = '/'.$realm;
5445: }
5446: if ($role eq 'ca') {
5447: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5448: $realm = &plainname($rname,$rdom);
5449: }
5450: # realm
5451: if ($env{'request.course.id'}) {
5452: if ($env{'request.role'} !~ /^cr/) {
5453: $role = &Apache::lonnet::plaintext($role,&course_type());
5454: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
5455: if ($env{'request.role.desc'}) {
5456: $role = $env{'request.role.desc'};
5457: } else {
5458: $role = &mt('Helpdesk[_1]',' '.$2);
5459: }
5460: } else {
5461: $role = (split(/\//,$role,4))[-1];
5462: }
5463: if ($env{'request.course.sec'}) {
5464: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5465: }
5466: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5467: } else {
5468: $role = &Apache::lonnet::plaintext($role);
5469: }
5470:
5471: if (!$realm) { $realm=' '; }
5472:
5473: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5474:
5475: # construct main body tag
5476: my $bodytag = "<body $extra_body_attr>".
5477: &Apache::lontexconvert::init_math_support();
5478:
5479: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5480:
5481: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5482: return $bodytag;
5483: }
5484:
5485: if ($public) {
5486: undef($role);
5487: }
5488:
5489: my $titleinfo = '<h1>'.$title.'</h1>';
5490: #
5491: # Extra info if you are the DC
5492: my $dc_info = '';
5493: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5494: $env{'course.'.$env{'request.course.id'}.
5495: '.domain'}.'/'})) {
5496: my $cid = $env{'request.course.id'};
5497: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5498: $dc_info =~ s/\s+$//;
5499: }
5500:
5501: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
5502:
5503: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5504:
5505:
5506:
5507: my $funclist;
5508: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
5509: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
5510: Apache::lonmenu::serverform();
5511: my $forbodytag;
5512: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5513: $forcereg,$args->{'group'},
5514: $args->{'bread_crumbs'},
5515: $advtoolsref,'','',\$forbodytag);
5516: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5517: $funclist = $forbodytag;
5518: }
5519: } else {
5520:
5521: # if ($env{'request.state'} eq 'construct') {
5522: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5523: # }
5524:
5525: $bodytag .= Apache::lonhtmlcommon::scripttag(
5526: Apache::lonmenu::utilityfunctions($httphost), 'start');
5527:
5528: my ($left,$right) = Apache::lonmenu::primary_menu();
5529:
5530: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5531: if ($dc_info) {
5532: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5533: }
5534: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5535: <em>$realm</em> $dc_info</div>|;
5536: return $bodytag;
5537: }
5538:
5539: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5540: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5541: }
5542:
5543: $bodytag .= $right;
5544:
5545: if ($dc_info) {
5546: $dc_info = &dc_courseid_toggle($dc_info);
5547: }
5548: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5549:
5550: #if directed to not display the secondary menu, don't.
5551: if ($args->{'no_secondary_menu'}) {
5552: return $bodytag;
5553: }
5554: #don't show menus for public users
5555: if (!$public){
5556: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5557: $bodytag .= Apache::lonmenu::serverform();
5558: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5559: if ($env{'request.state'} eq 'construct') {
5560: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5561: $args->{'bread_crumbs'},'','',$hostname);
5562: } elsif ($forcereg) {
5563: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5564: $args->{'group'},
5565: $args->{'hide_buttons',
5566: $hostname});
5567: } else {
5568: my $forbodytag;
5569: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5570: $forcereg,$args->{'group'},
5571: $args->{'bread_crumbs'},
5572: $advtoolsref,'',$hostname,
5573: \$forbodytag);
5574: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5575: $bodytag .= $forbodytag;
5576: }
5577: }
5578: }else{
5579: # this is to seperate menu from content when there's no secondary
5580: # menu. Especially needed for public accessible ressources.
5581: $bodytag .= '<hr style="clear:both" />';
5582: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5583: }
5584:
5585: return $bodytag;
5586: }
5587:
5588: #
5589: # Top frame rendering, Remote is up
5590: #
5591:
5592: my $imgsrc = $img;
5593: if ($img =~ /^\/adm/) {
5594: $imgsrc = &lonhttpdurl($img);
5595: }
5596: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
5597:
5598: my $help=($no_inline_link?''
5599: :&Apache::loncommon::top_nav_help('Help'));
5600:
5601: # Explicit link to get inline menu
5602: my $menu= ($no_inline_link?''
5603: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
5604:
5605: if ($dc_info) {
5606: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
5607: }
5608:
5609: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5610: unless ($public) {
5611: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5612: undef,'LC_menubuttons_link');
5613: }
5614:
5615: unless ($env{'form.inhibitmenu'}) {
5616: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
5617: <ol class="LC_primary_menu LC_floatright LC_right">
5618: <li>$help</li>
5619: <li>$menu</li>
5620: </ol><div id="LC_realm"> $realm $dc_info</div>|;
5621: }
5622: if ($env{'request.state'} eq 'construct') {
5623: if (!$public){
5624: if ($env{'request.state'} eq 'construct') {
5625: $funclist = &Apache::lonhtmlcommon::scripttag(
5626: &Apache::lonmenu::utilityfunctions($httphost), 'start').
5627: &Apache::lonhtmlcommon::scripttag('','end').
5628: &Apache::lonmenu::innerregister($forcereg,
5629: $args->{'bread_crumbs'});
5630: }
5631: }
5632: }
5633: return $bodytag."\n".$funclist;
5634: }
5635:
5636: sub dc_courseid_toggle {
5637: my ($dc_info) = @_;
5638: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5639: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5640: &mt('(More ...)').'</a></span>'.
5641: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5642: }
5643:
5644: sub make_attr_string {
5645: my ($register,$attr_ref) = @_;
5646:
5647: if ($attr_ref && !ref($attr_ref)) {
5648: die("addentries Must be a hash ref ".
5649: join(':',caller(1))." ".
5650: join(':',caller(0))." ");
5651: }
5652:
5653: if ($register) {
5654: my ($on_load,$on_unload);
5655: foreach my $key (keys(%{$attr_ref})) {
5656: if (lc($key) eq 'onload') {
5657: $on_load.=$attr_ref->{$key}.';';
5658: delete($attr_ref->{$key});
5659:
5660: } elsif (lc($key) eq 'onunload') {
5661: $on_unload.=$attr_ref->{$key}.';';
5662: delete($attr_ref->{$key});
5663: }
5664: }
5665: if ($env{'environment.remote'} eq 'on') {
5666: $attr_ref->{'onload'} =
5667: &Apache::lonmenu::loadevents(). $on_load;
5668: $attr_ref->{'onunload'}=
5669: &Apache::lonmenu::unloadevents().$on_unload;
5670: } else {
5671: $attr_ref->{'onload'} = $on_load;
5672: $attr_ref->{'onunload'}= $on_unload;
5673: }
5674: }
5675:
5676: my $attr_string;
5677: foreach my $attr (sort(keys(%$attr_ref))) {
5678: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5679: }
5680: return $attr_string;
5681: }
5682:
5683:
5684: ###############################################
5685: ###############################################
5686:
5687: =pod
5688:
5689: =item * &endbodytag()
5690:
5691: Returns a uniform footer for LON-CAPA web pages.
5692:
5693: Inputs: 1 - optional reference to an args hash
5694: If in the hash, key for noredirectlink has a value which evaluates to true,
5695: a 'Continue' link is not displayed if the page contains an
5696: internal redirect in the <head></head> section,
5697: i.e., $env{'internal.head.redirect'} exists
5698:
5699: =cut
5700:
5701: sub endbodytag {
5702: my ($args) = @_;
5703: my $endbodytag;
5704: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5705: $endbodytag='</body>';
5706: }
5707: if ( exists( $env{'internal.head.redirect'} ) ) {
5708: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5709: $endbodytag=
5710: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5711: &mt('Continue').'</a>'.
5712: $endbodytag;
5713: }
5714: }
5715: return $endbodytag;
5716: }
5717:
5718: =pod
5719:
5720: =item * &standard_css()
5721:
5722: Returns a style sheet
5723:
5724: Inputs: (all optional)
5725: domain -> force to color decorate a page for a specific
5726: domain
5727: function -> force usage of a specific rolish color scheme
5728: bgcolor -> override the default page bgcolor
5729:
5730: =cut
5731:
5732: sub standard_css {
5733: my ($function,$domain,$bgcolor) = @_;
5734: $function = &get_users_function() if (!$function);
5735: my $img = &designparm($function.'.img', $domain);
5736: my $tabbg = &designparm($function.'.tabbg', $domain);
5737: my $font = &designparm($function.'.font', $domain);
5738: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5739: #second colour for later usage
5740: my $sidebg = &designparm($function.'.sidebg',$domain);
5741: my $pgbg_or_bgcolor =
5742: $bgcolor ||
5743: &designparm($function.'.pgbg', $domain);
5744: my $pgbg = &designparm($function.'.pgbg', $domain);
5745: my $alink = &designparm($function.'.alink', $domain);
5746: my $vlink = &designparm($function.'.vlink', $domain);
5747: my $link = &designparm($function.'.link', $domain);
5748:
5749: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5750: my $mono = 'monospace';
5751: my $data_table_head = $sidebg;
5752: my $data_table_light = '#FAFAFA';
5753: my $data_table_dark = '#E0E0E0';
5754: my $data_table_darker = '#CCCCCC';
5755: my $data_table_highlight = '#FFFF00';
5756: my $mail_new = '#FFBB77';
5757: my $mail_new_hover = '#DD9955';
5758: my $mail_read = '#BBBB77';
5759: my $mail_read_hover = '#999944';
5760: my $mail_replied = '#AAAA88';
5761: my $mail_replied_hover = '#888855';
5762: my $mail_other = '#99BBBB';
5763: my $mail_other_hover = '#669999';
5764: my $table_header = '#DDDDDD';
5765: my $feedback_link_bg = '#BBBBBB';
5766: my $lg_border_color = '#C8C8C8';
5767: my $button_hover = '#BF2317';
5768:
5769: my $border = ($env{'browser.type'} eq 'explorer' ||
5770: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5771: : '0 3px 0 4px';
5772:
5773:
5774: return <<END;
5775:
5776: /* needed for iframe to allow 100% height in FF */
5777: body, html {
5778: margin: 0;
5779: padding: 0 0.5%;
5780: height: 99%; /* to avoid scrollbars */
5781: }
5782:
5783: body {
5784: font-family: $sans;
5785: line-height:130%;
5786: font-size:0.83em;
5787: color:$font;
5788: }
5789:
5790: a:focus,
5791: a:focus img {
5792: color: red;
5793: }
5794:
5795: form, .inline {
5796: display: inline;
5797: }
5798:
5799: .LC_right {
5800: text-align:right;
5801: }
5802:
5803: .LC_middle {
5804: vertical-align:middle;
5805: }
5806:
5807: .LC_floatleft {
5808: float: left;
5809: }
5810:
5811: .LC_floatright {
5812: float: right;
5813: }
5814:
5815: .LC_400Box {
5816: width:400px;
5817: }
5818:
5819: .LC_iframecontainer {
5820: width: 98%;
5821: margin: 0;
5822: position: fixed;
5823: top: 8.5em;
5824: bottom: 0;
5825: }
5826:
5827: .LC_iframecontainer iframe{
5828: border: none;
5829: width: 100%;
5830: height: 100%;
5831: }
5832:
5833: .LC_filename {
5834: font-family: $mono;
5835: white-space:pre;
5836: font-size: 120%;
5837: }
5838:
5839: .LC_fileicon {
5840: border: none;
5841: height: 1.3em;
5842: vertical-align: text-bottom;
5843: margin-right: 0.3em;
5844: text-decoration:none;
5845: }
5846:
5847: .LC_setting {
5848: text-decoration:underline;
5849: }
5850:
5851: .LC_error {
5852: color: red;
5853: }
5854:
5855: .LC_warning {
5856: color: darkorange;
5857: }
5858:
5859: .LC_diff_removed {
5860: color: red;
5861: }
5862:
5863: .LC_info,
5864: .LC_success,
5865: .LC_diff_added {
5866: color: green;
5867: }
5868:
5869: div.LC_confirm_box {
5870: background-color: #FAFAFA;
5871: border: 1px solid $lg_border_color;
5872: margin-right: 0;
5873: padding: 5px;
5874: }
5875:
5876: div.LC_confirm_box .LC_error img,
5877: div.LC_confirm_box .LC_success img {
5878: vertical-align: middle;
5879: }
5880:
5881: .LC_maxwidth {
5882: max-width: 100%;
5883: height: auto;
5884: }
5885:
5886: .LC_textsize_mobile {
5887: \@media only screen and (max-device-width: 480px) {
5888: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
5889: }
5890: }
5891:
5892: .LC_icon {
5893: border: none;
5894: vertical-align: middle;
5895: }
5896:
5897: .LC_docs_spacer {
5898: width: 25px;
5899: height: 1px;
5900: border: none;
5901: }
5902:
5903: .LC_internal_info {
5904: color: #999999;
5905: }
5906:
5907: .LC_discussion {
5908: background: $data_table_dark;
5909: border: 1px solid black;
5910: margin: 2px;
5911: }
5912:
5913: .LC_disc_action_left {
5914: background: $sidebg;
5915: text-align: left;
5916: padding: 4px;
5917: margin: 2px;
5918: }
5919:
5920: .LC_disc_action_right {
5921: background: $sidebg;
5922: text-align: right;
5923: padding: 4px;
5924: margin: 2px;
5925: }
5926:
5927: .LC_disc_new_item {
5928: background: white;
5929: border: 2px solid red;
5930: margin: 4px;
5931: padding: 4px;
5932: }
5933:
5934: .LC_disc_old_item {
5935: background: white;
5936: margin: 4px;
5937: padding: 4px;
5938: }
5939:
5940: table.LC_pastsubmission {
5941: border: 1px solid black;
5942: margin: 2px;
5943: }
5944:
5945: table#LC_menubuttons {
5946: width: 100%;
5947: background: $pgbg;
5948: border: 2px;
5949: border-collapse: separate;
5950: padding: 0;
5951: }
5952:
5953: table#LC_title_bar a {
5954: color: $fontmenu;
5955: }
5956:
5957: table#LC_title_bar {
5958: clear: both;
5959: display: none;
5960: }
5961:
5962: table#LC_title_bar,
5963: table.LC_breadcrumbs, /* obsolete? */
5964: table#LC_title_bar.LC_with_remote {
5965: width: 100%;
5966: border-color: $pgbg;
5967: border-style: solid;
5968: border-width: $border;
5969: background: $pgbg;
5970: color: $fontmenu;
5971: border-collapse: collapse;
5972: padding: 0;
5973: margin: 0;
5974: }
5975:
5976: ul.LC_breadcrumb_tools_outerlist {
5977: margin: 0;
5978: padding: 0;
5979: position: relative;
5980: list-style: none;
5981: }
5982: ul.LC_breadcrumb_tools_outerlist li {
5983: display: inline;
5984: }
5985:
5986: .LC_breadcrumb_tools_navigation {
5987: padding: 0;
5988: margin: 0;
5989: float: left;
5990: }
5991: .LC_breadcrumb_tools_tools {
5992: padding: 0;
5993: margin: 0;
5994: float: right;
5995: }
5996:
5997: table#LC_title_bar td {
5998: background: $tabbg;
5999: }
6000:
6001: table#LC_menubuttons img {
6002: border: none;
6003: }
6004:
6005: .LC_breadcrumbs_component {
6006: float: right;
6007: margin: 0 1em;
6008: }
6009: .LC_breadcrumbs_component img {
6010: vertical-align: middle;
6011: }
6012:
6013: .LC_breadcrumbs_hoverable {
6014: background: $sidebg;
6015: }
6016:
6017: td.LC_table_cell_checkbox {
6018: text-align: center;
6019: }
6020:
6021: .LC_fontsize_small {
6022: font-size: 70%;
6023: }
6024:
6025: #LC_breadcrumbs {
6026: clear:both;
6027: background: $sidebg;
6028: border-bottom: 1px solid $lg_border_color;
6029: line-height: 2.5em;
6030: overflow: hidden;
6031: margin: 0;
6032: padding: 0;
6033: text-align: left;
6034: }
6035:
6036: .LC_head_subbox, .LC_actionbox {
6037: clear:both;
6038: background: #F8F8F8; /* $sidebg; */
6039: border: 1px solid $sidebg;
6040: margin: 0 0 10px 0;
6041: padding: 3px;
6042: text-align: left;
6043: }
6044:
6045: .LC_fontsize_medium {
6046: font-size: 85%;
6047: }
6048:
6049: .LC_fontsize_large {
6050: font-size: 120%;
6051: }
6052:
6053: .LC_menubuttons_inline_text {
6054: color: $font;
6055: font-size: 90%;
6056: padding-left:3px;
6057: }
6058:
6059: .LC_menubuttons_inline_text img{
6060: vertical-align: middle;
6061: }
6062:
6063: li.LC_menubuttons_inline_text img {
6064: cursor:pointer;
6065: text-decoration: none;
6066: }
6067:
6068: .LC_menubuttons_link {
6069: text-decoration: none;
6070: }
6071:
6072: .LC_menubuttons_category {
6073: color: $font;
6074: background: $pgbg;
6075: font-size: larger;
6076: font-weight: bold;
6077: }
6078:
6079: td.LC_menubuttons_text {
6080: color: $font;
6081: }
6082:
6083: .LC_current_location {
6084: background: $tabbg;
6085: }
6086:
6087: td.LC_zero_height {
6088: line-height: 0;
6089: cellpadding: 0;
6090: }
6091:
6092: table.LC_data_table {
6093: border: 1px solid #000000;
6094: border-collapse: separate;
6095: border-spacing: 1px;
6096: background: $pgbg;
6097: }
6098:
6099: .LC_data_table_dense {
6100: font-size: small;
6101: }
6102:
6103: table.LC_nested_outer {
6104: border: 1px solid #000000;
6105: border-collapse: collapse;
6106: border-spacing: 0;
6107: width: 100%;
6108: }
6109:
6110: table.LC_innerpickbox,
6111: table.LC_nested {
6112: border: none;
6113: border-collapse: collapse;
6114: border-spacing: 0;
6115: width: 100%;
6116: }
6117:
6118: table.LC_data_table tr th,
6119: table.LC_calendar tr th,
6120: table.LC_prior_tries tr th,
6121: table.LC_innerpickbox tr th {
6122: font-weight: bold;
6123: background-color: $data_table_head;
6124: color:$fontmenu;
6125: font-size:90%;
6126: }
6127:
6128: table.LC_innerpickbox tr th,
6129: table.LC_innerpickbox tr td {
6130: vertical-align: top;
6131: }
6132:
6133: table.LC_data_table tr.LC_info_row > td {
6134: background-color: #CCCCCC;
6135: font-weight: bold;
6136: text-align: left;
6137: }
6138:
6139: table.LC_data_table tr.LC_odd_row > td {
6140: background-color: $data_table_light;
6141: padding: 2px;
6142: vertical-align: top;
6143: }
6144:
6145: table.LC_pick_box tr > td.LC_odd_row {
6146: background-color: $data_table_light;
6147: vertical-align: top;
6148: }
6149:
6150: table.LC_data_table tr.LC_even_row > td {
6151: background-color: $data_table_dark;
6152: padding: 2px;
6153: vertical-align: top;
6154: }
6155:
6156: table.LC_pick_box tr > td.LC_even_row {
6157: background-color: $data_table_dark;
6158: vertical-align: top;
6159: }
6160:
6161: table.LC_data_table tr.LC_data_table_highlight td {
6162: background-color: $data_table_darker;
6163: }
6164:
6165: table.LC_data_table tr td.LC_leftcol_header {
6166: background-color: $data_table_head;
6167: font-weight: bold;
6168: }
6169:
6170: table.LC_data_table tr.LC_empty_row td,
6171: table.LC_nested tr.LC_empty_row td {
6172: font-weight: bold;
6173: font-style: italic;
6174: text-align: center;
6175: padding: 8px;
6176: }
6177:
6178: table.LC_data_table tr.LC_empty_row td,
6179: table.LC_data_table tr.LC_footer_row td {
6180: background-color: $sidebg;
6181: }
6182:
6183: table.LC_nested tr.LC_empty_row td {
6184: background-color: #FFFFFF;
6185: }
6186:
6187: table.LC_caption {
6188: }
6189:
6190: table.LC_nested tr.LC_empty_row td {
6191: padding: 4ex
6192: }
6193:
6194: table.LC_nested_outer tr th {
6195: font-weight: bold;
6196: color:$fontmenu;
6197: background-color: $data_table_head;
6198: font-size: small;
6199: border-bottom: 1px solid #000000;
6200: }
6201:
6202: table.LC_nested_outer tr td.LC_subheader {
6203: background-color: $data_table_head;
6204: font-weight: bold;
6205: font-size: small;
6206: border-bottom: 1px solid #000000;
6207: text-align: right;
6208: }
6209:
6210: table.LC_nested tr.LC_info_row td {
6211: background-color: #CCCCCC;
6212: font-weight: bold;
6213: font-size: small;
6214: text-align: center;
6215: }
6216:
6217: table.LC_nested tr.LC_info_row td.LC_left_item,
6218: table.LC_nested_outer tr th.LC_left_item {
6219: text-align: left;
6220: }
6221:
6222: table.LC_nested td {
6223: background-color: #FFFFFF;
6224: font-size: small;
6225: }
6226:
6227: table.LC_nested_outer tr th.LC_right_item,
6228: table.LC_nested tr.LC_info_row td.LC_right_item,
6229: table.LC_nested tr.LC_odd_row td.LC_right_item,
6230: table.LC_nested tr td.LC_right_item {
6231: text-align: right;
6232: }
6233:
6234: table.LC_nested tr.LC_odd_row td {
6235: background-color: #EEEEEE;
6236: }
6237:
6238: table.LC_createuser {
6239: }
6240:
6241: table.LC_createuser tr.LC_section_row td {
6242: font-size: small;
6243: }
6244:
6245: table.LC_createuser tr.LC_info_row td {
6246: background-color: #CCCCCC;
6247: font-weight: bold;
6248: text-align: center;
6249: }
6250:
6251: table.LC_calendar {
6252: border: 1px solid #000000;
6253: border-collapse: collapse;
6254: width: 98%;
6255: }
6256:
6257: table.LC_calendar_pickdate {
6258: font-size: xx-small;
6259: }
6260:
6261: table.LC_calendar tr td {
6262: border: 1px solid #000000;
6263: vertical-align: top;
6264: width: 14%;
6265: }
6266:
6267: table.LC_calendar tr td.LC_calendar_day_empty {
6268: background-color: $data_table_dark;
6269: }
6270:
6271: table.LC_calendar tr td.LC_calendar_day_current {
6272: background-color: $data_table_highlight;
6273: }
6274:
6275: table.LC_data_table tr td.LC_mail_new {
6276: background-color: $mail_new;
6277: }
6278:
6279: table.LC_data_table tr.LC_mail_new:hover {
6280: background-color: $mail_new_hover;
6281: }
6282:
6283: table.LC_data_table tr td.LC_mail_read {
6284: background-color: $mail_read;
6285: }
6286:
6287: /*
6288: table.LC_data_table tr.LC_mail_read:hover {
6289: background-color: $mail_read_hover;
6290: }
6291: */
6292:
6293: table.LC_data_table tr td.LC_mail_replied {
6294: background-color: $mail_replied;
6295: }
6296:
6297: /*
6298: table.LC_data_table tr.LC_mail_replied:hover {
6299: background-color: $mail_replied_hover;
6300: }
6301: */
6302:
6303: table.LC_data_table tr td.LC_mail_other {
6304: background-color: $mail_other;
6305: }
6306:
6307: /*
6308: table.LC_data_table tr.LC_mail_other:hover {
6309: background-color: $mail_other_hover;
6310: }
6311: */
6312:
6313: table.LC_data_table tr > td.LC_browser_file,
6314: table.LC_data_table tr > td.LC_browser_file_published {
6315: background: #AAEE77;
6316: }
6317:
6318: table.LC_data_table tr > td.LC_browser_file_locked,
6319: table.LC_data_table tr > td.LC_browser_file_unpublished {
6320: background: #FFAA99;
6321: }
6322:
6323: table.LC_data_table tr > td.LC_browser_file_obsolete {
6324: background: #888888;
6325: }
6326:
6327: table.LC_data_table tr > td.LC_browser_file_modified,
6328: table.LC_data_table tr > td.LC_browser_file_metamodified {
6329: background: #F8F866;
6330: }
6331:
6332: table.LC_data_table tr.LC_browser_folder > td {
6333: background: #E0E8FF;
6334: }
6335:
6336: table.LC_data_table tr > td.LC_roles_is {
6337: /* background: #77FF77; */
6338: }
6339:
6340: table.LC_data_table tr > td.LC_roles_future {
6341: border-right: 8px solid #FFFF77;
6342: }
6343:
6344: table.LC_data_table tr > td.LC_roles_will {
6345: border-right: 8px solid #FFAA77;
6346: }
6347:
6348: table.LC_data_table tr > td.LC_roles_expired {
6349: border-right: 8px solid #FF7777;
6350: }
6351:
6352: table.LC_data_table tr > td.LC_roles_will_not {
6353: border-right: 8px solid #AAFF77;
6354: }
6355:
6356: table.LC_data_table tr > td.LC_roles_selected {
6357: border-right: 8px solid #11CC55;
6358: }
6359:
6360: span.LC_current_location {
6361: font-size:larger;
6362: background: $pgbg;
6363: }
6364:
6365: span.LC_current_nav_location {
6366: font-weight:bold;
6367: background: $sidebg;
6368: }
6369:
6370: span.LC_parm_menu_item {
6371: font-size: larger;
6372: }
6373:
6374: span.LC_parm_scope_all {
6375: color: red;
6376: }
6377:
6378: span.LC_parm_scope_folder {
6379: color: green;
6380: }
6381:
6382: span.LC_parm_scope_resource {
6383: color: orange;
6384: }
6385:
6386: span.LC_parm_part {
6387: color: blue;
6388: }
6389:
6390: span.LC_parm_folder,
6391: span.LC_parm_symb {
6392: font-size: x-small;
6393: font-family: $mono;
6394: color: #AAAAAA;
6395: }
6396:
6397: ul.LC_parm_parmlist li {
6398: display: inline-block;
6399: padding: 0.3em 0.8em;
6400: vertical-align: top;
6401: width: 150px;
6402: border-top:1px solid $lg_border_color;
6403: }
6404:
6405: td.LC_parm_overview_level_menu,
6406: td.LC_parm_overview_map_menu,
6407: td.LC_parm_overview_parm_selectors,
6408: td.LC_parm_overview_restrictions {
6409: border: 1px solid black;
6410: border-collapse: collapse;
6411: }
6412:
6413: table.LC_parm_overview_restrictions td {
6414: border-width: 1px 4px 1px 4px;
6415: border-style: solid;
6416: border-color: $pgbg;
6417: text-align: center;
6418: }
6419:
6420: table.LC_parm_overview_restrictions th {
6421: background: $tabbg;
6422: border-width: 1px 4px 1px 4px;
6423: border-style: solid;
6424: border-color: $pgbg;
6425: }
6426:
6427: table#LC_helpmenu {
6428: border: none;
6429: height: 55px;
6430: border-spacing: 0;
6431: }
6432:
6433: table#LC_helpmenu fieldset legend {
6434: font-size: larger;
6435: }
6436:
6437: table#LC_helpmenu_links {
6438: width: 100%;
6439: border: 1px solid black;
6440: background: $pgbg;
6441: padding: 0;
6442: border-spacing: 1px;
6443: }
6444:
6445: table#LC_helpmenu_links tr td {
6446: padding: 1px;
6447: background: $tabbg;
6448: text-align: center;
6449: font-weight: bold;
6450: }
6451:
6452: table#LC_helpmenu_links a:link,
6453: table#LC_helpmenu_links a:visited,
6454: table#LC_helpmenu_links a:active {
6455: text-decoration: none;
6456: color: $font;
6457: }
6458:
6459: table#LC_helpmenu_links a:hover {
6460: text-decoration: underline;
6461: color: $vlink;
6462: }
6463:
6464: .LC_chrt_popup_exists {
6465: border: 1px solid #339933;
6466: margin: -1px;
6467: }
6468:
6469: .LC_chrt_popup_up {
6470: border: 1px solid yellow;
6471: margin: -1px;
6472: }
6473:
6474: .LC_chrt_popup {
6475: border: 1px solid #8888FF;
6476: background: #CCCCFF;
6477: }
6478:
6479: table.LC_pick_box {
6480: border-collapse: separate;
6481: background: white;
6482: border: 1px solid black;
6483: border-spacing: 1px;
6484: }
6485:
6486: table.LC_pick_box td.LC_pick_box_title {
6487: background: $sidebg;
6488: font-weight: bold;
6489: text-align: left;
6490: vertical-align: top;
6491: width: 184px;
6492: padding: 8px;
6493: }
6494:
6495: table.LC_pick_box td.LC_pick_box_value {
6496: text-align: left;
6497: padding: 8px;
6498: }
6499:
6500: table.LC_pick_box td.LC_pick_box_select {
6501: text-align: left;
6502: padding: 8px;
6503: }
6504:
6505: table.LC_pick_box td.LC_pick_box_separator {
6506: padding: 0;
6507: height: 1px;
6508: background: black;
6509: }
6510:
6511: table.LC_pick_box td.LC_pick_box_submit {
6512: text-align: right;
6513: }
6514:
6515: table.LC_pick_box td.LC_evenrow_value {
6516: text-align: left;
6517: padding: 8px;
6518: background-color: $data_table_light;
6519: }
6520:
6521: table.LC_pick_box td.LC_oddrow_value {
6522: text-align: left;
6523: padding: 8px;
6524: background-color: $data_table_light;
6525: }
6526:
6527: span.LC_helpform_receipt_cat {
6528: font-weight: bold;
6529: }
6530:
6531: table.LC_group_priv_box {
6532: background: white;
6533: border: 1px solid black;
6534: border-spacing: 1px;
6535: }
6536:
6537: table.LC_group_priv_box td.LC_pick_box_title {
6538: background: $tabbg;
6539: font-weight: bold;
6540: text-align: right;
6541: width: 184px;
6542: }
6543:
6544: table.LC_group_priv_box td.LC_groups_fixed {
6545: background: $data_table_light;
6546: text-align: center;
6547: }
6548:
6549: table.LC_group_priv_box td.LC_groups_optional {
6550: background: $data_table_dark;
6551: text-align: center;
6552: }
6553:
6554: table.LC_group_priv_box td.LC_groups_functionality {
6555: background: $data_table_darker;
6556: text-align: center;
6557: font-weight: bold;
6558: }
6559:
6560: table.LC_group_priv td {
6561: text-align: left;
6562: padding: 0;
6563: }
6564:
6565: .LC_navbuttons {
6566: margin: 2ex 0ex 2ex 0ex;
6567: }
6568:
6569: .LC_topic_bar {
6570: font-weight: bold;
6571: background: $tabbg;
6572: margin: 1em 0em 1em 2em;
6573: padding: 3px;
6574: font-size: 1.2em;
6575: }
6576:
6577: .LC_topic_bar span {
6578: left: 0.5em;
6579: position: absolute;
6580: vertical-align: middle;
6581: font-size: 1.2em;
6582: }
6583:
6584: table.LC_course_group_status {
6585: margin: 20px;
6586: }
6587:
6588: table.LC_status_selector td {
6589: vertical-align: top;
6590: text-align: center;
6591: padding: 4px;
6592: }
6593:
6594: div.LC_feedback_link {
6595: clear: both;
6596: background: $sidebg;
6597: width: 100%;
6598: padding-bottom: 10px;
6599: border: 1px $tabbg solid;
6600: height: 22px;
6601: line-height: 22px;
6602: padding-top: 5px;
6603: }
6604:
6605: div.LC_feedback_link img {
6606: height: 22px;
6607: vertical-align:middle;
6608: }
6609:
6610: div.LC_feedback_link a {
6611: text-decoration: none;
6612: }
6613:
6614: div.LC_comblock {
6615: display:inline;
6616: color:$font;
6617: font-size:90%;
6618: }
6619:
6620: div.LC_feedback_link div.LC_comblock {
6621: padding-left:5px;
6622: }
6623:
6624: div.LC_feedback_link div.LC_comblock a {
6625: color:$font;
6626: }
6627:
6628: span.LC_feedback_link {
6629: /* background: $feedback_link_bg; */
6630: font-size: larger;
6631: }
6632:
6633: span.LC_message_link {
6634: /* background: $feedback_link_bg; */
6635: font-size: larger;
6636: position: absolute;
6637: right: 1em;
6638: }
6639:
6640: table.LC_prior_tries {
6641: border: 1px solid #000000;
6642: border-collapse: separate;
6643: border-spacing: 1px;
6644: }
6645:
6646: table.LC_prior_tries td {
6647: padding: 2px;
6648: }
6649:
6650: .LC_answer_correct {
6651: background: lightgreen;
6652: color: darkgreen;
6653: padding: 6px;
6654: }
6655:
6656: .LC_answer_charged_try {
6657: background: #FFAAAA;
6658: color: darkred;
6659: padding: 6px;
6660: }
6661:
6662: .LC_answer_not_charged_try,
6663: .LC_answer_no_grade,
6664: .LC_answer_late {
6665: background: lightyellow;
6666: color: black;
6667: padding: 6px;
6668: }
6669:
6670: .LC_answer_previous {
6671: background: lightblue;
6672: color: darkblue;
6673: padding: 6px;
6674: }
6675:
6676: .LC_answer_no_message {
6677: background: #FFFFFF;
6678: color: black;
6679: padding: 6px;
6680: }
6681:
6682: .LC_answer_unknown {
6683: background: orange;
6684: color: black;
6685: padding: 6px;
6686: }
6687:
6688: span.LC_prior_numerical,
6689: span.LC_prior_string,
6690: span.LC_prior_custom,
6691: span.LC_prior_reaction,
6692: span.LC_prior_math {
6693: font-family: $mono;
6694: white-space: pre;
6695: }
6696:
6697: span.LC_prior_string {
6698: font-family: $mono;
6699: white-space: pre;
6700: }
6701:
6702: table.LC_prior_option {
6703: width: 100%;
6704: border-collapse: collapse;
6705: }
6706:
6707: table.LC_prior_rank,
6708: table.LC_prior_match {
6709: border-collapse: collapse;
6710: }
6711:
6712: table.LC_prior_option tr td,
6713: table.LC_prior_rank tr td,
6714: table.LC_prior_match tr td {
6715: border: 1px solid #000000;
6716: }
6717:
6718: .LC_nobreak {
6719: white-space: nowrap;
6720: }
6721:
6722: span.LC_cusr_emph {
6723: font-style: italic;
6724: }
6725:
6726: span.LC_cusr_subheading {
6727: font-weight: normal;
6728: font-size: 85%;
6729: }
6730:
6731: div.LC_docs_entry_move {
6732: border: 1px solid #BBBBBB;
6733: background: #DDDDDD;
6734: width: 22px;
6735: padding: 1px;
6736: margin: 0;
6737: }
6738:
6739: table.LC_data_table tr > td.LC_docs_entry_commands,
6740: table.LC_data_table tr > td.LC_docs_entry_parameter {
6741: font-size: x-small;
6742: }
6743:
6744: .LC_docs_entry_parameter {
6745: white-space: nowrap;
6746: }
6747:
6748: .LC_docs_copy {
6749: color: #000099;
6750: }
6751:
6752: .LC_docs_cut {
6753: color: #550044;
6754: }
6755:
6756: .LC_docs_rename {
6757: color: #009900;
6758: }
6759:
6760: .LC_docs_remove {
6761: color: #990000;
6762: }
6763:
6764: .LC_domprefs_email,
6765: .LC_docs_reinit_warn,
6766: .LC_docs_ext_edit {
6767: font-size: x-small;
6768: }
6769:
6770: table.LC_docs_adddocs td,
6771: table.LC_docs_adddocs th {
6772: border: 1px solid #BBBBBB;
6773: padding: 4px;
6774: background: #DDDDDD;
6775: }
6776:
6777: table.LC_sty_begin {
6778: background: #BBFFBB;
6779: }
6780:
6781: table.LC_sty_end {
6782: background: #FFBBBB;
6783: }
6784:
6785: table.LC_double_column {
6786: border-width: 0;
6787: border-collapse: collapse;
6788: width: 100%;
6789: padding: 2px;
6790: }
6791:
6792: table.LC_double_column tr td.LC_left_col {
6793: top: 2px;
6794: left: 2px;
6795: width: 47%;
6796: vertical-align: top;
6797: }
6798:
6799: table.LC_double_column tr td.LC_right_col {
6800: top: 2px;
6801: right: 2px;
6802: width: 47%;
6803: vertical-align: top;
6804: }
6805:
6806: div.LC_left_float {
6807: float: left;
6808: padding-right: 5%;
6809: padding-bottom: 4px;
6810: }
6811:
6812: div.LC_clear_float_header {
6813: padding-bottom: 2px;
6814: }
6815:
6816: div.LC_clear_float_footer {
6817: padding-top: 10px;
6818: clear: both;
6819: }
6820:
6821: div.LC_grade_show_user {
6822: /* border-left: 5px solid $sidebg; */
6823: border-top: 5px solid #000000;
6824: margin: 50px 0 0 0;
6825: padding: 15px 0 5px 10px;
6826: }
6827:
6828: div.LC_grade_show_user_odd_row {
6829: /* border-left: 5px solid #000000; */
6830: }
6831:
6832: div.LC_grade_show_user div.LC_Box {
6833: margin-right: 50px;
6834: }
6835:
6836: div.LC_grade_submissions,
6837: div.LC_grade_message_center,
6838: div.LC_grade_info_links {
6839: margin: 5px;
6840: width: 99%;
6841: background: #FFFFFF;
6842: }
6843:
6844: div.LC_grade_submissions_header,
6845: div.LC_grade_message_center_header {
6846: font-weight: bold;
6847: font-size: large;
6848: }
6849:
6850: div.LC_grade_submissions_body,
6851: div.LC_grade_message_center_body {
6852: border: 1px solid black;
6853: width: 99%;
6854: background: #FFFFFF;
6855: }
6856:
6857: table.LC_scantron_action {
6858: width: 100%;
6859: }
6860:
6861: table.LC_scantron_action tr th {
6862: font-weight:bold;
6863: font-style:normal;
6864: }
6865:
6866: .LC_edit_problem_header,
6867: div.LC_edit_problem_footer {
6868: font-weight: normal;
6869: font-size: medium;
6870: margin: 2px;
6871: background-color: $sidebg;
6872: }
6873:
6874: div.LC_edit_problem_header,
6875: div.LC_edit_problem_header div,
6876: div.LC_edit_problem_footer,
6877: div.LC_edit_problem_footer div,
6878: div.LC_edit_problem_editxml_header,
6879: div.LC_edit_problem_editxml_header div {
6880: z-index: 100;
6881: }
6882:
6883: div.LC_edit_problem_header_title {
6884: font-weight: bold;
6885: font-size: larger;
6886: background: $tabbg;
6887: padding: 3px;
6888: margin: 0 0 5px 0;
6889: }
6890:
6891: table.LC_edit_problem_header_title {
6892: width: 100%;
6893: background: $tabbg;
6894: }
6895:
6896: div.LC_edit_actionbar {
6897: background-color: $sidebg;
6898: margin: 0;
6899: padding: 0;
6900: line-height: 200%;
6901: }
6902:
6903: div.LC_edit_actionbar div{
6904: padding: 0;
6905: margin: 0;
6906: display: inline-block;
6907: }
6908:
6909: .LC_edit_opt {
6910: padding-left: 1em;
6911: white-space: nowrap;
6912: }
6913:
6914: .LC_edit_problem_latexhelper{
6915: text-align: right;
6916: }
6917:
6918: #LC_edit_problem_colorful div{
6919: margin-left: 40px;
6920: }
6921:
6922: #LC_edit_problem_codemirror div{
6923: margin-left: 0px;
6924: }
6925:
6926: img.stift {
6927: border-width: 0;
6928: vertical-align: middle;
6929: }
6930:
6931: table td.LC_mainmenu_col_fieldset {
6932: vertical-align: top;
6933: }
6934:
6935: div.LC_createcourse {
6936: margin: 10px 10px 10px 10px;
6937: }
6938:
6939: .LC_dccid {
6940: float: right;
6941: margin: 0.2em 0 0 0;
6942: padding: 0;
6943: font-size: 90%;
6944: display:none;
6945: }
6946:
6947: ol.LC_primary_menu a:hover,
6948: ol#LC_MenuBreadcrumbs a:hover,
6949: ol#LC_PathBreadcrumbs a:hover,
6950: ul#LC_secondary_menu a:hover,
6951: .LC_FormSectionClearButton input:hover
6952: ul.LC_TabContent li:hover a {
6953: color:$button_hover;
6954: text-decoration:none;
6955: }
6956:
6957: h1 {
6958: padding: 0;
6959: line-height:130%;
6960: }
6961:
6962: h2,
6963: h3,
6964: h4,
6965: h5,
6966: h6 {
6967: margin: 5px 0 5px 0;
6968: padding: 0;
6969: line-height:130%;
6970: }
6971:
6972: .LC_hcell {
6973: padding:3px 15px 3px 15px;
6974: margin: 0;
6975: background-color:$tabbg;
6976: color:$fontmenu;
6977: border-bottom:solid 1px $lg_border_color;
6978: }
6979:
6980: .LC_Box > .LC_hcell {
6981: margin: 0 -10px 10px -10px;
6982: }
6983:
6984: .LC_noBorder {
6985: border: 0;
6986: }
6987:
6988: .LC_FormSectionClearButton input {
6989: background-color:transparent;
6990: border: none;
6991: cursor:pointer;
6992: text-decoration:underline;
6993: }
6994:
6995: .LC_help_open_topic {
6996: color: #FFFFFF;
6997: background-color: #EEEEFF;
6998: margin: 1px;
6999: padding: 4px;
7000: border: 1px solid #000033;
7001: white-space: nowrap;
7002: /* vertical-align: middle; */
7003: }
7004:
7005: dl,
7006: ul,
7007: div,
7008: fieldset {
7009: margin: 10px 10px 10px 0;
7010: /* overflow: hidden; */
7011: }
7012:
7013: article.geogebraweb div {
7014: margin: 0;
7015: }
7016:
7017: fieldset > legend {
7018: font-weight: bold;
7019: padding: 0 5px 0 5px;
7020: }
7021:
7022: #LC_nav_bar {
7023: float: left;
7024: background-color: $pgbg_or_bgcolor;
7025: margin: 0 0 2px 0;
7026: }
7027:
7028: #LC_realm {
7029: margin: 0.2em 0 0 0;
7030: padding: 0;
7031: font-weight: bold;
7032: text-align: center;
7033: background-color: $pgbg_or_bgcolor;
7034: }
7035:
7036: #LC_nav_bar em {
7037: font-weight: bold;
7038: font-style: normal;
7039: }
7040:
7041: ol.LC_primary_menu {
7042: margin: 0;
7043: padding: 0;
7044: }
7045:
7046: ol#LC_PathBreadcrumbs {
7047: margin: 0;
7048: }
7049:
7050: ol.LC_primary_menu li {
7051: color: RGB(80, 80, 80);
7052: vertical-align: middle;
7053: text-align: left;
7054: list-style: none;
7055: position: relative;
7056: float: left;
7057: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7058: line-height: 1.5em;
7059: }
7060:
7061: ol.LC_primary_menu li a,
7062: ol.LC_primary_menu li p {
7063: display: block;
7064: margin: 0;
7065: padding: 0 5px 0 10px;
7066: text-decoration: none;
7067: }
7068:
7069: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7070: display: inline-block;
7071: width: 95%;
7072: text-align: left;
7073: }
7074:
7075: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7076: display: inline-block;
7077: width: 5%;
7078: float: right;
7079: text-align: right;
7080: font-size: 70%;
7081: }
7082:
7083: ol.LC_primary_menu ul {
7084: display: none;
7085: width: 15em;
7086: background-color: $data_table_light;
7087: position: absolute;
7088: top: 100%;
7089: }
7090:
7091: ol.LC_primary_menu ul ul {
7092: left: 100%;
7093: top: 0;
7094: }
7095:
7096: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7097: display: block;
7098: position: absolute;
7099: margin: 0;
7100: padding: 0;
7101: z-index: 2;
7102: }
7103:
7104: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7105: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7106: font-size: 90%;
7107: vertical-align: top;
7108: float: none;
7109: border-left: 1px solid black;
7110: border-right: 1px solid black;
7111: /* A dark bottom border to visualize different menu options;
7112: overwritten in the create_submenu routine for the last border-bottom of the menu */
7113: border-bottom: 1px solid $data_table_dark;
7114: }
7115:
7116: ol.LC_primary_menu li li p:hover {
7117: color:$button_hover;
7118: text-decoration:none;
7119: background-color:$data_table_dark;
7120: }
7121:
7122: ol.LC_primary_menu li li a:hover {
7123: color:$button_hover;
7124: background-color:$data_table_dark;
7125: }
7126:
7127: /* Font-size equal to the size of the predecessors*/
7128: ol.LC_primary_menu li:hover li li {
7129: font-size: 100%;
7130: }
7131:
7132: ol.LC_primary_menu li img {
7133: vertical-align: bottom;
7134: height: 1.1em;
7135: margin: 0.2em 0 0 0;
7136: }
7137:
7138: ol.LC_primary_menu a {
7139: color: RGB(80, 80, 80);
7140: text-decoration: none;
7141: }
7142:
7143: ol.LC_primary_menu a.LC_new_message {
7144: font-weight:bold;
7145: color: darkred;
7146: }
7147:
7148: ol.LC_docs_parameters {
7149: margin-left: 0;
7150: padding: 0;
7151: list-style: none;
7152: }
7153:
7154: ol.LC_docs_parameters li {
7155: margin: 0;
7156: padding-right: 20px;
7157: display: inline;
7158: }
7159:
7160: ol.LC_docs_parameters li:before {
7161: content: "\\002022 \\0020";
7162: }
7163:
7164: li.LC_docs_parameters_title {
7165: font-weight: bold;
7166: }
7167:
7168: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7169: content: "";
7170: }
7171:
7172: ul#LC_secondary_menu {
7173: clear: right;
7174: color: $fontmenu;
7175: background: $tabbg;
7176: list-style: none;
7177: padding: 0;
7178: margin: 0;
7179: width: 100%;
7180: text-align: left;
7181: float: left;
7182: }
7183:
7184: ul#LC_secondary_menu li {
7185: font-weight: bold;
7186: line-height: 1.8em;
7187: border-right: 1px solid black;
7188: float: left;
7189: }
7190:
7191: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7192: background-color: $data_table_light;
7193: }
7194:
7195: ul#LC_secondary_menu li a {
7196: padding: 0 0.8em;
7197: }
7198:
7199: ul#LC_secondary_menu li ul {
7200: display: none;
7201: }
7202:
7203: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7204: display: block;
7205: position: absolute;
7206: margin: 0;
7207: padding: 0;
7208: list-style:none;
7209: float: none;
7210: background-color: $data_table_light;
7211: z-index: 2;
7212: margin-left: -1px;
7213: }
7214:
7215: ul#LC_secondary_menu li ul li {
7216: font-size: 90%;
7217: vertical-align: top;
7218: border-left: 1px solid black;
7219: border-right: 1px solid black;
7220: background-color: $data_table_light;
7221: list-style:none;
7222: float: none;
7223: }
7224:
7225: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7226: background-color: $data_table_dark;
7227: }
7228:
7229: ul.LC_TabContent {
7230: display:block;
7231: background: $sidebg;
7232: border-bottom: solid 1px $lg_border_color;
7233: list-style:none;
7234: margin: -1px -10px 0 -10px;
7235: padding: 0;
7236: }
7237:
7238: ul.LC_TabContent li,
7239: ul.LC_TabContentBigger li {
7240: float:left;
7241: }
7242:
7243: ul#LC_secondary_menu li a {
7244: color: $fontmenu;
7245: text-decoration: none;
7246: }
7247:
7248: ul.LC_TabContent {
7249: min-height:20px;
7250: }
7251:
7252: ul.LC_TabContent li {
7253: vertical-align:middle;
7254: padding: 0 16px 0 10px;
7255: background-color:$tabbg;
7256: border-bottom:solid 1px $lg_border_color;
7257: border-left: solid 1px $font;
7258: }
7259:
7260: ul.LC_TabContent .right {
7261: float:right;
7262: }
7263:
7264: ul.LC_TabContent li a,
7265: ul.LC_TabContent li {
7266: color:rgb(47,47,47);
7267: text-decoration:none;
7268: font-size:95%;
7269: font-weight:bold;
7270: min-height:20px;
7271: }
7272:
7273: ul.LC_TabContent li a:hover,
7274: ul.LC_TabContent li a:focus {
7275: color: $button_hover;
7276: background:none;
7277: outline:none;
7278: }
7279:
7280: ul.LC_TabContent li:hover {
7281: color: $button_hover;
7282: cursor:pointer;
7283: }
7284:
7285: ul.LC_TabContent li.active {
7286: color: $font;
7287: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7288: border-bottom:solid 1px #FFFFFF;
7289: cursor: default;
7290: }
7291:
7292: ul.LC_TabContent li.active a {
7293: color:$font;
7294: background:#FFFFFF;
7295: outline: none;
7296: }
7297:
7298: ul.LC_TabContent li.goback {
7299: float: left;
7300: border-left: none;
7301: }
7302:
7303: #maincoursedoc {
7304: clear:both;
7305: }
7306:
7307: ul.LC_TabContentBigger {
7308: display:block;
7309: list-style:none;
7310: padding: 0;
7311: }
7312:
7313: ul.LC_TabContentBigger li {
7314: vertical-align:bottom;
7315: height: 30px;
7316: font-size:110%;
7317: font-weight:bold;
7318: color: #737373;
7319: }
7320:
7321: ul.LC_TabContentBigger li.active {
7322: position: relative;
7323: top: 1px;
7324: }
7325:
7326: ul.LC_TabContentBigger li a {
7327: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7328: height: 30px;
7329: line-height: 30px;
7330: text-align: center;
7331: display: block;
7332: text-decoration: none;
7333: outline: none;
7334: }
7335:
7336: ul.LC_TabContentBigger li.active a {
7337: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7338: color:$font;
7339: }
7340:
7341: ul.LC_TabContentBigger li b {
7342: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7343: display: block;
7344: float: left;
7345: padding: 0 30px;
7346: border-bottom: 1px solid $lg_border_color;
7347: }
7348:
7349: ul.LC_TabContentBigger li:hover b {
7350: color:$button_hover;
7351: }
7352:
7353: ul.LC_TabContentBigger li.active b {
7354: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7355: color:$font;
7356: border: 0;
7357: }
7358:
7359:
7360: ul.LC_CourseBreadcrumbs {
7361: background: $sidebg;
7362: height: 2em;
7363: padding-left: 10px;
7364: margin: 0;
7365: list-style-position: inside;
7366: }
7367:
7368: ol#LC_MenuBreadcrumbs,
7369: ol#LC_PathBreadcrumbs {
7370: padding-left: 10px;
7371: margin: 0;
7372: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7373: }
7374:
7375: ol#LC_MenuBreadcrumbs li,
7376: ol#LC_PathBreadcrumbs li,
7377: ul.LC_CourseBreadcrumbs li {
7378: display: inline;
7379: white-space: normal;
7380: }
7381:
7382: ol#LC_MenuBreadcrumbs li a,
7383: ul.LC_CourseBreadcrumbs li a {
7384: text-decoration: none;
7385: font-size:90%;
7386: }
7387:
7388: ol#LC_MenuBreadcrumbs h1 {
7389: display: inline;
7390: font-size: 90%;
7391: line-height: 2.5em;
7392: margin: 0;
7393: padding: 0;
7394: }
7395:
7396: ol#LC_PathBreadcrumbs li a {
7397: text-decoration:none;
7398: font-size:100%;
7399: font-weight:bold;
7400: }
7401:
7402: .LC_Box {
7403: border: solid 1px $lg_border_color;
7404: padding: 0 10px 10px 10px;
7405: }
7406:
7407: .LC_DocsBox {
7408: border: solid 1px $lg_border_color;
7409: padding: 0 0 10px 10px;
7410: }
7411:
7412: .LC_AboutMe_Image {
7413: float:left;
7414: margin-right:10px;
7415: }
7416:
7417: .LC_Clear_AboutMe_Image {
7418: clear:left;
7419: }
7420:
7421: dl.LC_ListStyleClean dt {
7422: padding-right: 5px;
7423: display: table-header-group;
7424: }
7425:
7426: dl.LC_ListStyleClean dd {
7427: display: table-row;
7428: }
7429:
7430: .LC_ListStyleClean,
7431: .LC_ListStyleSimple,
7432: .LC_ListStyleNormal,
7433: .LC_ListStyleSpecial {
7434: /* display:block; */
7435: list-style-position: inside;
7436: list-style-type: none;
7437: overflow: hidden;
7438: padding: 0;
7439: }
7440:
7441: .LC_ListStyleSimple li,
7442: .LC_ListStyleSimple dd,
7443: .LC_ListStyleNormal li,
7444: .LC_ListStyleNormal dd,
7445: .LC_ListStyleSpecial li,
7446: .LC_ListStyleSpecial dd {
7447: margin: 0;
7448: padding: 5px 5px 5px 10px;
7449: clear: both;
7450: }
7451:
7452: .LC_ListStyleClean li,
7453: .LC_ListStyleClean dd {
7454: padding-top: 0;
7455: padding-bottom: 0;
7456: }
7457:
7458: .LC_ListStyleSimple dd,
7459: .LC_ListStyleSimple li {
7460: border-bottom: solid 1px $lg_border_color;
7461: }
7462:
7463: .LC_ListStyleSpecial li,
7464: .LC_ListStyleSpecial dd {
7465: list-style-type: none;
7466: background-color: RGB(220, 220, 220);
7467: margin-bottom: 4px;
7468: }
7469:
7470: table.LC_SimpleTable {
7471: margin:5px;
7472: border:solid 1px $lg_border_color;
7473: }
7474:
7475: table.LC_SimpleTable tr {
7476: padding: 0;
7477: border:solid 1px $lg_border_color;
7478: }
7479:
7480: table.LC_SimpleTable thead {
7481: background:rgb(220,220,220);
7482: }
7483:
7484: div.LC_columnSection {
7485: display: block;
7486: clear: both;
7487: overflow: hidden;
7488: margin: 0;
7489: }
7490:
7491: div.LC_columnSection>* {
7492: float: left;
7493: margin: 10px 20px 10px 0;
7494: overflow:hidden;
7495: }
7496:
7497: table em {
7498: font-weight: bold;
7499: font-style: normal;
7500: }
7501:
7502: table.LC_tableBrowseRes,
7503: table.LC_tableOfContent {
7504: border:none;
7505: border-spacing: 1px;
7506: padding: 3px;
7507: background-color: #FFFFFF;
7508: font-size: 90%;
7509: }
7510:
7511: table.LC_tableOfContent {
7512: border-collapse: collapse;
7513: }
7514:
7515: table.LC_tableBrowseRes a,
7516: table.LC_tableOfContent a {
7517: background-color: transparent;
7518: text-decoration: none;
7519: }
7520:
7521: table.LC_tableOfContent img {
7522: border: none;
7523: height: 1.3em;
7524: vertical-align: text-bottom;
7525: margin-right: 0.3em;
7526: }
7527:
7528: a#LC_content_toolbar_firsthomework {
7529: background-image:url(/res/adm/pages/open-first-problem.gif);
7530: }
7531:
7532: a#LC_content_toolbar_everything {
7533: background-image:url(/res/adm/pages/show-all.gif);
7534: }
7535:
7536: a#LC_content_toolbar_uncompleted {
7537: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7538: }
7539:
7540: #LC_content_toolbar_clearbubbles {
7541: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7542: }
7543:
7544: a#LC_content_toolbar_changefolder {
7545: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7546: }
7547:
7548: a#LC_content_toolbar_changefolder_toggled {
7549: background-image:url(/res/adm/pages/open-all-folders.gif);
7550: }
7551:
7552: a#LC_content_toolbar_edittoplevel {
7553: background-image:url(/res/adm/pages/edittoplevel.gif);
7554: }
7555:
7556: ul#LC_toolbar li a:hover {
7557: background-position: bottom center;
7558: }
7559:
7560: ul#LC_toolbar {
7561: padding: 0;
7562: margin: 2px;
7563: list-style:none;
7564: position:relative;
7565: background-color:white;
7566: overflow: auto;
7567: }
7568:
7569: ul#LC_toolbar li {
7570: border:1px solid white;
7571: padding: 0;
7572: margin: 0;
7573: float: left;
7574: display:inline;
7575: vertical-align:middle;
7576: white-space: nowrap;
7577: }
7578:
7579:
7580: a.LC_toolbarItem {
7581: display:block;
7582: padding: 0;
7583: margin: 0;
7584: height: 32px;
7585: width: 32px;
7586: color:white;
7587: border: none;
7588: background-repeat:no-repeat;
7589: background-color:transparent;
7590: }
7591:
7592: ul.LC_funclist {
7593: margin: 0;
7594: padding: 0.5em 1em 0.5em 0;
7595: }
7596:
7597: ul.LC_funclist > li:first-child {
7598: font-weight:bold;
7599: margin-left:0.8em;
7600: }
7601:
7602: ul.LC_funclist + ul.LC_funclist {
7603: /*
7604: left border as a seperator if we have more than
7605: one list
7606: */
7607: border-left: 1px solid $sidebg;
7608: /*
7609: this hides the left border behind the border of the
7610: outer box if element is wrapped to the next 'line'
7611: */
7612: margin-left: -1px;
7613: }
7614:
7615: ul.LC_funclist li {
7616: display: inline;
7617: white-space: nowrap;
7618: margin: 0 0 0 25px;
7619: line-height: 150%;
7620: }
7621:
7622: .LC_hidden {
7623: display: none;
7624: }
7625:
7626: .LCmodal-overlay {
7627: position:fixed;
7628: top:0;
7629: right:0;
7630: bottom:0;
7631: left:0;
7632: height:100%;
7633: width:100%;
7634: margin:0;
7635: padding:0;
7636: background:#999;
7637: opacity:.75;
7638: filter: alpha(opacity=75);
7639: -moz-opacity: 0.75;
7640: z-index:101;
7641: }
7642:
7643: * html .LCmodal-overlay {
7644: position: absolute;
7645: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7646: }
7647:
7648: .LCmodal-window {
7649: position:fixed;
7650: top:50%;
7651: left:50%;
7652: margin:0;
7653: padding:0;
7654: z-index:102;
7655: }
7656:
7657: * html .LCmodal-window {
7658: position:absolute;
7659: }
7660:
7661: .LCclose-window {
7662: position:absolute;
7663: width:32px;
7664: height:32px;
7665: right:8px;
7666: top:8px;
7667: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7668: text-indent:-99999px;
7669: overflow:hidden;
7670: cursor:pointer;
7671: }
7672:
7673: /*
7674: styles used by TTH when "Default set of options to pass to tth/m
7675: when converting TeX" in course settings has been set
7676:
7677: option passed: -t
7678:
7679: */
7680:
7681: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7682: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7683: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7684: td div.norm {line-height:normal;}
7685:
7686: /*
7687: option passed -y3
7688: */
7689:
7690: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7691: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7692: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7693:
7694: #LC_minitab_header {
7695: float:left;
7696: width:100%;
7697: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
7698: font-size:93%;
7699: line-height:normal;
7700: margin: 0.5em 0 0.5em 0;
7701: }
7702: #LC_minitab_header ul {
7703: margin:0;
7704: padding:10px 10px 0;
7705: list-style:none;
7706: }
7707: #LC_minitab_header li {
7708: float:left;
7709: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
7710: margin:0;
7711: padding:0 0 0 9px;
7712: }
7713: #LC_minitab_header a {
7714: display:block;
7715: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
7716: padding:5px 15px 4px 6px;
7717: }
7718: #LC_minitab_header #LC_current_minitab {
7719: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
7720: }
7721: #LC_minitab_header #LC_current_minitab a {
7722: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
7723: padding-bottom:5px;
7724: }
7725:
7726:
7727: END
7728: }
7729:
7730: =pod
7731:
7732: =item * &headtag()
7733:
7734: Returns a uniform footer for LON-CAPA web pages.
7735:
7736: Inputs: $title - optional title for the head
7737: $head_extra - optional extra HTML to put inside the <head>
7738: $args - optional arguments
7739: force_register - if is true call registerurl so the remote is
7740: informed
7741: redirect -> array ref of
7742: 1- seconds before redirect occurs
7743: 2- url to redirect to
7744: 3- whether the side effect should occur
7745: (side effect of setting
7746: $env{'internal.head.redirect'} to the url
7747: redirected too)
7748: domain -> force to color decorate a page for a specific
7749: domain
7750: function -> force usage of a specific rolish color scheme
7751: bgcolor -> override the default page bgcolor
7752: no_auto_mt_title
7753: -> prevent &mt()ing the title arg
7754:
7755: =cut
7756:
7757: sub headtag {
7758: my ($title,$head_extra,$args) = @_;
7759:
7760: my $function = $args->{'function'} || &get_users_function();
7761: my $domain = $args->{'domain'} || &determinedomain();
7762: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7763: my $httphost = $args->{'use_absolute'};
7764: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7765: $Apache::lonnet::perlvar{'lonVersion'},
7766: #time(),
7767: $env{'environment.color.timestamp'},
7768: $function,$domain,$bgcolor);
7769:
7770: $url = '/adm/css/'.&escape($url).'.css';
7771:
7772: my $result =
7773: '<head>'.
7774: &font_settings($args);
7775:
7776: my $inhibitprint;
7777: if ($args->{'print_suppress'}) {
7778: $inhibitprint = &print_suppression();
7779: }
7780:
7781: if (!$args->{'frameset'}) {
7782: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7783: }
7784: if ($args->{'force_register'}) {
7785: $result .= &Apache::lonmenu::registerurl(1);
7786: }
7787: if (!$args->{'no_nav_bar'}
7788: && !$args->{'only_body'}
7789: && !$args->{'frameset'}) {
7790: $result .= &help_menu_js($httphost);
7791: $result.=&modal_window();
7792: $result.=&togglebox_script();
7793: $result.=&wishlist_window();
7794: $result.=&LCprogressbarUpdate_script();
7795: } else {
7796: if ($args->{'add_modal'}) {
7797: $result.=&modal_window();
7798: }
7799: if ($args->{'add_wishlist'}) {
7800: $result.=&wishlist_window();
7801: }
7802: if ($args->{'add_togglebox'}) {
7803: $result.=&togglebox_script();
7804: }
7805: if ($args->{'add_progressbar'}) {
7806: $result.=&LCprogressbarUpdate_script();
7807: }
7808: }
7809: if (ref($args->{'redirect'})) {
7810: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7811: $url = &Apache::lonenc::check_encrypt($url);
7812: if (!$inhibit_continue) {
7813: $env{'internal.head.redirect'} = $url;
7814: }
7815: $result.=<<ADDMETA
7816: <meta http-equiv="pragma" content="no-cache" />
7817: <meta http-equiv="Refresh" content="$time; url=$url" />
7818: ADDMETA
7819: } else {
7820: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
7821: my $requrl = $env{'request.uri'};
7822: if ($requrl eq '') {
7823: $requrl = $ENV{'REQUEST_URI'};
7824: $requrl =~ s/\?.+$//;
7825: }
7826: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
7827: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
7828: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
7829: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
7830: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
7831: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
7832: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
7833: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
7834: if ($domdefs{'offloadnow'}{$lonhost}) {
7835: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
7836: if (($newserver) && ($newserver ne $lonhost)) {
7837: my $numsec = 5;
7838: my $timeout = $numsec * 1000;
7839: my ($newurl,$locknum,%locks,$msg);
7840: if ($env{'request.role.adv'}) {
7841: ($locknum,%locks) = &Apache::lonnet::get_locks();
7842: }
7843: my $disable_submit = 0;
7844: if ($requrl =~ /$LONCAPA::assess_re/) {
7845: $disable_submit = 1;
7846: }
7847: if ($locknum) {
7848: my @lockinfo = sort(values(%locks));
7849: $msg = &mt('Once the following tasks are complete: ')."\\n".
7850: join(", ",sort(values(%locks)))."\\n".
7851: &mt('your session will be transferred to a different server, after you click "Roles".');
7852: } else {
7853: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
7854: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
7855: }
7856: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
7857: $newurl = '/adm/switchserver?otherserver='.$newserver;
7858: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
7859: $newurl .= '&role='.$env{'request.role'};
7860: }
7861: if ($env{'request.symb'}) {
7862: $newurl .= '&symb='.$env{'request.symb'};
7863: } else {
7864: $newurl .= '&origurl='.$requrl;
7865: }
7866: }
7867: &js_escape(\$msg);
7868: $result.=<<OFFLOAD
7869: <meta http-equiv="pragma" content="no-cache" />
7870: <script type="text/javascript">
7871: // <![CDATA[
7872: function LC_Offload_Now() {
7873: var dest = "$newurl";
7874: if (dest != '') {
7875: window.location.href="$newurl";
7876: }
7877: }
7878: \$(document).ready(function () {
7879: window.alert('$msg');
7880: if ($disable_submit) {
7881: \$(".LC_hwk_submit").prop("disabled", true);
7882: \$( ".LC_textline" ).prop( "readonly", "readonly");
7883: }
7884: setTimeout('LC_Offload_Now()', $timeout);
7885: });
7886: // ]]>
7887: </script>
7888: OFFLOAD
7889: }
7890: }
7891: }
7892: }
7893: }
7894: }
7895: }
7896: if (!defined($title)) {
7897: $title = 'The LearningOnline Network with CAPA';
7898: }
7899: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7900: $result .= '<title> LON-CAPA '.$title.'</title>'
7901: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7902: if (!$args->{'frameset'}) {
7903: $result .= ' /';
7904: }
7905: $result .= '>'
7906: .$inhibitprint
7907: .$head_extra;
7908: my $clientmobile;
7909: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
7910: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
7911: } else {
7912: $clientmobile = $env{'browser.mobile'};
7913: }
7914: if ($clientmobile) {
7915: $result .= '
7916: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7917: <meta name="apple-mobile-web-app-capable" content="yes" />';
7918: }
7919: $result .= '<meta name="google" content="notranslate" />'."\n";
7920: return $result.'</head>';
7921: }
7922:
7923: =pod
7924:
7925: =item * &font_settings()
7926:
7927: Returns neccessary <meta> to set the proper encoding
7928:
7929: Inputs: optional reference to HASH -- $args passed to &headtag()
7930:
7931: =cut
7932:
7933: sub font_settings {
7934: my ($args) = @_;
7935: my $headerstring='';
7936: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
7937: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
7938: $headerstring.=
7939: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
7940: if (!$args->{'frameset'}) {
7941: $headerstring.= ' /';
7942: }
7943: $headerstring .= '>'."\n";
7944: }
7945: return $headerstring;
7946: }
7947:
7948: =pod
7949:
7950: =item * &print_suppression()
7951:
7952: In course context returns css which causes the body to be blank when media="print",
7953: if printout generation is unavailable for the current resource.
7954:
7955: This could be because:
7956:
7957: (a) printstartdate is in the future
7958:
7959: (b) printenddate is in the past
7960:
7961: (c) there is an active exam block with "printout"
7962: functionality blocked
7963:
7964: Users with pav, pfo or evb privileges are exempt.
7965:
7966: Inputs: none
7967:
7968: =cut
7969:
7970:
7971: sub print_suppression {
7972: my $noprint;
7973: if ($env{'request.course.id'}) {
7974: my $scope = $env{'request.course.id'};
7975: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7976: (&Apache::lonnet::allowed('pfo',$scope))) {
7977: return;
7978: }
7979: if ($env{'request.course.sec'} ne '') {
7980: $scope .= "/$env{'request.course.sec'}";
7981: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7982: (&Apache::lonnet::allowed('pfo',$scope))) {
7983: return;
7984: }
7985: }
7986: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7987: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7988: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
7989: if ($blocked) {
7990: my $checkrole = "cm./$cdom/$cnum";
7991: if ($env{'request.course.sec'} ne '') {
7992: $checkrole .= "/$env{'request.course.sec'}";
7993: }
7994: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7995: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7996: $noprint = 1;
7997: }
7998: }
7999: unless ($noprint) {
8000: my $symb = &Apache::lonnet::symbread();
8001: if ($symb ne '') {
8002: my $navmap = Apache::lonnavmaps::navmap->new();
8003: if (ref($navmap)) {
8004: my $res = $navmap->getBySymb($symb);
8005: if (ref($res)) {
8006: if (!$res->resprintable()) {
8007: $noprint = 1;
8008: }
8009: }
8010: }
8011: }
8012: }
8013: if ($noprint) {
8014: return <<"ENDSTYLE";
8015: <style type="text/css" media="print">
8016: body { display:none }
8017: </style>
8018: ENDSTYLE
8019: }
8020: }
8021: return;
8022: }
8023:
8024: =pod
8025:
8026: =item * &xml_begin()
8027:
8028: Returns the needed doctype and <html>
8029:
8030: Inputs: none
8031:
8032: =cut
8033:
8034: sub xml_begin {
8035: my ($is_frameset) = @_;
8036: my $output='';
8037:
8038: if ($env{'browser.mathml'}) {
8039: $output='<?xml version="1.0"?>'
8040: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8041: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8042:
8043: # .'<!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">] >'
8044: .'<!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">'
8045: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8046: .'xmlns="http://www.w3.org/1999/xhtml">';
8047: } elsif ($is_frameset) {
8048: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8049: '<html>'."\n";
8050: } else {
8051: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8052: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8053: }
8054: return $output;
8055: }
8056:
8057: =pod
8058:
8059: =item * &start_page()
8060:
8061: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8062:
8063: Inputs:
8064:
8065: =over 4
8066:
8067: $title - optional title for the page
8068:
8069: $head_extra - optional extra HTML to incude inside the <head>
8070:
8071: $args - additional optional args supported are:
8072:
8073: =over 8
8074:
8075: only_body -> is true will set &bodytag() onlybodytag
8076: arg on
8077: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8078: add_entries -> additional attributes to add to the <body>
8079: domain -> force to color decorate a page for a
8080: specific domain
8081: function -> force usage of a specific rolish color
8082: scheme
8083: redirect -> see &headtag()
8084: bgcolor -> override the default page bg color
8085: js_ready -> return a string ready for being used in
8086: a javascript writeln
8087: html_encode -> return a string ready for being used in
8088: a html attribute
8089: force_register -> if is true will turn on the &bodytag()
8090: $forcereg arg
8091: frameset -> if true will start with a <frameset>
8092: rather than <body>
8093: skip_phases -> hash ref of
8094: head -> skip the <html><head> generation
8095: body -> skip all <body> generation
8096: no_inline_link -> if true and in remote mode, don't show the
8097: 'Switch To Inline Menu' link
8098: no_auto_mt_title -> prevent &mt()ing the title arg
8099: bread_crumbs -> Array containing breadcrumbs
8100: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8101: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
8102: to lonhtmlcommon::breadcrumbs
8103: group -> includes the current group, if page is for a
8104: specific group
8105: use_absolute -> for request for external resource or syllabus, this
8106: will contain https://<hostname> if server uses
8107: https (as per hosts.tab), but request is for http
8108: hostname -> hostname, originally from $r->hostname(), (optional).
8109:
8110: =back
8111:
8112: =back
8113:
8114: =cut
8115:
8116: sub start_page {
8117: my ($title,$head_extra,$args) = @_;
8118: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8119:
8120: $env{'internal.start_page'}++;
8121: my ($result,@advtools);
8122:
8123: if (! exists($args->{'skip_phases'}{'head'}) ) {
8124: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8125: }
8126:
8127: if (! exists($args->{'skip_phases'}{'body'}) ) {
8128: if ($args->{'frameset'}) {
8129: my $attr_string = &make_attr_string($args->{'force_register'},
8130: $args->{'add_entries'});
8131: $result .= "\n<frameset $attr_string>\n";
8132: } else {
8133: $result .=
8134: &bodytag($title,
8135: $args->{'function'}, $args->{'add_entries'},
8136: $args->{'only_body'}, $args->{'domain'},
8137: $args->{'force_register'}, $args->{'no_nav_bar'},
8138: $args->{'bgcolor'}, $args->{'no_inline_link'},
8139: $args, \@advtools);
8140: }
8141: }
8142:
8143: if ($args->{'js_ready'}) {
8144: $result = &js_ready($result);
8145: }
8146: if ($args->{'html_encode'}) {
8147: $result = &html_encode($result);
8148: }
8149:
8150: # Preparation for new and consistent functionlist at top of screen
8151: # if ($args->{'functionlist'}) {
8152: # $result .= &build_functionlist();
8153: #}
8154:
8155: # Don't add anything more if only_body wanted or in const space
8156: return $result if $args->{'only_body'}
8157: || $env{'request.state'} eq 'construct';
8158:
8159: #Breadcrumbs
8160: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8161: &Apache::lonhtmlcommon::clear_breadcrumbs();
8162: #if any br links exists, add them to the breadcrumbs
8163: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8164: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8165: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8166: }
8167: }
8168: # if @advtools array contains items add then to the breadcrumbs
8169: if (@advtools > 0) {
8170: &Apache::lonmenu::advtools_crumbs(@advtools);
8171: }
8172: my $menulink;
8173: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
8174: if (exists($args->{'bread_crumbs_nomenu'})) {
8175: $menulink = 0;
8176: } else {
8177: undef($menulink);
8178: }
8179: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8180: if(exists($args->{'bread_crumbs_component'})){
8181: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
8182: }else{
8183: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
8184: }
8185: } elsif (($env{'environment.remote'} eq 'on') &&
8186: ($env{'form.inhibitmenu'} ne 'yes') &&
8187: ($env{'request.noversionuri'} =~ m{^/res/}) &&
8188: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
8189: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
8190: }
8191: return $result;
8192: }
8193:
8194: sub end_page {
8195: my ($args) = @_;
8196: $env{'internal.end_page'}++;
8197: my $result;
8198: if ($args->{'discussion'}) {
8199: my ($target,$parser);
8200: if (ref($args->{'discussion'})) {
8201: ($target,$parser) =($args->{'discussion'}{'target'},
8202: $args->{'discussion'}{'parser'});
8203: }
8204: $result .= &Apache::lonxml::xmlend($target,$parser);
8205: }
8206: if ($args->{'frameset'}) {
8207: $result .= '</frameset>';
8208: } else {
8209: $result .= &endbodytag($args);
8210: }
8211: unless ($args->{'notbody'}) {
8212: $result .= "\n</html>";
8213: }
8214:
8215: if ($args->{'js_ready'}) {
8216: $result = &js_ready($result);
8217: }
8218:
8219: if ($args->{'html_encode'}) {
8220: $result = &html_encode($result);
8221: }
8222:
8223: return $result;
8224: }
8225:
8226: sub wishlist_window {
8227: return(<<'ENDWISHLIST');
8228: <script type="text/javascript">
8229: // <![CDATA[
8230: // <!-- BEGIN LON-CAPA Internal
8231: function set_wishlistlink(title, path) {
8232: if (!title) {
8233: title = document.title;
8234: title = title.replace(/^LON-CAPA /,'');
8235: }
8236: title = encodeURIComponent(title);
8237: title = title.replace("'","\\\'");
8238: if (!path) {
8239: path = location.pathname;
8240: }
8241: path = encodeURIComponent(path);
8242: path = path.replace("'","\\\'");
8243: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8244: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8245: }
8246: // END LON-CAPA Internal -->
8247: // ]]>
8248: </script>
8249: ENDWISHLIST
8250: }
8251:
8252: sub modal_window {
8253: return(<<'ENDMODAL');
8254: <script type="text/javascript">
8255: // <![CDATA[
8256: // <!-- BEGIN LON-CAPA Internal
8257: var modalWindow = {
8258: parent:"body",
8259: windowId:null,
8260: content:null,
8261: width:null,
8262: height:null,
8263: close:function()
8264: {
8265: $(".LCmodal-window").remove();
8266: $(".LCmodal-overlay").remove();
8267: },
8268: open:function()
8269: {
8270: var modal = "";
8271: modal += "<div class=\"LCmodal-overlay\"></div>";
8272: 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;\">";
8273: modal += this.content;
8274: modal += "</div>";
8275:
8276: $(this.parent).append(modal);
8277:
8278: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8279: $(".LCclose-window").click(function(){modalWindow.close();});
8280: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8281: }
8282: };
8283: var openMyModal = function(source,width,height,scrolling,transparency,style)
8284: {
8285: source = source.replace(/'/g,"'");
8286: modalWindow.windowId = "myModal";
8287: modalWindow.width = width;
8288: modalWindow.height = height;
8289: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8290: modalWindow.open();
8291: };
8292: // END LON-CAPA Internal -->
8293: // ]]>
8294: </script>
8295: ENDMODAL
8296: }
8297:
8298: sub modal_link {
8299: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8300: unless ($width) { $width=480; }
8301: unless ($height) { $height=400; }
8302: unless ($scrolling) { $scrolling='yes'; }
8303: unless ($transparency) { $transparency='true'; }
8304:
8305: my $target_attr;
8306: if (defined($target)) {
8307: $target_attr = 'target="'.$target.'"';
8308: }
8309: return <<"ENDLINK";
8310: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
8311: $linktext</a>
8312: ENDLINK
8313: }
8314:
8315: sub modal_adhoc_script {
8316: my ($funcname,$width,$height,$content)=@_;
8317: return (<<ENDADHOC);
8318: <script type="text/javascript">
8319: // <![CDATA[
8320: var $funcname = function()
8321: {
8322: modalWindow.windowId = "myModal";
8323: modalWindow.width = $width;
8324: modalWindow.height = $height;
8325: modalWindow.content = '$content';
8326: modalWindow.open();
8327: };
8328: // ]]>
8329: </script>
8330: ENDADHOC
8331: }
8332:
8333: sub modal_adhoc_inner {
8334: my ($funcname,$width,$height,$content)=@_;
8335: my $innerwidth=$width-20;
8336: $content=&js_ready(
8337: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8338: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8339: $content.
8340: &end_scrollbox().
8341: &end_page()
8342: );
8343: return &modal_adhoc_script($funcname,$width,$height,$content);
8344: }
8345:
8346: sub modal_adhoc_window {
8347: my ($funcname,$width,$height,$content,$linktext)=@_;
8348: return &modal_adhoc_inner($funcname,$width,$height,$content).
8349: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8350: }
8351:
8352: sub modal_adhoc_launch {
8353: my ($funcname,$width,$height,$content)=@_;
8354: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8355: <script type="text/javascript">
8356: // <![CDATA[
8357: $funcname();
8358: // ]]>
8359: </script>
8360: ENDLAUNCH
8361: }
8362:
8363: sub modal_adhoc_close {
8364: return (<<ENDCLOSE);
8365: <script type="text/javascript">
8366: // <![CDATA[
8367: modalWindow.close();
8368: // ]]>
8369: </script>
8370: ENDCLOSE
8371: }
8372:
8373: sub togglebox_script {
8374: return(<<ENDTOGGLE);
8375: <script type="text/javascript">
8376: // <![CDATA[
8377: function LCtoggleDisplay(id,hidetext,showtext) {
8378: link = document.getElementById(id + "link").childNodes[0];
8379: with (document.getElementById(id).style) {
8380: if (display == "none" ) {
8381: display = "inline";
8382: link.nodeValue = hidetext;
8383: } else {
8384: display = "none";
8385: link.nodeValue = showtext;
8386: }
8387: }
8388: }
8389: // ]]>
8390: </script>
8391: ENDTOGGLE
8392: }
8393:
8394: sub start_togglebox {
8395: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8396: unless ($heading) { $heading=''; } else { $heading.=' '; }
8397: unless ($showtext) { $showtext=&mt('show'); }
8398: unless ($hidetext) { $hidetext=&mt('hide'); }
8399: unless ($headerbg) { $headerbg='#FFFFFF'; }
8400: return &start_data_table().
8401: &start_data_table_header_row().
8402: '<td bgcolor="'.$headerbg.'">'.$heading.
8403: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8404: $showtext.'\')">'.$showtext.'</a>]</td>'.
8405: &end_data_table_header_row().
8406: '<tr id="'.$id.'" style="display:none""><td>';
8407: }
8408:
8409: sub end_togglebox {
8410: return '</td></tr>'.&end_data_table();
8411: }
8412:
8413: sub LCprogressbar_script {
8414: my ($id,$number_to_do)=@_;
8415: if ($number_to_do) {
8416: return(<<ENDPROGRESS);
8417: <script type="text/javascript">
8418: // <![CDATA[
8419: \$('#progressbar$id').progressbar({
8420: value: 0,
8421: change: function(event, ui) {
8422: var newVal = \$(this).progressbar('option', 'value');
8423: \$('.pblabel', this).text(LCprogressTxt);
8424: }
8425: });
8426: // ]]>
8427: </script>
8428: ENDPROGRESS
8429: } else {
8430: return(<<ENDPROGRESS);
8431: <script type="text/javascript">
8432: // <![CDATA[
8433: \$('#progressbar$id').progressbar({
8434: value: false,
8435: create: function(event, ui) {
8436: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
8437: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
8438: }
8439: });
8440: // ]]>
8441: </script>
8442: ENDPROGRESS
8443: }
8444: }
8445:
8446: sub LCprogressbarUpdate_script {
8447: return(<<ENDPROGRESSUPDATE);
8448: <style type="text/css">
8449: .ui-progressbar { position:relative; }
8450: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
8451: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
8452: </style>
8453: <script type="text/javascript">
8454: // <![CDATA[
8455: var LCprogressTxt='---';
8456:
8457: function LCupdateProgress(percent,progresstext,id,maxnum) {
8458: LCprogressTxt=progresstext;
8459: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
8460: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
8461: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
8462: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
8463: } else {
8464: \$('#progressbar'+id).progressbar('value',percent);
8465: }
8466: }
8467: // ]]>
8468: </script>
8469: ENDPROGRESSUPDATE
8470: }
8471:
8472: my $LClastpercent;
8473: my $LCidcnt;
8474: my $LCcurrentid;
8475:
8476: sub LCprogressbar {
8477: my ($r,$number_to_do,$preamble)=@_;
8478: $LClastpercent=0;
8479: $LCidcnt++;
8480: $LCcurrentid=$$.'_'.$LCidcnt;
8481: my ($starting,$content);
8482: if ($number_to_do) {
8483: $starting=&mt('Starting');
8484: $content=(<<ENDPROGBAR);
8485: $preamble
8486: <div id="progressbar$LCcurrentid">
8487: <span class="pblabel">$starting</span>
8488: </div>
8489: ENDPROGBAR
8490: } else {
8491: $starting=&mt('Loading...');
8492: $LClastpercent='false';
8493: $content=(<<ENDPROGBAR);
8494: $preamble
8495: <div id="progressbar$LCcurrentid">
8496: <div class="progress-label">$starting</div>
8497: </div>
8498: ENDPROGBAR
8499: }
8500: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
8501: }
8502:
8503: sub LCprogressbarUpdate {
8504: my ($r,$val,$text,$number_to_do)=@_;
8505: if ($number_to_do) {
8506: unless ($val) {
8507: if ($LClastpercent) {
8508: $val=$LClastpercent;
8509: } else {
8510: $val=0;
8511: }
8512: }
8513: if ($val<0) { $val=0; }
8514: if ($val>100) { $val=0; }
8515: $LClastpercent=$val;
8516: unless ($text) { $text=$val.'%'; }
8517: } else {
8518: $val = 'false';
8519: }
8520: $text=&js_ready($text);
8521: &r_print($r,<<ENDUPDATE);
8522: <script type="text/javascript">
8523: // <![CDATA[
8524: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
8525: // ]]>
8526: </script>
8527: ENDUPDATE
8528: }
8529:
8530: sub LCprogressbarClose {
8531: my ($r)=@_;
8532: $LClastpercent=0;
8533: &r_print($r,<<ENDCLOSE);
8534: <script type="text/javascript">
8535: // <![CDATA[
8536: \$("#progressbar$LCcurrentid").hide('slow');
8537: // ]]>
8538: </script>
8539: ENDCLOSE
8540: }
8541:
8542: sub r_print {
8543: my ($r,$to_print)=@_;
8544: if ($r) {
8545: $r->print($to_print);
8546: $r->rflush();
8547: } else {
8548: print($to_print);
8549: }
8550: }
8551:
8552: sub html_encode {
8553: my ($result) = @_;
8554:
8555: $result = &HTML::Entities::encode($result,'<>&"');
8556:
8557: return $result;
8558: }
8559:
8560: sub js_ready {
8561: my ($result) = @_;
8562:
8563: $result =~ s/[\n\r]/ /xmsg;
8564: $result =~ s/\\/\\\\/xmsg;
8565: $result =~ s/'/\\'/xmsg;
8566: $result =~ s{</}{<\\/}xmsg;
8567:
8568: return $result;
8569: }
8570:
8571: sub validate_page {
8572: if ( exists($env{'internal.start_page'})
8573: && $env{'internal.start_page'} > 1) {
8574: &Apache::lonnet::logthis('start_page called multiple times '.
8575: $env{'internal.start_page'}.' '.
8576: $ENV{'request.filename'});
8577: }
8578: if ( exists($env{'internal.end_page'})
8579: && $env{'internal.end_page'} > 1) {
8580: &Apache::lonnet::logthis('end_page called multiple times '.
8581: $env{'internal.end_page'}.' '.
8582: $env{'request.filename'});
8583: }
8584: if ( exists($env{'internal.start_page'})
8585: && ! exists($env{'internal.end_page'})) {
8586: &Apache::lonnet::logthis('start_page called without end_page '.
8587: $env{'request.filename'});
8588: }
8589: if ( ! exists($env{'internal.start_page'})
8590: && exists($env{'internal.end_page'})) {
8591: &Apache::lonnet::logthis('end_page called without start_page'.
8592: $env{'request.filename'});
8593: }
8594: }
8595:
8596:
8597: sub start_scrollbox {
8598: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8599: unless ($outerwidth) { $outerwidth='520px'; }
8600: unless ($width) { $width='500px'; }
8601: unless ($height) { $height='200px'; }
8602: my ($table_id,$div_id,$tdcol);
8603: if ($id ne '') {
8604: $table_id = ' id="table_'.$id.'"';
8605: $div_id = ' id="div_'.$id.'"';
8606: }
8607: if ($bgcolor ne '') {
8608: $tdcol = "background-color: $bgcolor;";
8609: }
8610: my $nicescroll_js;
8611: if ($env{'browser.mobile'}) {
8612: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8613: }
8614: return <<"END";
8615: $nicescroll_js
8616:
8617: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8618: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8619: END
8620: }
8621:
8622: sub end_scrollbox {
8623: return '</div></td></tr></table>';
8624: }
8625:
8626: sub nicescroll_javascript {
8627: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8628: my %options;
8629: if (ref($cursor) eq 'HASH') {
8630: %options = %{$cursor};
8631: }
8632: unless ($options{'railalign'} =~ /^left|right$/) {
8633: $options{'railalign'} = 'left';
8634: }
8635: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8636: my $function = &get_users_function();
8637: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8638: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8639: $options{'cursorcolor'} = '#00F';
8640: }
8641: }
8642: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8643: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8644: $options{'cursoropacity'}='1.0';
8645: }
8646: } else {
8647: $options{'cursoropacity'}='1.0';
8648: }
8649: if ($options{'cursorfixedheight'} eq 'none') {
8650: delete($options{'cursorfixedheight'});
8651: } else {
8652: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8653: }
8654: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8655: delete($options{'railoffset'});
8656: }
8657: my @niceoptions;
8658: while (my($key,$value) = each(%options)) {
8659: if ($value =~ /^\{.+\}$/) {
8660: push(@niceoptions,$key.':'.$value);
8661: } else {
8662: push(@niceoptions,$key.':"'.$value.'"');
8663: }
8664: }
8665: my $nicescroll_js = '
8666: $(document).ready(
8667: function() {
8668: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8669: }
8670: );
8671: ';
8672: if ($framecheck) {
8673: $nicescroll_js .= '
8674: function expand_div(caller) {
8675: if (top === self) {
8676: document.getElementById("'.$id.'").style.width = "auto";
8677: document.getElementById("'.$id.'").style.height = "auto";
8678: } else {
8679: try {
8680: if (parent.frames) {
8681: if (parent.frames.length > 1) {
8682: var framesrc = parent.frames[1].location.href;
8683: var currsrc = framesrc.replace(/\#.*$/,"");
8684: if ((caller == "search") || (currsrc == "'.$location.'")) {
8685: document.getElementById("'.$id.'").style.width = "auto";
8686: document.getElementById("'.$id.'").style.height = "auto";
8687: }
8688: }
8689: }
8690: } catch (e) {
8691: return;
8692: }
8693: }
8694: return;
8695: }
8696: ';
8697: }
8698: if ($needjsready) {
8699: $nicescroll_js = '
8700: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8701: } else {
8702: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8703: }
8704: return $nicescroll_js;
8705: }
8706:
8707: sub simple_error_page {
8708: my ($r,$title,$msg,$args) = @_;
8709: if (ref($args) eq 'HASH') {
8710: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8711: } else {
8712: $msg = &mt($msg);
8713: }
8714:
8715: my $page =
8716: &Apache::loncommon::start_page($title).
8717: '<p class="LC_error">'.$msg.'</p>'.
8718: &Apache::loncommon::end_page();
8719: if (ref($r)) {
8720: $r->print($page);
8721: return;
8722: }
8723: return $page;
8724: }
8725:
8726: {
8727: my @row_count;
8728:
8729: sub start_data_table_count {
8730: unshift(@row_count, 0);
8731: return;
8732: }
8733:
8734: sub end_data_table_count {
8735: shift(@row_count);
8736: return;
8737: }
8738:
8739: sub start_data_table {
8740: my ($add_class,$id) = @_;
8741: my $css_class = (join(' ','LC_data_table',$add_class));
8742: my $table_id;
8743: if (defined($id)) {
8744: $table_id = ' id="'.$id.'"';
8745: }
8746: &start_data_table_count();
8747: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8748: }
8749:
8750: sub end_data_table {
8751: &end_data_table_count();
8752: return '</table>'."\n";;
8753: }
8754:
8755: sub start_data_table_row {
8756: my ($add_class, $id) = @_;
8757: $row_count[0]++;
8758: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8759: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8760: $id = (' id="'.$id.'"') unless ($id eq '');
8761: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8762: }
8763:
8764: sub continue_data_table_row {
8765: my ($add_class, $id) = @_;
8766: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8767: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8768: $id = (' id="'.$id.'"') unless ($id eq '');
8769: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8770: }
8771:
8772: sub end_data_table_row {
8773: return '</tr>'."\n";;
8774: }
8775:
8776: sub start_data_table_empty_row {
8777: # $row_count[0]++;
8778: return '<tr class="LC_empty_row" >'."\n";;
8779: }
8780:
8781: sub end_data_table_empty_row {
8782: return '</tr>'."\n";;
8783: }
8784:
8785: sub start_data_table_header_row {
8786: return '<tr class="LC_header_row">'."\n";;
8787: }
8788:
8789: sub end_data_table_header_row {
8790: return '</tr>'."\n";;
8791: }
8792:
8793: sub data_table_caption {
8794: my $caption = shift;
8795: return "<caption class=\"LC_caption\">$caption</caption>";
8796: }
8797: }
8798:
8799: =pod
8800:
8801: =item * &inhibit_menu_check($arg)
8802:
8803: Checks for a inhibitmenu state and generates output to preserve it
8804:
8805: Inputs: $arg - can be any of
8806: - undef - in which case the return value is a string
8807: to add into arguments list of a uri
8808: - 'input' - in which case the return value is a HTML
8809: <form> <input> field of type hidden to
8810: preserve the value
8811: - a url - in which case the return value is the url with
8812: the neccesary cgi args added to preserve the
8813: inhibitmenu state
8814: - a ref to a url - no return value, but the string is
8815: updated to include the neccessary cgi
8816: args to preserve the inhibitmenu state
8817:
8818: =cut
8819:
8820: sub inhibit_menu_check {
8821: my ($arg) = @_;
8822: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8823: if ($arg eq 'input') {
8824: if ($env{'form.inhibitmenu'}) {
8825: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8826: } else {
8827: return
8828: }
8829: }
8830: if ($env{'form.inhibitmenu'}) {
8831: if (ref($arg)) {
8832: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8833: } elsif ($arg eq '') {
8834: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8835: } else {
8836: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8837: }
8838: }
8839: if (!ref($arg)) {
8840: return $arg;
8841: }
8842: }
8843:
8844: ###############################################
8845:
8846: =pod
8847:
8848: =back
8849:
8850: =head1 User Information Routines
8851:
8852: =over 4
8853:
8854: =item * &get_users_function()
8855:
8856: Used by &bodytag to determine the current users primary role.
8857: Returns either 'student','coordinator','admin', or 'author'.
8858:
8859: =cut
8860:
8861: ###############################################
8862: sub get_users_function {
8863: my $function = 'norole';
8864: if ($env{'request.role'}=~/^(st)/) {
8865: $function='student';
8866: }
8867: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8868: $function='coordinator';
8869: }
8870: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8871: $function='admin';
8872: }
8873: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8874: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8875: $function='author';
8876: }
8877: return $function;
8878: }
8879:
8880: ###############################################
8881:
8882: =pod
8883:
8884: =item * &show_course()
8885:
8886: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8887: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8888:
8889: Inputs:
8890: None
8891:
8892: Outputs:
8893: Scalar: 1 if 'Course' to be used, 0 otherwise.
8894:
8895: =cut
8896:
8897: ###############################################
8898: sub show_course {
8899: my $course = !$env{'user.adv'};
8900: if (!$env{'user.adv'}) {
8901: foreach my $env (keys(%env)) {
8902: next if ($env !~ m/^user\.priv\./);
8903: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8904: $course = 0;
8905: last;
8906: }
8907: }
8908: }
8909: return $course;
8910: }
8911:
8912: ###############################################
8913:
8914: =pod
8915:
8916: =item * &check_user_status()
8917:
8918: Determines current status of supplied role for a
8919: specific user. Roles can be active, previous or future.
8920:
8921: Inputs:
8922: user's domain, user's username, course's domain,
8923: course's number, optional section ID.
8924:
8925: Outputs:
8926: role status: active, previous or future.
8927:
8928: =cut
8929:
8930: sub check_user_status {
8931: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8932: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8933: my @uroles = keys(%userinfo);
8934: my $srchstr;
8935: my $active_chk = 'none';
8936: my $now = time;
8937: if (@uroles > 0) {
8938: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8939: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8940: } else {
8941: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8942: }
8943: if (grep/^\Q$srchstr\E$/,@uroles) {
8944: my $role_end = 0;
8945: my $role_start = 0;
8946: $active_chk = 'active';
8947: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8948: $role_end = $1;
8949: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8950: $role_start = $1;
8951: }
8952: }
8953: if ($role_start > 0) {
8954: if ($now < $role_start) {
8955: $active_chk = 'future';
8956: }
8957: }
8958: if ($role_end > 0) {
8959: if ($now > $role_end) {
8960: $active_chk = 'previous';
8961: }
8962: }
8963: }
8964: }
8965: return $active_chk;
8966: }
8967:
8968: ###############################################
8969:
8970: =pod
8971:
8972: =item * &get_sections()
8973:
8974: Determines all the sections for a course including
8975: sections with students and sections containing other roles.
8976: Incoming parameters:
8977:
8978: 1. domain
8979: 2. course number
8980: 3. reference to array containing roles for which sections should
8981: be gathered (optional).
8982: 4. reference to array containing status types for which sections
8983: should be gathered (optional).
8984:
8985: If the third argument is undefined, sections are gathered for any role.
8986: If the fourth argument is undefined, sections are gathered for any status.
8987: Permissible values are 'active' or 'future' or 'previous'.
8988:
8989: Returns section hash (keys are section IDs, values are
8990: number of users in each section), subject to the
8991: optional roles filter, optional status filter
8992:
8993: =cut
8994:
8995: ###############################################
8996: sub get_sections {
8997: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8998: if (!defined($cdom) || !defined($cnum)) {
8999: my $cid = $env{'request.course.id'};
9000:
9001: return if (!defined($cid));
9002:
9003: $cdom = $env{'course.'.$cid.'.domain'};
9004: $cnum = $env{'course.'.$cid.'.num'};
9005: }
9006:
9007: my %sectioncount;
9008: my $now = time;
9009:
9010: my $check_students = 1;
9011: my $only_students = 0;
9012: if (ref($possible_roles) eq 'ARRAY') {
9013: if (grep(/^st$/,@{$possible_roles})) {
9014: if (@{$possible_roles} == 1) {
9015: $only_students = 1;
9016: }
9017: } else {
9018: $check_students = 0;
9019: }
9020: }
9021:
9022: if ($check_students) {
9023: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9024: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9025: my $status_index = &Apache::loncoursedata::CL_STATUS();
9026: my $start_index = &Apache::loncoursedata::CL_START();
9027: my $end_index = &Apache::loncoursedata::CL_END();
9028: my $status;
9029: while (my ($student,$data) = each(%$classlist)) {
9030: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9031: $data->[$status_index],
9032: $data->[$start_index],
9033: $data->[$end_index]);
9034: if ($stu_status eq 'Active') {
9035: $status = 'active';
9036: } elsif ($end < $now) {
9037: $status = 'previous';
9038: } elsif ($start > $now) {
9039: $status = 'future';
9040: }
9041: if ($section ne '-1' && $section !~ /^\s*$/) {
9042: if ((!defined($possible_status)) || (($status ne '') &&
9043: (grep/^\Q$status\E$/,@{$possible_status}))) {
9044: $sectioncount{$section}++;
9045: }
9046: }
9047: }
9048: }
9049: if ($only_students) {
9050: return %sectioncount;
9051: }
9052: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9053: foreach my $user (sort(keys(%courseroles))) {
9054: if ($user !~ /^(\w{2})/) { next; }
9055: my ($role) = ($user =~ /^(\w{2})/);
9056: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9057: my ($section,$status);
9058: if ($role eq 'cr' &&
9059: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9060: $section=$1;
9061: }
9062: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9063: if (!defined($section) || $section eq '-1') { next; }
9064: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9065: if ($end == -1 && $start == -1) {
9066: next; #deleted role
9067: }
9068: if (!defined($possible_status)) {
9069: $sectioncount{$section}++;
9070: } else {
9071: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9072: $status = 'active';
9073: } elsif ($end < $now) {
9074: $status = 'future';
9075: } elsif ($start > $now) {
9076: $status = 'previous';
9077: }
9078: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9079: $sectioncount{$section}++;
9080: }
9081: }
9082: }
9083: return %sectioncount;
9084: }
9085:
9086: ###############################################
9087:
9088: =pod
9089:
9090: =item * &get_course_users()
9091:
9092: Retrieves usernames:domains for users in the specified course
9093: with specific role(s), and access status.
9094:
9095: Incoming parameters:
9096: 1. course domain
9097: 2. course number
9098: 3. access status: users must have - either active,
9099: previous, future, or all.
9100: 4. reference to array of permissible roles
9101: 5. reference to array of section restrictions (optional)
9102: 6. reference to results object (hash of hashes).
9103: 7. reference to optional userdata hash
9104: 8. reference to optional statushash
9105: 9. flag if privileged users (except those set to unhide in
9106: course settings) should be excluded
9107: Keys of top level results hash are roles.
9108: Keys of inner hashes are username:domain, with
9109: values set to access type.
9110: Optional userdata hash returns an array with arguments in the
9111: same order as loncoursedata::get_classlist() for student data.
9112:
9113: Optional statushash returns
9114:
9115: Entries for end, start, section and status are blank because
9116: of the possibility of multiple values for non-student roles.
9117:
9118: =cut
9119:
9120: ###############################################
9121:
9122: sub get_course_users {
9123: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9124: my %idx = ();
9125: my %seclists;
9126:
9127: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9128: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9129: $idx{end} = &Apache::loncoursedata::CL_END();
9130: $idx{start} = &Apache::loncoursedata::CL_START();
9131: $idx{id} = &Apache::loncoursedata::CL_ID();
9132: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9133: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9134: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9135:
9136: if (grep(/^st$/,@{$roles})) {
9137: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9138: my $now = time;
9139: foreach my $student (keys(%{$classlist})) {
9140: my $match = 0;
9141: my $secmatch = 0;
9142: my $section = $$classlist{$student}[$idx{section}];
9143: my $status = $$classlist{$student}[$idx{status}];
9144: if ($section eq '') {
9145: $section = 'none';
9146: }
9147: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9148: if (grep(/^all$/,@{$sections})) {
9149: $secmatch = 1;
9150: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9151: if (grep(/^none$/,@{$sections})) {
9152: $secmatch = 1;
9153: }
9154: } else {
9155: if (grep(/^\Q$section\E$/,@{$sections})) {
9156: $secmatch = 1;
9157: }
9158: }
9159: if (!$secmatch) {
9160: next;
9161: }
9162: }
9163: if (defined($$types{'active'})) {
9164: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9165: push(@{$$users{st}{$student}},'active');
9166: $match = 1;
9167: }
9168: }
9169: if (defined($$types{'previous'})) {
9170: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9171: push(@{$$users{st}{$student}},'previous');
9172: $match = 1;
9173: }
9174: }
9175: if (defined($$types{'future'})) {
9176: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9177: push(@{$$users{st}{$student}},'future');
9178: $match = 1;
9179: }
9180: }
9181: if ($match) {
9182: push(@{$seclists{$student}},$section);
9183: if (ref($userdata) eq 'HASH') {
9184: $$userdata{$student} = $$classlist{$student};
9185: }
9186: if (ref($statushash) eq 'HASH') {
9187: $statushash->{$student}{'st'}{$section} = $status;
9188: }
9189: }
9190: }
9191: }
9192: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9193: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9194: my $now = time;
9195: my %displaystatus = ( previous => 'Expired',
9196: active => 'Active',
9197: future => 'Future',
9198: );
9199: my (%nothide,@possdoms);
9200: if ($hidepriv) {
9201: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9202: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9203: if ($user !~ /:/) {
9204: $nothide{join(':',split(/[\@]/,$user))}=1;
9205: } else {
9206: $nothide{$user} = 1;
9207: }
9208: }
9209: my @possdoms = ($cdom);
9210: if ($coursehash{'checkforpriv'}) {
9211: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9212: }
9213: }
9214: foreach my $person (sort(keys(%coursepersonnel))) {
9215: my $match = 0;
9216: my $secmatch = 0;
9217: my $status;
9218: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9219: $user =~ s/:$//;
9220: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9221: if ($end == -1 || $start == -1) {
9222: next;
9223: }
9224: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9225: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9226: my ($uname,$udom) = split(/:/,$user);
9227: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9228: if (grep(/^all$/,@{$sections})) {
9229: $secmatch = 1;
9230: } elsif ($usec eq '') {
9231: if (grep(/^none$/,@{$sections})) {
9232: $secmatch = 1;
9233: }
9234: } else {
9235: if (grep(/^\Q$usec\E$/,@{$sections})) {
9236: $secmatch = 1;
9237: }
9238: }
9239: if (!$secmatch) {
9240: next;
9241: }
9242: }
9243: if ($usec eq '') {
9244: $usec = 'none';
9245: }
9246: if ($uname ne '' && $udom ne '') {
9247: if ($hidepriv) {
9248: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9249: (!$nothide{$uname.':'.$udom})) {
9250: next;
9251: }
9252: }
9253: if ($end > 0 && $end < $now) {
9254: $status = 'previous';
9255: } elsif ($start > $now) {
9256: $status = 'future';
9257: } else {
9258: $status = 'active';
9259: }
9260: foreach my $type (keys(%{$types})) {
9261: if ($status eq $type) {
9262: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9263: push(@{$$users{$role}{$user}},$type);
9264: }
9265: $match = 1;
9266: }
9267: }
9268: if (($match) && (ref($userdata) eq 'HASH')) {
9269: if (!exists($$userdata{$uname.':'.$udom})) {
9270: &get_user_info($udom,$uname,\%idx,$userdata);
9271: }
9272: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9273: push(@{$seclists{$uname.':'.$udom}},$usec);
9274: }
9275: if (ref($statushash) eq 'HASH') {
9276: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9277: }
9278: }
9279: }
9280: }
9281: }
9282: if (grep(/^ow$/,@{$roles})) {
9283: if ((defined($cdom)) && (defined($cnum))) {
9284: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9285: if ( defined($csettings{'internal.courseowner'}) ) {
9286: my $owner = $csettings{'internal.courseowner'};
9287: next if ($owner eq '');
9288: my ($ownername,$ownerdom);
9289: if ($owner =~ /^([^:]+):([^:]+)$/) {
9290: $ownername = $1;
9291: $ownerdom = $2;
9292: } else {
9293: $ownername = $owner;
9294: $ownerdom = $cdom;
9295: $owner = $ownername.':'.$ownerdom;
9296: }
9297: @{$$users{'ow'}{$owner}} = 'any';
9298: if (defined($userdata) &&
9299: !exists($$userdata{$owner})) {
9300: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9301: if (!grep(/^none$/,@{$seclists{$owner}})) {
9302: push(@{$seclists{$owner}},'none');
9303: }
9304: if (ref($statushash) eq 'HASH') {
9305: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9306: }
9307: }
9308: }
9309: }
9310: }
9311: foreach my $user (keys(%seclists)) {
9312: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9313: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9314: }
9315: }
9316: return;
9317: }
9318:
9319: sub get_user_info {
9320: my ($udom,$uname,$idx,$userdata) = @_;
9321: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9322: &plainname($uname,$udom,'lastname');
9323: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9324: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9325: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9326: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9327: return;
9328: }
9329:
9330: ###############################################
9331:
9332: =pod
9333:
9334: =item * &get_user_quota()
9335:
9336: Retrieves quota assigned for storage of user files.
9337: Default is to report quota for portfolio files.
9338:
9339: Incoming parameters:
9340: 1. user's username
9341: 2. user's domain
9342: 3. quota name - portfolio, author, or course
9343: (if no quota name provided, defaults to portfolio).
9344: 4. crstype - official, unofficial, textbook or community, if quota name is
9345: course
9346:
9347: Returns:
9348: 1. Disk quota (in MB) assigned to student.
9349: 2. (Optional) Type of setting: custom or default
9350: (individually assigned or default for user's
9351: institutional status).
9352: 3. (Optional) - User's institutional status (e.g., faculty, staff
9353: or student - types as defined in localenroll::inst_usertypes
9354: for user's domain, which determines default quota for user.
9355: 4. (Optional) - Default quota which would apply to the user.
9356:
9357: If a value has been stored in the user's environment,
9358: it will return that, otherwise it returns the maximal default
9359: defined for the user's institutional status(es) in the domain.
9360:
9361: =cut
9362:
9363: ###############################################
9364:
9365:
9366: sub get_user_quota {
9367: my ($uname,$udom,$quotaname,$crstype) = @_;
9368: my ($quota,$quotatype,$settingstatus,$defquota);
9369: if (!defined($udom)) {
9370: $udom = $env{'user.domain'};
9371: }
9372: if (!defined($uname)) {
9373: $uname = $env{'user.name'};
9374: }
9375: if (($udom eq '' || $uname eq '') ||
9376: ($udom eq 'public') && ($uname eq 'public')) {
9377: $quota = 0;
9378: $quotatype = 'default';
9379: $defquota = 0;
9380: } else {
9381: my $inststatus;
9382: if ($quotaname eq 'course') {
9383: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9384: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9385: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9386: } else {
9387: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9388: $quota = $cenv{'internal.uploadquota'};
9389: }
9390: } else {
9391: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9392: if ($quotaname eq 'author') {
9393: $quota = $env{'environment.authorquota'};
9394: } else {
9395: $quota = $env{'environment.portfolioquota'};
9396: }
9397: $inststatus = $env{'environment.inststatus'};
9398: } else {
9399: my %userenv =
9400: &Apache::lonnet::get('environment',['portfolioquota',
9401: 'authorquota','inststatus'],$udom,$uname);
9402: my ($tmp) = keys(%userenv);
9403: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9404: if ($quotaname eq 'author') {
9405: $quota = $userenv{'authorquota'};
9406: } else {
9407: $quota = $userenv{'portfolioquota'};
9408: }
9409: $inststatus = $userenv{'inststatus'};
9410: } else {
9411: undef(%userenv);
9412: }
9413: }
9414: }
9415: if ($quota eq '' || wantarray) {
9416: if ($quotaname eq 'course') {
9417: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9418: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9419: ($crstype eq 'community') || ($crstype eq 'textbook')) {
9420: $defquota = $domdefs{$crstype.'quota'};
9421: }
9422: if ($defquota eq '') {
9423: $defquota = 500;
9424: }
9425: } else {
9426: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9427: }
9428: if ($quota eq '') {
9429: $quota = $defquota;
9430: $quotatype = 'default';
9431: } else {
9432: $quotatype = 'custom';
9433: }
9434: }
9435: }
9436: if (wantarray) {
9437: return ($quota,$quotatype,$settingstatus,$defquota);
9438: } else {
9439: return $quota;
9440: }
9441: }
9442:
9443: ###############################################
9444:
9445: =pod
9446:
9447: =item * &default_quota()
9448:
9449: Retrieves default quota assigned for storage of user portfolio files,
9450: given an (optional) user's institutional status.
9451:
9452: Incoming parameters:
9453:
9454: 1. domain
9455: 2. (Optional) institutional status(es). This is a : separated list of
9456: status types (e.g., faculty, staff, student etc.)
9457: which apply to the user for whom the default is being retrieved.
9458: If the institutional status string in undefined, the domain
9459: default quota will be returned.
9460: 3. quota name - portfolio, author, or course
9461: (if no quota name provided, defaults to portfolio).
9462:
9463: Returns:
9464:
9465: 1. Default disk quota (in MB) for user portfolios in the domain.
9466: 2. (Optional) institutional type which determined the value of the
9467: default quota.
9468:
9469: If a value has been stored in the domain's configuration db,
9470: it will return that, otherwise it returns 20 (for backwards
9471: compatibility with domains which have not set up a configuration
9472: db file; the original statically defined portfolio quota was 20 MB).
9473:
9474: If the user's status includes multiple types (e.g., staff and student),
9475: the largest default quota which applies to the user determines the
9476: default quota returned.
9477:
9478: =cut
9479:
9480: ###############################################
9481:
9482:
9483: sub default_quota {
9484: my ($udom,$inststatus,$quotaname) = @_;
9485: my ($defquota,$settingstatus);
9486: my %quotahash = &Apache::lonnet::get_dom('configuration',
9487: ['quotas'],$udom);
9488: my $key = 'defaultquota';
9489: if ($quotaname eq 'author') {
9490: $key = 'authorquota';
9491: }
9492: if (ref($quotahash{'quotas'}) eq 'HASH') {
9493: if ($inststatus ne '') {
9494: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
9495: foreach my $item (@statuses) {
9496: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9497: if ($quotahash{'quotas'}{$key}{$item} ne '') {
9498: if ($defquota eq '') {
9499: $defquota = $quotahash{'quotas'}{$key}{$item};
9500: $settingstatus = $item;
9501: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
9502: $defquota = $quotahash{'quotas'}{$key}{$item};
9503: $settingstatus = $item;
9504: }
9505: }
9506: } elsif ($key eq 'defaultquota') {
9507: if ($quotahash{'quotas'}{$item} ne '') {
9508: if ($defquota eq '') {
9509: $defquota = $quotahash{'quotas'}{$item};
9510: $settingstatus = $item;
9511: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
9512: $defquota = $quotahash{'quotas'}{$item};
9513: $settingstatus = $item;
9514: }
9515: }
9516: }
9517: }
9518: }
9519: if ($defquota eq '') {
9520: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9521: $defquota = $quotahash{'quotas'}{$key}{'default'};
9522: } elsif ($key eq 'defaultquota') {
9523: $defquota = $quotahash{'quotas'}{'default'};
9524: }
9525: $settingstatus = 'default';
9526: if ($defquota eq '') {
9527: if ($quotaname eq 'author') {
9528: $defquota = 500;
9529: }
9530: }
9531: }
9532: } else {
9533: $settingstatus = 'default';
9534: if ($quotaname eq 'author') {
9535: $defquota = 500;
9536: } else {
9537: $defquota = 20;
9538: }
9539: }
9540: if (wantarray) {
9541: return ($defquota,$settingstatus);
9542: } else {
9543: return $defquota;
9544: }
9545: }
9546:
9547: ###############################################
9548:
9549: =pod
9550:
9551: =item * &excess_filesize_warning()
9552:
9553: Returns warning message if upload of file to authoring space, or copying
9554: of existing file within authoring space will cause quota for the authoring
9555: space to be exceeded.
9556:
9557: Same, if upload of a file directly to a course/community via Course Editor
9558: will cause quota for uploaded content for the course to be exceeded.
9559:
9560: Inputs: 7
9561: 1. username or coursenum
9562: 2. domain
9563: 3. context ('author' or 'course')
9564: 4. filename of file for which action is being requested
9565: 5. filesize (kB) of file
9566: 6. action being taken: copy or upload.
9567: 7. quotatype (in course context -- official, unofficial, community or textbook).
9568:
9569: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9570: otherwise return null.
9571:
9572: =back
9573:
9574: =cut
9575:
9576: sub excess_filesize_warning {
9577: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9578: my $current_disk_usage = 0;
9579: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9580: if ($context eq 'author') {
9581: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9582: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9583: } else {
9584: foreach my $subdir ('docs','supplemental') {
9585: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9586: }
9587: }
9588: $disk_quota = int($disk_quota * 1000);
9589: if (($current_disk_usage + $filesize) > $disk_quota) {
9590: return '<p class="LC_warning">'.
9591: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9592: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9593: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9594: $disk_quota,$current_disk_usage).
9595: '</p>';
9596: }
9597: return;
9598: }
9599:
9600: ###############################################
9601:
9602:
9603: sub get_secgrprole_info {
9604: my ($cdom,$cnum,$needroles,$type) = @_;
9605: my %sections_count = &get_sections($cdom,$cnum);
9606: my @sections = (sort {$a <=> $b} keys(%sections_count));
9607: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9608: my @groups = sort(keys(%curr_groups));
9609: my $allroles = [];
9610: my $rolehash;
9611: my $accesshash = {
9612: active => 'Currently has access',
9613: future => 'Will have future access',
9614: previous => 'Previously had access',
9615: };
9616: if ($needroles) {
9617: $rolehash = {'all' => 'all'};
9618: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9619: if (&Apache::lonnet::error(%user_roles)) {
9620: undef(%user_roles);
9621: }
9622: foreach my $item (keys(%user_roles)) {
9623: my ($role)=split(/\:/,$item,2);
9624: if ($role eq 'cr') { next; }
9625: if ($role =~ /^cr/) {
9626: $$rolehash{$role} = (split('/',$role))[3];
9627: } else {
9628: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9629: }
9630: }
9631: foreach my $key (sort(keys(%{$rolehash}))) {
9632: push(@{$allroles},$key);
9633: }
9634: push (@{$allroles},'st');
9635: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9636: }
9637: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9638: }
9639:
9640: sub user_picker {
9641: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
9642: my $currdom = $dom;
9643: my @alldoms = &Apache::lonnet::all_domains();
9644: if (@alldoms == 1) {
9645: my %domsrch = &Apache::lonnet::get_dom('configuration',
9646: ['directorysrch'],$alldoms[0]);
9647: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
9648: my $showdom = $domdesc;
9649: if ($showdom eq '') {
9650: $showdom = $dom;
9651: }
9652: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
9653: if ((!$domsrch{'directorysrch'}{'available'}) &&
9654: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
9655: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
9656: }
9657: }
9658: }
9659: my %curr_selected = (
9660: srchin => 'dom',
9661: srchby => 'lastname',
9662: );
9663: my $srchterm;
9664: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9665: if ($srch->{'srchby'} ne '') {
9666: $curr_selected{'srchby'} = $srch->{'srchby'};
9667: }
9668: if ($srch->{'srchin'} ne '') {
9669: $curr_selected{'srchin'} = $srch->{'srchin'};
9670: }
9671: if ($srch->{'srchtype'} ne '') {
9672: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9673: }
9674: if ($srch->{'srchdomain'} ne '') {
9675: $currdom = $srch->{'srchdomain'};
9676: }
9677: $srchterm = $srch->{'srchterm'};
9678: }
9679: my %html_lt=&Apache::lonlocal::texthash(
9680: 'usr' => 'Search criteria',
9681: 'doma' => 'Domain/institution to search',
9682: 'uname' => 'username',
9683: 'lastname' => 'last name',
9684: 'lastfirst' => 'last name, first name',
9685: 'crs' => 'in this course',
9686: 'dom' => 'in selected LON-CAPA domain',
9687: 'alc' => 'all LON-CAPA',
9688: 'instd' => 'in institutional directory for selected domain',
9689: 'exact' => 'is',
9690: 'contains' => 'contains',
9691: 'begins' => 'begins with',
9692: );
9693: my %js_lt=&Apache::lonlocal::texthash(
9694: 'youm' => "You must include some text to search for.",
9695: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9696: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9697: 'yomc' => "You must choose a domain when using an institutional directory search.",
9698: 'ymcd' => "You must choose a domain when using a domain search.",
9699: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9700: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9701: 'thfo' => "The following need to be corrected before the search can be run:",
9702: );
9703: &html_escape(\%html_lt);
9704: &js_escape(\%js_lt);
9705: my $domform;
9706: my $allow_blank = 1;
9707: if ($fixeddom) {
9708: $allow_blank = 0;
9709: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
9710: } else {
9711: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
9712: }
9713: my $srchinsel = ' <select name="srchin">';
9714:
9715: my @srchins = ('crs','dom','alc','instd');
9716:
9717: foreach my $option (@srchins) {
9718: # FIXME 'alc' option unavailable until
9719: # loncreateuser::print_user_query_page()
9720: # has been completed.
9721: next if ($option eq 'alc');
9722: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9723: next if ($option eq 'crs' && !$env{'request.course.id'});
9724: next if (($option eq 'instd') && ($noinstd));
9725: if ($curr_selected{'srchin'} eq $option) {
9726: $srchinsel .= '
9727: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9728: } else {
9729: $srchinsel .= '
9730: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9731: }
9732: }
9733: $srchinsel .= "\n </select>\n";
9734:
9735: my $srchbysel = ' <select name="srchby">';
9736: foreach my $option ('lastname','lastfirst','uname') {
9737: if ($curr_selected{'srchby'} eq $option) {
9738: $srchbysel .= '
9739: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9740: } else {
9741: $srchbysel .= '
9742: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9743: }
9744: }
9745: $srchbysel .= "\n </select>\n";
9746:
9747: my $srchtypesel = ' <select name="srchtype">';
9748: foreach my $option ('begins','contains','exact') {
9749: if ($curr_selected{'srchtype'} eq $option) {
9750: $srchtypesel .= '
9751: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9752: } else {
9753: $srchtypesel .= '
9754: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9755: }
9756: }
9757: $srchtypesel .= "\n </select>\n";
9758:
9759: my ($newuserscript,$new_user_create);
9760: my $context_dom = $env{'request.role.domain'};
9761: if ($context eq 'requestcrs') {
9762: if ($env{'form.coursedom'} ne '') {
9763: $context_dom = $env{'form.coursedom'};
9764: }
9765: }
9766: if ($forcenewuser) {
9767: if (ref($srch) eq 'HASH') {
9768: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9769: if ($cancreate) {
9770: $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>';
9771: } else {
9772: my $helplink = 'javascript:helpMenu('."'display'".')';
9773: my %usertypetext = (
9774: official => 'institutional',
9775: unofficial => 'non-institutional',
9776: );
9777: $new_user_create = '<p class="LC_warning">'
9778: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9779: .' '
9780: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9781: ,'<a href="'.$helplink.'">','</a>')
9782: .'</p><br />';
9783: }
9784: }
9785: }
9786:
9787: $newuserscript = <<"ENDSCRIPT";
9788:
9789: function setSearch(createnew,callingForm) {
9790: if (createnew == 1) {
9791: for (var i=0; i<callingForm.srchby.length; i++) {
9792: if (callingForm.srchby.options[i].value == 'uname') {
9793: callingForm.srchby.selectedIndex = i;
9794: }
9795: }
9796: for (var i=0; i<callingForm.srchin.length; i++) {
9797: if ( callingForm.srchin.options[i].value == 'dom') {
9798: callingForm.srchin.selectedIndex = i;
9799: }
9800: }
9801: for (var i=0; i<callingForm.srchtype.length; i++) {
9802: if (callingForm.srchtype.options[i].value == 'exact') {
9803: callingForm.srchtype.selectedIndex = i;
9804: }
9805: }
9806: for (var i=0; i<callingForm.srchdomain.length; i++) {
9807: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9808: callingForm.srchdomain.selectedIndex = i;
9809: }
9810: }
9811: }
9812: }
9813: ENDSCRIPT
9814:
9815: }
9816:
9817: my $output = <<"END_BLOCK";
9818: <script type="text/javascript">
9819: // <![CDATA[
9820: function validateEntry(callingForm) {
9821:
9822: var checkok = 1;
9823: var srchin;
9824: for (var i=0; i<callingForm.srchin.length; i++) {
9825: if ( callingForm.srchin[i].checked ) {
9826: srchin = callingForm.srchin[i].value;
9827: }
9828: }
9829:
9830: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9831: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9832: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9833: var srchterm = callingForm.srchterm.value;
9834: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9835: var msg = "";
9836:
9837: if (srchterm == "") {
9838: checkok = 0;
9839: msg += "$js_lt{'youm'}\\n";
9840: }
9841:
9842: if (srchtype== 'begins') {
9843: if (srchterm.length < 2) {
9844: checkok = 0;
9845: msg += "$js_lt{'thte'}\\n";
9846: }
9847: }
9848:
9849: if (srchtype== 'contains') {
9850: if (srchterm.length < 3) {
9851: checkok = 0;
9852: msg += "$js_lt{'thet'}\\n";
9853: }
9854: }
9855: if (srchin == 'instd') {
9856: if (srchdomain == '') {
9857: checkok = 0;
9858: msg += "$js_lt{'yomc'}\\n";
9859: }
9860: }
9861: if (srchin == 'dom') {
9862: if (srchdomain == '') {
9863: checkok = 0;
9864: msg += "$js_lt{'ymcd'}\\n";
9865: }
9866: }
9867: if (srchby == 'lastfirst') {
9868: if (srchterm.indexOf(",") == -1) {
9869: checkok = 0;
9870: msg += "$js_lt{'whus'}\\n";
9871: }
9872: if (srchterm.indexOf(",") == srchterm.length -1) {
9873: checkok = 0;
9874: msg += "$js_lt{'whse'}\\n";
9875: }
9876: }
9877: if (checkok == 0) {
9878: alert("$js_lt{'thfo'}\\n"+msg);
9879: return;
9880: }
9881: if (checkok == 1) {
9882: callingForm.submit();
9883: }
9884: }
9885:
9886: $newuserscript
9887:
9888: // ]]>
9889: </script>
9890:
9891: $new_user_create
9892:
9893: END_BLOCK
9894:
9895: $output .= &Apache::lonhtmlcommon::start_pick_box().
9896: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
9897: $domform.
9898: &Apache::lonhtmlcommon::row_closure().
9899: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
9900: $srchbysel.
9901: $srchtypesel.
9902: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9903: $srchinsel.
9904: &Apache::lonhtmlcommon::row_closure(1).
9905: &Apache::lonhtmlcommon::end_pick_box().
9906: '<br />';
9907: return ($output,1);
9908: }
9909:
9910: sub user_rule_check {
9911: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9912: my ($response,%inst_response);
9913: if (ref($usershash) eq 'HASH') {
9914: if (keys(%{$usershash}) > 1) {
9915: my (%by_username,%by_id,%userdoms);
9916: my $checkid;
9917: if (ref($checks) eq 'HASH') {
9918: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
9919: $checkid = 1;
9920: }
9921: }
9922: foreach my $user (keys(%{$usershash})) {
9923: my ($uname,$udom) = split(/:/,$user);
9924: if ($checkid) {
9925: if (ref($usershash->{$user}) eq 'HASH') {
9926: if ($usershash->{$user}->{'id'} ne '') {
9927: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
9928: $userdoms{$udom} = 1;
9929: if (ref($inst_results) eq 'HASH') {
9930: $inst_results->{$uname.':'.$udom} = {};
9931: }
9932: }
9933: }
9934: } else {
9935: $by_username{$udom}{$uname} = 1;
9936: $userdoms{$udom} = 1;
9937: if (ref($inst_results) eq 'HASH') {
9938: $inst_results->{$uname.':'.$udom} = {};
9939: }
9940: }
9941: }
9942: foreach my $udom (keys(%userdoms)) {
9943: if (!$got_rules->{$udom}) {
9944: my %domconfig = &Apache::lonnet::get_dom('configuration',
9945: ['usercreation'],$udom);
9946: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9947: foreach my $item ('username','id') {
9948: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9949: $$curr_rules{$udom}{$item} =
9950: $domconfig{'usercreation'}{$item.'_rule'};
9951: }
9952: }
9953: }
9954: $got_rules->{$udom} = 1;
9955: }
9956: }
9957: if ($checkid) {
9958: foreach my $udom (keys(%by_id)) {
9959: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
9960: if ($outcome eq 'ok') {
9961: foreach my $id (keys(%{$by_id{$udom}})) {
9962: my $uname = $by_id{$udom}{$id};
9963: $inst_response{$uname.':'.$udom} = $outcome;
9964: }
9965: if (ref($results) eq 'HASH') {
9966: foreach my $uname (keys(%{$results})) {
9967: if (exists($inst_response{$uname.':'.$udom})) {
9968: $inst_response{$uname.':'.$udom} = $outcome;
9969: $inst_results->{$uname.':'.$udom} = $results->{$uname};
9970: }
9971: }
9972: }
9973: }
9974: }
9975: } else {
9976: foreach my $udom (keys(%by_username)) {
9977: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
9978: if ($outcome eq 'ok') {
9979: foreach my $uname (keys(%{$by_username{$udom}})) {
9980: $inst_response{$uname.':'.$udom} = $outcome;
9981: }
9982: if (ref($results) eq 'HASH') {
9983: foreach my $uname (keys(%{$results})) {
9984: $inst_results->{$uname.':'.$udom} = $results->{$uname};
9985: }
9986: }
9987: }
9988: }
9989: }
9990: } elsif (keys(%{$usershash}) == 1) {
9991: my $user = (keys(%{$usershash}))[0];
9992: my ($uname,$udom) = split(/:/,$user);
9993: if (($udom ne '') && ($uname ne '')) {
9994: if (ref($usershash->{$user}) eq 'HASH') {
9995: if (ref($checks) eq 'HASH') {
9996: if (defined($checks->{'username'})) {
9997: ($inst_response{$user},%{$inst_results->{$user}}) =
9998: &Apache::lonnet::get_instuser($udom,$uname);
9999: } elsif (defined($checks->{'id'})) {
10000: if ($usershash->{$user}->{'id'} ne '') {
10001: ($inst_response{$user},%{$inst_results->{$user}}) =
10002: &Apache::lonnet::get_instuser($udom,undef,
10003: $usershash->{$user}->{'id'});
10004: } else {
10005: ($inst_response{$user},%{$inst_results->{$user}}) =
10006: &Apache::lonnet::get_instuser($udom,$uname);
10007: }
10008: }
10009: } else {
10010: ($inst_response{$user},%{$inst_results->{$user}}) =
10011: &Apache::lonnet::get_instuser($udom,$uname);
10012: return;
10013: }
10014: if (!$got_rules->{$udom}) {
10015: my %domconfig = &Apache::lonnet::get_dom('configuration',
10016: ['usercreation'],$udom);
10017: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10018: foreach my $item ('username','id') {
10019: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10020: $$curr_rules{$udom}{$item} =
10021: $domconfig{'usercreation'}{$item.'_rule'};
10022: }
10023: }
10024: }
10025: $got_rules->{$udom} = 1;
10026: }
10027: }
10028: } else {
10029: return;
10030: }
10031: } else {
10032: return;
10033: }
10034: foreach my $user (keys(%{$usershash})) {
10035: my ($uname,$udom) = split(/:/,$user);
10036: next if (($udom eq '') || ($uname eq ''));
10037: my $id;
10038: if (ref($inst_results) eq 'HASH') {
10039: if (ref($inst_results->{$user}) eq 'HASH') {
10040: $id = $inst_results->{$user}->{'id'};
10041: }
10042: }
10043: if ($id eq '') {
10044: if (ref($usershash->{$user})) {
10045: $id = $usershash->{$user}->{'id'};
10046: }
10047: }
10048: foreach my $item (keys(%{$checks})) {
10049: if (ref($$curr_rules{$udom}) eq 'HASH') {
10050: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10051: if (@{$$curr_rules{$udom}{$item}} > 0) {
10052: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10053: $$curr_rules{$udom}{$item});
10054: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10055: if ($rule_check{$rule}) {
10056: $$rulematch{$user}{$item} = $rule;
10057: if ($inst_response{$user} eq 'ok') {
10058: if (ref($inst_results) eq 'HASH') {
10059: if (ref($inst_results->{$user}) eq 'HASH') {
10060: if (keys(%{$inst_results->{$user}}) == 0) {
10061: $$alerts{$item}{$udom}{$uname} = 1;
10062: } elsif ($item eq 'id') {
10063: if ($inst_results->{$user}->{'id'} eq '') {
10064: $$alerts{$item}{$udom}{$uname} = 1;
10065: }
10066: }
10067: }
10068: }
10069: }
10070: last;
10071: }
10072: }
10073: }
10074: }
10075: }
10076: }
10077: }
10078: }
10079: return;
10080: }
10081:
10082: sub user_rule_formats {
10083: my ($domain,$domdesc,$curr_rules,$check) = @_;
10084: my %text = (
10085: 'username' => 'Usernames',
10086: 'id' => 'IDs',
10087: );
10088: my $output;
10089: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10090: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10091: if (@{$ruleorder} > 0) {
10092: $output = '<br />'.
10093: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10094: '<span class="LC_cusr_emph">','</span>',$domdesc).
10095: ' <ul>';
10096: foreach my $rule (@{$ruleorder}) {
10097: if (ref($curr_rules) eq 'ARRAY') {
10098: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10099: if (ref($rules->{$rule}) eq 'HASH') {
10100: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10101: $rules->{$rule}{'desc'}.'</li>';
10102: }
10103: }
10104: }
10105: }
10106: $output .= '</ul>';
10107: }
10108: }
10109: return $output;
10110: }
10111:
10112: sub instrule_disallow_msg {
10113: my ($checkitem,$domdesc,$count,$mode) = @_;
10114: my $response;
10115: my %text = (
10116: item => 'username',
10117: items => 'usernames',
10118: match => 'matches',
10119: do => 'does',
10120: action => 'a username',
10121: one => 'one',
10122: );
10123: if ($count > 1) {
10124: $text{'item'} = 'usernames';
10125: $text{'match'} ='match';
10126: $text{'do'} = 'do';
10127: $text{'action'} = 'usernames',
10128: $text{'one'} = 'ones';
10129: }
10130: if ($checkitem eq 'id') {
10131: $text{'items'} = 'IDs';
10132: $text{'item'} = 'ID';
10133: $text{'action'} = 'an ID';
10134: if ($count > 1) {
10135: $text{'item'} = 'IDs';
10136: $text{'action'} = 'IDs';
10137: }
10138: }
10139: $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 />';
10140: if ($mode eq 'upload') {
10141: if ($checkitem eq 'username') {
10142: $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'}.");
10143: } elsif ($checkitem eq 'id') {
10144: $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.");
10145: }
10146: } elsif ($mode eq 'selfcreate') {
10147: if ($checkitem eq 'id') {
10148: $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.");
10149: }
10150: } else {
10151: if ($checkitem eq 'username') {
10152: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10153: } elsif ($checkitem eq 'id') {
10154: $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.");
10155: }
10156: }
10157: return $response;
10158: }
10159:
10160: sub personal_data_fieldtitles {
10161: my %fieldtitles = &Apache::lonlocal::texthash (
10162: id => 'Student/Employee ID',
10163: permanentemail => 'E-mail address',
10164: lastname => 'Last Name',
10165: firstname => 'First Name',
10166: middlename => 'Middle Name',
10167: generation => 'Generation',
10168: gen => 'Generation',
10169: inststatus => 'Affiliation',
10170: );
10171: return %fieldtitles;
10172: }
10173:
10174: sub sorted_inst_types {
10175: my ($dom) = @_;
10176: my ($usertypes,$order);
10177: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10178: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10179: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10180: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10181: } else {
10182: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10183: }
10184: my $othertitle = &mt('All users');
10185: if ($env{'request.course.id'}) {
10186: $othertitle = &mt('Any users');
10187: }
10188: my @types;
10189: if (ref($order) eq 'ARRAY') {
10190: @types = @{$order};
10191: }
10192: if (@types == 0) {
10193: if (ref($usertypes) eq 'HASH') {
10194: @types = sort(keys(%{$usertypes}));
10195: }
10196: }
10197: if (keys(%{$usertypes}) > 0) {
10198: $othertitle = &mt('Other users');
10199: }
10200: return ($othertitle,$usertypes,\@types);
10201: }
10202:
10203: sub get_institutional_codes {
10204: my ($settings,$allcourses,$LC_code) = @_;
10205: # Get complete list of course sections to update
10206: my @currsections = ();
10207: my @currxlists = ();
10208: my $coursecode = $$settings{'internal.coursecode'};
10209:
10210: if ($$settings{'internal.sectionnums'} ne '') {
10211: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10212: }
10213:
10214: if ($$settings{'internal.crosslistings'} ne '') {
10215: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10216: }
10217:
10218: if (@currxlists > 0) {
10219: foreach (@currxlists) {
10220: if (m/^([^:]+):(\w*)$/) {
10221: unless (grep/^$1$/,@{$allcourses}) {
10222: push(@{$allcourses},$1);
10223: $$LC_code{$1} = $2;
10224: }
10225: }
10226: }
10227: }
10228:
10229: if (@currsections > 0) {
10230: foreach (@currsections) {
10231: if (m/^(\w+):(\w*)$/) {
10232: my $sec = $coursecode.$1;
10233: my $lc_sec = $2;
10234: unless (grep/^$sec$/,@{$allcourses}) {
10235: push(@{$allcourses},$sec);
10236: $$LC_code{$sec} = $lc_sec;
10237: }
10238: }
10239: }
10240: }
10241: return;
10242: }
10243:
10244: sub get_standard_codeitems {
10245: return ('Year','Semester','Department','Number','Section');
10246: }
10247:
10248: =pod
10249:
10250: =head1 Slot Helpers
10251:
10252: =over 4
10253:
10254: =item * sorted_slots()
10255:
10256: Sorts an array of slot names in order of an optional sort key,
10257: default sort is by slot start time (earliest first).
10258:
10259: Inputs:
10260:
10261: =over 4
10262:
10263: slotsarr - Reference to array of unsorted slot names.
10264:
10265: slots - Reference to hash of hash, where outer hash keys are slot names.
10266:
10267: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10268:
10269: =back
10270:
10271: Returns:
10272:
10273: =over 4
10274:
10275: sorted - An array of slot names sorted by a specified sort key
10276: (default sort key is start time of the slot).
10277:
10278: =back
10279:
10280: =cut
10281:
10282:
10283: sub sorted_slots {
10284: my ($slotsarr,$slots,$sortkey) = @_;
10285: if ($sortkey eq '') {
10286: $sortkey = 'starttime';
10287: }
10288: my @sorted;
10289: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10290: @sorted =
10291: sort {
10292: if (ref($slots->{$a}) && ref($slots->{$b})) {
10293: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10294: }
10295: if (ref($slots->{$a})) { return -1;}
10296: if (ref($slots->{$b})) { return 1;}
10297: return 0;
10298: } @{$slotsarr};
10299: }
10300: return @sorted;
10301: }
10302:
10303: =pod
10304:
10305: =item * get_future_slots()
10306:
10307: Inputs:
10308:
10309: =over 4
10310:
10311: cnum - course number
10312:
10313: cdom - course domain
10314:
10315: now - current UNIX time
10316:
10317: symb - optional symb
10318:
10319: =back
10320:
10321: Returns:
10322:
10323: =over 4
10324:
10325: sorted_reservable - ref to array of student_schedulable slots currently
10326: reservable, ordered by end date of reservation period.
10327:
10328: reservable_now - ref to hash of student_schedulable slots currently
10329: reservable.
10330:
10331: Keys in inner hash are:
10332: (a) symb: either blank or symb to which slot use is restricted.
10333: (b) endreserve: end date of reservation period.
10334: (c) uniqueperiod: start,end dates when slot is to be uniquely
10335: selected.
10336:
10337: sorted_future - ref to array of student_schedulable slots reservable in
10338: the future, ordered by start date of reservation period.
10339:
10340: future_reservable - ref to hash of student_schedulable slots reservable
10341: in the future.
10342:
10343: Keys in inner hash are:
10344: (a) symb: either blank or symb to which slot use is restricted.
10345: (b) startreserve: start date of reservation period.
10346: (c) uniqueperiod: start,end dates when slot is to be uniquely
10347: selected.
10348:
10349: =back
10350:
10351: =cut
10352:
10353: sub get_future_slots {
10354: my ($cnum,$cdom,$now,$symb) = @_;
10355: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10356: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10357: foreach my $slot (keys(%slots)) {
10358: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10359: if ($symb) {
10360: next if (($slots{$slot}->{'symb'} ne '') &&
10361: ($slots{$slot}->{'symb'} ne $symb));
10362: }
10363: if (($slots{$slot}->{'starttime'} > $now) &&
10364: ($slots{$slot}->{'endtime'} > $now)) {
10365: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10366: my $userallowed = 0;
10367: if ($slots{$slot}->{'allowedsections'}) {
10368: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10369: if (!defined($env{'request.role.sec'})
10370: && grep(/^No section assigned$/,@allowed_sec)) {
10371: $userallowed=1;
10372: } else {
10373: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10374: $userallowed=1;
10375: }
10376: }
10377: unless ($userallowed) {
10378: if (defined($env{'request.course.groups'})) {
10379: my @groups = split(/:/,$env{'request.course.groups'});
10380: foreach my $group (@groups) {
10381: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10382: $userallowed=1;
10383: last;
10384: }
10385: }
10386: }
10387: }
10388: }
10389: if ($slots{$slot}->{'allowedusers'}) {
10390: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10391: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10392: if (grep(/^\Q$user\E$/,@allowed_users)) {
10393: $userallowed = 1;
10394: }
10395: }
10396: next unless($userallowed);
10397: }
10398: my $startreserve = $slots{$slot}->{'startreserve'};
10399: my $endreserve = $slots{$slot}->{'endreserve'};
10400: my $symb = $slots{$slot}->{'symb'};
10401: my $uniqueperiod;
10402: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10403: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10404: }
10405: if (($startreserve < $now) &&
10406: (!$endreserve || $endreserve > $now)) {
10407: my $lastres = $endreserve;
10408: if (!$lastres) {
10409: $lastres = $slots{$slot}->{'starttime'};
10410: }
10411: $reservable_now{$slot} = {
10412: symb => $symb,
10413: endreserve => $lastres,
10414: uniqueperiod => $uniqueperiod,
10415: };
10416: } elsif (($startreserve > $now) &&
10417: (!$endreserve || $endreserve > $startreserve)) {
10418: $future_reservable{$slot} = {
10419: symb => $symb,
10420: startreserve => $startreserve,
10421: uniqueperiod => $uniqueperiod,
10422: };
10423: }
10424: }
10425: }
10426: my @unsorted_reservable = keys(%reservable_now);
10427: if (@unsorted_reservable > 0) {
10428: @sorted_reservable =
10429: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10430: }
10431: my @unsorted_future = keys(%future_reservable);
10432: if (@unsorted_future > 0) {
10433: @sorted_future =
10434: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10435: }
10436: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10437: }
10438:
10439: =pod
10440:
10441: =back
10442:
10443: =head1 HTTP Helpers
10444:
10445: =over 4
10446:
10447: =item * &get_unprocessed_cgi($query,$possible_names)
10448:
10449: Modify the %env hash to contain unprocessed CGI form parameters held in
10450: $query. The parameters listed in $possible_names (an array reference),
10451: will be set in $env{'form.name'} if they do not already exist.
10452:
10453: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
10454: $possible_names is an ref to an array of form element names. As an example:
10455: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10456: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10457:
10458: =cut
10459:
10460: sub get_unprocessed_cgi {
10461: my ($query,$possible_names)= @_;
10462: # $Apache::lonxml::debug=1;
10463: foreach my $pair (split(/&/,$query)) {
10464: my ($name, $value) = split(/=/,$pair);
10465: $name = &unescape($name);
10466: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10467: $value =~ tr/+/ /;
10468: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10469: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10470: }
10471: }
10472: }
10473:
10474: =pod
10475:
10476: =item * &cacheheader()
10477:
10478: returns cache-controlling header code
10479:
10480: =cut
10481:
10482: sub cacheheader {
10483: unless ($env{'request.method'} eq 'GET') { return ''; }
10484: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10485: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10486: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10487: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10488: return $output;
10489: }
10490:
10491: =pod
10492:
10493: =item * &no_cache($r)
10494:
10495: specifies header code to not have cache
10496:
10497: =cut
10498:
10499: sub no_cache {
10500: my ($r) = @_;
10501: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10502: $env{'request.method'} ne 'GET') { return ''; }
10503: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10504: $r->no_cache(1);
10505: $r->header_out("Expires" => $date);
10506: $r->header_out("Pragma" => "no-cache");
10507: }
10508:
10509: sub content_type {
10510: my ($r,$type,$charset) = @_;
10511: if ($r) {
10512: # Note that printout.pl calls this with undef for $r.
10513: &no_cache($r);
10514: }
10515: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10516: unless ($charset) {
10517: $charset=&Apache::lonlocal::current_encoding;
10518: }
10519: if ($charset) { $type.='; charset='.$charset; }
10520: if ($r) {
10521: $r->content_type($type);
10522: } else {
10523: print("Content-type: $type\n\n");
10524: }
10525: }
10526:
10527: =pod
10528:
10529: =item * &add_to_env($name,$value)
10530:
10531: adds $name to the %env hash with value
10532: $value, if $name already exists, the entry is converted to an array
10533: reference and $value is added to the array.
10534:
10535: =cut
10536:
10537: sub add_to_env {
10538: my ($name,$value)=@_;
10539: if (defined($env{$name})) {
10540: if (ref($env{$name})) {
10541: #already have multiple values
10542: push(@{ $env{$name} },$value);
10543: } else {
10544: #first time seeing multiple values, convert hash entry to an arrayref
10545: my $first=$env{$name};
10546: undef($env{$name});
10547: push(@{ $env{$name} },$first,$value);
10548: }
10549: } else {
10550: $env{$name}=$value;
10551: }
10552: }
10553:
10554: =pod
10555:
10556: =item * &get_env_multiple($name)
10557:
10558: gets $name from the %env hash, it seemlessly handles the cases where multiple
10559: values may be defined and end up as an array ref.
10560:
10561: returns an array of values
10562:
10563: =cut
10564:
10565: sub get_env_multiple {
10566: my ($name) = @_;
10567: my @values;
10568: if (defined($env{$name})) {
10569: # exists is it an array
10570: if (ref($env{$name})) {
10571: @values=@{ $env{$name} };
10572: } else {
10573: $values[0]=$env{$name};
10574: }
10575: }
10576: return(@values);
10577: }
10578:
10579: sub ask_for_embedded_content {
10580: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10581: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10582: %currsubfile,%unused,$rem);
10583: my $counter = 0;
10584: my $numnew = 0;
10585: my $numremref = 0;
10586: my $numinvalid = 0;
10587: my $numpathchg = 0;
10588: my $numexisting = 0;
10589: my $numunused = 0;
10590: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10591: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10592: my $heading = &mt('Upload embedded files');
10593: my $buttontext = &mt('Upload');
10594:
10595: if ($env{'request.course.id'}) {
10596: if ($actionurl eq '/adm/dependencies') {
10597: $navmap = Apache::lonnavmaps::navmap->new();
10598: }
10599: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10600: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10601: }
10602: if (($actionurl eq '/adm/portfolio') ||
10603: ($actionurl eq '/adm/coursegrp_portfolio')) {
10604: my $current_path='/';
10605: if ($env{'form.currentpath'}) {
10606: $current_path = $env{'form.currentpath'};
10607: }
10608: if ($actionurl eq '/adm/coursegrp_portfolio') {
10609: $udom = $cdom;
10610: $uname = $cnum;
10611: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10612: } else {
10613: $udom = $env{'user.domain'};
10614: $uname = $env{'user.name'};
10615: $url = '/userfiles/portfolio';
10616: }
10617: $toplevel = $url.'/';
10618: $url .= $current_path;
10619: $getpropath = 1;
10620: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10621: ($actionurl eq '/adm/imsimport')) {
10622: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10623: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10624: $toplevel = $url;
10625: if ($rest ne '') {
10626: $url .= $rest;
10627: }
10628: } elsif ($actionurl eq '/adm/coursedocs') {
10629: if (ref($args) eq 'HASH') {
10630: $url = $args->{'docs_url'};
10631: $toplevel = $url;
10632: if ($args->{'context'} eq 'paste') {
10633: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10634: ($path) =
10635: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10636: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10637: $fileloc =~ s{^/}{};
10638: }
10639: }
10640: } elsif ($actionurl eq '/adm/dependencies') {
10641: if ($env{'request.course.id'} ne '') {
10642: if (ref($args) eq 'HASH') {
10643: $url = $args->{'docs_url'};
10644: $title = $args->{'docs_title'};
10645: $toplevel = $url;
10646: unless ($toplevel =~ m{^/}) {
10647: $toplevel = "/$url";
10648: }
10649: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10650: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10651: $path = $1;
10652: } else {
10653: ($path) =
10654: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10655: }
10656: if ($toplevel=~/^\/*(uploaded|editupload)/) {
10657: $fileloc = $toplevel;
10658: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10659: my ($udom,$uname,$fname) =
10660: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10661: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10662: } else {
10663: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10664: }
10665: $fileloc =~ s{^/}{};
10666: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10667: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10668: }
10669: }
10670: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10671: $udom = $cdom;
10672: $uname = $cnum;
10673: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10674: $toplevel = $url;
10675: $path = $url;
10676: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10677: $fileloc =~ s{^/}{};
10678: }
10679: foreach my $file (keys(%{$allfiles})) {
10680: my $embed_file;
10681: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10682: $embed_file = $1;
10683: } else {
10684: $embed_file = $file;
10685: }
10686: my ($absolutepath,$cleaned_file);
10687: if ($embed_file =~ m{^\w+://}) {
10688: $cleaned_file = $embed_file;
10689: $newfiles{$cleaned_file} = 1;
10690: $mapping{$cleaned_file} = $embed_file;
10691: } else {
10692: $cleaned_file = &clean_path($embed_file);
10693: if ($embed_file =~ m{^/}) {
10694: $absolutepath = $embed_file;
10695: }
10696: if ($cleaned_file =~ m{/}) {
10697: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10698: $path = &check_for_traversal($path,$url,$toplevel);
10699: my $item = $fname;
10700: if ($path ne '') {
10701: $item = $path.'/'.$fname;
10702: $subdependencies{$path}{$fname} = 1;
10703: } else {
10704: $dependencies{$item} = 1;
10705: }
10706: if ($absolutepath) {
10707: $mapping{$item} = $absolutepath;
10708: } else {
10709: $mapping{$item} = $embed_file;
10710: }
10711: } else {
10712: $dependencies{$embed_file} = 1;
10713: if ($absolutepath) {
10714: $mapping{$cleaned_file} = $absolutepath;
10715: } else {
10716: $mapping{$cleaned_file} = $embed_file;
10717: }
10718: }
10719: }
10720: }
10721: my $dirptr = 16384;
10722: foreach my $path (keys(%subdependencies)) {
10723: $currsubfile{$path} = {};
10724: if (($actionurl eq '/adm/portfolio') ||
10725: ($actionurl eq '/adm/coursegrp_portfolio')) {
10726: my ($sublistref,$listerror) =
10727: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10728: if (ref($sublistref) eq 'ARRAY') {
10729: foreach my $line (@{$sublistref}) {
10730: my ($file_name,$rest) = split(/\&/,$line,2);
10731: $currsubfile{$path}{$file_name} = 1;
10732: }
10733: }
10734: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10735: if (opendir(my $dir,$url.'/'.$path)) {
10736: my @subdir_list = grep(!/^\./,readdir($dir));
10737: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10738: }
10739: } elsif (($actionurl eq '/adm/dependencies') ||
10740: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10741: ($args->{'context'} eq 'paste')) ||
10742: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10743: if ($env{'request.course.id'} ne '') {
10744: my $dir;
10745: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10746: $dir = $fileloc;
10747: } else {
10748: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10749: }
10750: if ($dir ne '') {
10751: my ($sublistref,$listerror) =
10752: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10753: if (ref($sublistref) eq 'ARRAY') {
10754: foreach my $line (@{$sublistref}) {
10755: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10756: undef,$mtime)=split(/\&/,$line,12);
10757: unless (($testdir&$dirptr) ||
10758: ($file_name =~ /^\.\.?$/)) {
10759: $currsubfile{$path}{$file_name} = [$size,$mtime];
10760: }
10761: }
10762: }
10763: }
10764: }
10765: }
10766: foreach my $file (keys(%{$subdependencies{$path}})) {
10767: if (exists($currsubfile{$path}{$file})) {
10768: my $item = $path.'/'.$file;
10769: unless ($mapping{$item} eq $item) {
10770: $pathchanges{$item} = 1;
10771: }
10772: $existing{$item} = 1;
10773: $numexisting ++;
10774: } else {
10775: $newfiles{$path.'/'.$file} = 1;
10776: }
10777: }
10778: if ($actionurl eq '/adm/dependencies') {
10779: foreach my $path (keys(%currsubfile)) {
10780: if (ref($currsubfile{$path}) eq 'HASH') {
10781: foreach my $file (keys(%{$currsubfile{$path}})) {
10782: unless ($subdependencies{$path}{$file}) {
10783: next if (($rem ne '') &&
10784: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10785: (ref($navmap) &&
10786: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10787: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10788: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10789: $unused{$path.'/'.$file} = 1;
10790: }
10791: }
10792: }
10793: }
10794: }
10795: }
10796: my %currfile;
10797: if (($actionurl eq '/adm/portfolio') ||
10798: ($actionurl eq '/adm/coursegrp_portfolio')) {
10799: my ($dirlistref,$listerror) =
10800: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10801: if (ref($dirlistref) eq 'ARRAY') {
10802: foreach my $line (@{$dirlistref}) {
10803: my ($file_name,$rest) = split(/\&/,$line,2);
10804: $currfile{$file_name} = 1;
10805: }
10806: }
10807: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10808: if (opendir(my $dir,$url)) {
10809: my @dir_list = grep(!/^\./,readdir($dir));
10810: map {$currfile{$_} = 1;} @dir_list;
10811: }
10812: } elsif (($actionurl eq '/adm/dependencies') ||
10813: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10814: ($args->{'context'} eq 'paste')) ||
10815: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10816: if ($env{'request.course.id'} ne '') {
10817: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10818: if ($dir ne '') {
10819: my ($dirlistref,$listerror) =
10820: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10821: if (ref($dirlistref) eq 'ARRAY') {
10822: foreach my $line (@{$dirlistref}) {
10823: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10824: $size,undef,$mtime)=split(/\&/,$line,12);
10825: unless (($testdir&$dirptr) ||
10826: ($file_name =~ /^\.\.?$/)) {
10827: $currfile{$file_name} = [$size,$mtime];
10828: }
10829: }
10830: }
10831: }
10832: }
10833: }
10834: foreach my $file (keys(%dependencies)) {
10835: if (exists($currfile{$file})) {
10836: unless ($mapping{$file} eq $file) {
10837: $pathchanges{$file} = 1;
10838: }
10839: $existing{$file} = 1;
10840: $numexisting ++;
10841: } else {
10842: $newfiles{$file} = 1;
10843: }
10844: }
10845: foreach my $file (keys(%currfile)) {
10846: unless (($file eq $filename) ||
10847: ($file eq $filename.'.bak') ||
10848: ($dependencies{$file})) {
10849: if ($actionurl eq '/adm/dependencies') {
10850: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10851: next if (($rem ne '') &&
10852: (($env{"httpref.$rem".$file} ne '') ||
10853: (ref($navmap) &&
10854: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10855: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10856: ($navmap->getResourceByUrl($rem.$1)))))));
10857: }
10858: }
10859: $unused{$file} = 1;
10860: }
10861: }
10862: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10863: ($args->{'context'} eq 'paste')) {
10864: $counter = scalar(keys(%existing));
10865: $numpathchg = scalar(keys(%pathchanges));
10866: return ($output,$counter,$numpathchg,\%existing);
10867: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10868: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10869: $counter = scalar(keys(%existing));
10870: $numpathchg = scalar(keys(%pathchanges));
10871: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10872: }
10873: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10874: if ($actionurl eq '/adm/dependencies') {
10875: next if ($embed_file =~ m{^\w+://});
10876: }
10877: $upload_output .= &start_data_table_row().
10878: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10879: '<span class="LC_filename">'.$embed_file.'</span>';
10880: unless ($mapping{$embed_file} eq $embed_file) {
10881: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10882: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10883: }
10884: $upload_output .= '</td>';
10885: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10886: $upload_output.='<td align="right">'.
10887: '<span class="LC_info LC_fontsize_medium">'.
10888: &mt("URL points to web address").'</span>';
10889: $numremref++;
10890: } elsif ($args->{'error_on_invalid_names'}
10891: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10892: $upload_output.='<td align="right"><span class="LC_warning">'.
10893: &mt('Invalid characters').'</span>';
10894: $numinvalid++;
10895: } else {
10896: $upload_output .= '<td>'.
10897: &embedded_file_element('upload_embedded',$counter,
10898: $embed_file,\%mapping,
10899: $allfiles,$codebase,'upload');
10900: $counter ++;
10901: $numnew ++;
10902: }
10903: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10904: }
10905: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10906: if ($actionurl eq '/adm/dependencies') {
10907: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10908: $modify_output .= &start_data_table_row().
10909: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10910: '<img src="'.&icon($embed_file).'" border="0" />'.
10911: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10912: '<td>'.$size.'</td>'.
10913: '<td>'.$mtime.'</td>'.
10914: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10915: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10916: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10917: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10918: &embedded_file_element('upload_embedded',$counter,
10919: $embed_file,\%mapping,
10920: $allfiles,$codebase,'modify').
10921: '</div></td>'.
10922: &end_data_table_row()."\n";
10923: $counter ++;
10924: } else {
10925: $upload_output .= &start_data_table_row().
10926: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10927: '<span class="LC_filename">'.$embed_file.'</span></td>'.
10928: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10929: &Apache::loncommon::end_data_table_row()."\n";
10930: }
10931: }
10932: my $delidx = $counter;
10933: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10934: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10935: $delete_output .= &start_data_table_row().
10936: '<td><img src="'.&icon($oldfile).'" />'.
10937: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
10938: '<td>'.$size.'</td>'.
10939: '<td>'.$mtime.'</td>'.
10940: '<td><label><input type="checkbox" name="del_upload_dep" '.
10941: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10942: &embedded_file_element('upload_embedded',$delidx,
10943: $oldfile,\%mapping,$allfiles,
10944: $codebase,'delete').'</td>'.
10945: &end_data_table_row()."\n";
10946: $numunused ++;
10947: $delidx ++;
10948: }
10949: if ($upload_output) {
10950: $upload_output = &start_data_table().
10951: $upload_output.
10952: &end_data_table()."\n";
10953: }
10954: if ($modify_output) {
10955: $modify_output = &start_data_table().
10956: &start_data_table_header_row().
10957: '<th>'.&mt('File').'</th>'.
10958: '<th>'.&mt('Size (KB)').'</th>'.
10959: '<th>'.&mt('Modified').'</th>'.
10960: '<th>'.&mt('Upload replacement?').'</th>'.
10961: &end_data_table_header_row().
10962: $modify_output.
10963: &end_data_table()."\n";
10964: }
10965: if ($delete_output) {
10966: $delete_output = &start_data_table().
10967: &start_data_table_header_row().
10968: '<th>'.&mt('File').'</th>'.
10969: '<th>'.&mt('Size (KB)').'</th>'.
10970: '<th>'.&mt('Modified').'</th>'.
10971: '<th>'.&mt('Delete?').'</th>'.
10972: &end_data_table_header_row().
10973: $delete_output.
10974: &end_data_table()."\n";
10975: }
10976: my $applies = 0;
10977: if ($numremref) {
10978: $applies ++;
10979: }
10980: if ($numinvalid) {
10981: $applies ++;
10982: }
10983: if ($numexisting) {
10984: $applies ++;
10985: }
10986: if ($counter || $numunused) {
10987: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10988: ' method="post" enctype="multipart/form-data">'."\n".
10989: $state.'<h3>'.$heading.'</h3>';
10990: if ($actionurl eq '/adm/dependencies') {
10991: if ($numnew) {
10992: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10993: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10994: $upload_output.'<br />'."\n";
10995: }
10996: if ($numexisting) {
10997: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10998: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10999: $modify_output.'<br />'."\n";
11000: $buttontext = &mt('Save changes');
11001: }
11002: if ($numunused) {
11003: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11004: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11005: $delete_output.'<br />'."\n";
11006: $buttontext = &mt('Save changes');
11007: }
11008: } else {
11009: $output .= $upload_output.'<br />'."\n";
11010: }
11011: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11012: $counter.'" />'."\n";
11013: if ($actionurl eq '/adm/dependencies') {
11014: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11015: $numnew.'" />'."\n";
11016: } elsif ($actionurl eq '') {
11017: $output .= '<input type="hidden" name="phase" value="three" />';
11018: }
11019: } elsif ($applies) {
11020: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11021: if ($applies > 1) {
11022: $output .=
11023: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11024: if ($numremref) {
11025: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11026: }
11027: if ($numinvalid) {
11028: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11029: }
11030: if ($numexisting) {
11031: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11032: }
11033: $output .= '</ul><br />';
11034: } elsif ($numremref) {
11035: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11036: } elsif ($numinvalid) {
11037: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11038: } elsif ($numexisting) {
11039: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11040: }
11041: $output .= $upload_output.'<br />';
11042: }
11043: my ($pathchange_output,$chgcount);
11044: $chgcount = $counter;
11045: if (keys(%pathchanges) > 0) {
11046: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11047: if ($counter) {
11048: $output .= &embedded_file_element('pathchange',$chgcount,
11049: $embed_file,\%mapping,
11050: $allfiles,$codebase,'change');
11051: } else {
11052: $pathchange_output .=
11053: &start_data_table_row().
11054: '<td><input type ="checkbox" name="namechange" value="'.
11055: $chgcount.'" checked="checked" /></td>'.
11056: '<td>'.$mapping{$embed_file}.'</td>'.
11057: '<td>'.$embed_file.
11058: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11059: \%mapping,$allfiles,$codebase,'change').
11060: '</td>'.&end_data_table_row();
11061: }
11062: $numpathchg ++;
11063: $chgcount ++;
11064: }
11065: }
11066: if (($counter) || ($numunused)) {
11067: if ($numpathchg) {
11068: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11069: $numpathchg.'" />'."\n";
11070: }
11071: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11072: ($actionurl eq '/adm/imsimport')) {
11073: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11074: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11075: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11076: } elsif ($actionurl eq '/adm/dependencies') {
11077: $output .= '<input type="hidden" name="action" value="process_changes" />';
11078: }
11079: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11080: } elsif ($numpathchg) {
11081: my %pathchange = ();
11082: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11083: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11084: $output .= '<p>'.&mt('or').'</p>';
11085: }
11086: }
11087: return ($output,$counter,$numpathchg);
11088: }
11089:
11090: =pod
11091:
11092: =item * clean_path($name)
11093:
11094: Performs clean-up of directories, subdirectories and filename in an
11095: embedded object, referenced in an HTML file which is being uploaded
11096: to a course or portfolio, where
11097: "Upload embedded images/multimedia files if HTML file" checkbox was
11098: checked.
11099:
11100: Clean-up is similar to replacements in lonnet::clean_filename()
11101: except each / between sub-directory and next level is preserved.
11102:
11103: =cut
11104:
11105: sub clean_path {
11106: my ($embed_file) = @_;
11107: $embed_file =~s{^/+}{};
11108: my @contents;
11109: if ($embed_file =~ m{/}) {
11110: @contents = split(/\//,$embed_file);
11111: } else {
11112: @contents = ($embed_file);
11113: }
11114: my $lastidx = scalar(@contents)-1;
11115: for (my $i=0; $i<=$lastidx; $i++) {
11116: $contents[$i]=~s{\\}{/}g;
11117: $contents[$i]=~s/\s+/\_/g;
11118: $contents[$i]=~s{[^/\w\.\-]}{}g;
11119: if ($i == $lastidx) {
11120: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11121: }
11122: }
11123: if ($lastidx > 0) {
11124: return join('/',@contents);
11125: } else {
11126: return $contents[0];
11127: }
11128: }
11129:
11130: sub embedded_file_element {
11131: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11132: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11133: (ref($codebase) eq 'HASH'));
11134: my $output;
11135: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11136: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11137: }
11138: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11139: &escape($embed_file).'" />';
11140: unless (($context eq 'upload_embedded') &&
11141: ($mapping->{$embed_file} eq $embed_file)) {
11142: $output .='
11143: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11144: }
11145: my $attrib;
11146: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11147: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11148: }
11149: $output .=
11150: "\n\t\t".
11151: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11152: $attrib.'" />';
11153: if (exists($codebase->{$mapping->{$embed_file}})) {
11154: $output .=
11155: "\n\t\t".
11156: '<input name="codebase_'.$num.'" type="hidden" value="'.
11157: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11158: }
11159: return $output;
11160: }
11161:
11162: sub get_dependency_details {
11163: my ($currfile,$currsubfile,$embed_file) = @_;
11164: my ($size,$mtime,$showsize,$showmtime);
11165: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11166: if ($embed_file =~ m{/}) {
11167: my ($path,$fname) = split(/\//,$embed_file);
11168: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11169: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11170: }
11171: } else {
11172: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11173: ($size,$mtime) = @{$currfile->{$embed_file}};
11174: }
11175: }
11176: $showsize = $size/1024.0;
11177: $showsize = sprintf("%.1f",$showsize);
11178: if ($mtime > 0) {
11179: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11180: }
11181: }
11182: return ($showsize,$showmtime);
11183: }
11184:
11185: sub ask_embedded_js {
11186: return <<"END";
11187: <script type="text/javascript"">
11188: // <![CDATA[
11189: function toggleBrowse(counter) {
11190: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11191: var fileid = document.getElementById('embedded_item_'+counter);
11192: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11193: if (chkboxid.checked == true) {
11194: uploaddivid.style.display='block';
11195: } else {
11196: uploaddivid.style.display='none';
11197: fileid.value = '';
11198: }
11199: }
11200: // ]]>
11201: </script>
11202:
11203: END
11204: }
11205:
11206: sub upload_embedded {
11207: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11208: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11209: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11210: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11211: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11212: my $orig_uploaded_filename =
11213: $env{'form.embedded_item_'.$i.'.filename'};
11214: foreach my $type ('orig','ref','attrib','codebase') {
11215: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11216: $env{'form.embedded_'.$type.'_'.$i} =
11217: &unescape($env{'form.embedded_'.$type.'_'.$i});
11218: }
11219: }
11220: my ($path,$fname) =
11221: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11222: # no path, whole string is fname
11223: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11224: $fname = &Apache::lonnet::clean_filename($fname);
11225: # See if there is anything left
11226: next if ($fname eq '');
11227:
11228: # Check if file already exists as a file or directory.
11229: my ($state,$msg);
11230: if ($context eq 'portfolio') {
11231: my $port_path = $dirpath;
11232: if ($group ne '') {
11233: $port_path = "groups/$group/$port_path";
11234: }
11235: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11236: $fname,$group,'embedded_item_'.$i,
11237: $dir_root,$port_path,$disk_quota,
11238: $current_disk_usage,$uname,$udom);
11239: if ($state eq 'will_exceed_quota'
11240: || $state eq 'file_locked') {
11241: $output .= $msg;
11242: next;
11243: }
11244: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11245: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11246: if ($state eq 'exists') {
11247: $output .= $msg;
11248: next;
11249: }
11250: }
11251: # Check if extension is valid
11252: if (($fname =~ /\.(\w+)$/) &&
11253: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11254: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11255: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11256: next;
11257: } elsif (($fname =~ /\.(\w+)$/) &&
11258: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11259: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11260: next;
11261: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11262: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11263: next;
11264: }
11265: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11266: my $subdir = $path;
11267: $subdir =~ s{/+$}{};
11268: if ($context eq 'portfolio') {
11269: my $result;
11270: if ($state eq 'existingfile') {
11271: $result=
11272: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11273: $dirpath.$env{'form.currentpath'}.$subdir);
11274: } else {
11275: $result=
11276: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11277: $dirpath.
11278: $env{'form.currentpath'}.$subdir);
11279: if ($result !~ m|^/uploaded/|) {
11280: $output .= '<span class="LC_error">'
11281: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11282: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11283: .'</span><br />';
11284: next;
11285: } else {
11286: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11287: $path.$fname.'</span>').'<br />';
11288: }
11289: }
11290: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11291: my $extendedsubdir = $dirpath.'/'.$subdir;
11292: $extendedsubdir =~ s{/+$}{};
11293: my $result =
11294: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11295: if ($result !~ m|^/uploaded/|) {
11296: $output .= '<span class="LC_error">'
11297: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11298: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11299: .'</span><br />';
11300: next;
11301: } else {
11302: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11303: $path.$fname.'</span>').'<br />';
11304: if ($context eq 'syllabus') {
11305: &Apache::lonnet::make_public_indefinitely($result);
11306: }
11307: }
11308: } else {
11309: # Save the file
11310: my $target = $env{'form.embedded_item_'.$i};
11311: my $fullpath = $dir_root.$dirpath.'/'.$path;
11312: my $dest = $fullpath.$fname;
11313: my $url = $url_root.$dirpath.'/'.$path.$fname;
11314: my @parts=split(/\//,"$dirpath/$path");
11315: my $count;
11316: my $filepath = $dir_root;
11317: foreach my $subdir (@parts) {
11318: $filepath .= "/$subdir";
11319: if (!-e $filepath) {
11320: mkdir($filepath,0770);
11321: }
11322: }
11323: my $fh;
11324: if (!open($fh,'>'.$dest)) {
11325: &Apache::lonnet::logthis('Failed to create '.$dest);
11326: $output .= '<span class="LC_error">'.
11327: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11328: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11329: '</span><br />';
11330: } else {
11331: if (!print $fh $env{'form.embedded_item_'.$i}) {
11332: &Apache::lonnet::logthis('Failed to write to '.$dest);
11333: $output .= '<span class="LC_error">'.
11334: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11335: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11336: '</span><br />';
11337: } else {
11338: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11339: $url.'</span>').'<br />';
11340: unless ($context eq 'testbank') {
11341: $footer .= &mt('View embedded file: [_1]',
11342: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11343: }
11344: }
11345: close($fh);
11346: }
11347: }
11348: if ($env{'form.embedded_ref_'.$i}) {
11349: $pathchange{$i} = 1;
11350: }
11351: }
11352: if ($output) {
11353: $output = '<p>'.$output.'</p>';
11354: }
11355: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11356: $returnflag = 'ok';
11357: my $numpathchgs = scalar(keys(%pathchange));
11358: if ($numpathchgs > 0) {
11359: if ($context eq 'portfolio') {
11360: $output .= '<p>'.&mt('or').'</p>';
11361: } elsif ($context eq 'testbank') {
11362: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11363: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11364: $returnflag = 'modify_orightml';
11365: }
11366: }
11367: return ($output.$footer,$returnflag,$numpathchgs);
11368: }
11369:
11370: sub modify_html_form {
11371: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11372: my $end = 0;
11373: my $modifyform;
11374: if ($context eq 'upload_embedded') {
11375: return unless (ref($pathchange) eq 'HASH');
11376: if ($env{'form.number_embedded_items'}) {
11377: $end += $env{'form.number_embedded_items'};
11378: }
11379: if ($env{'form.number_pathchange_items'}) {
11380: $end += $env{'form.number_pathchange_items'};
11381: }
11382: if ($end) {
11383: for (my $i=0; $i<$end; $i++) {
11384: if ($i < $env{'form.number_embedded_items'}) {
11385: next unless($pathchange->{$i});
11386: }
11387: $modifyform .=
11388: &start_data_table_row().
11389: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11390: 'checked="checked" /></td>'.
11391: '<td>'.$env{'form.embedded_ref_'.$i}.
11392: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11393: &escape($env{'form.embedded_ref_'.$i}).'" />'.
11394: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11395: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11396: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11397: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11398: '<td>'.$env{'form.embedded_orig_'.$i}.
11399: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11400: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11401: &end_data_table_row();
11402: }
11403: }
11404: } else {
11405: $modifyform = $pathchgtable;
11406: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11407: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11408: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11409: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11410: }
11411: }
11412: if ($modifyform) {
11413: if ($actionurl eq '/adm/dependencies') {
11414: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11415: }
11416: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11417: '<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".
11418: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11419: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11420: '</ol></p>'."\n".'<p>'.
11421: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11422: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11423: &start_data_table()."\n".
11424: &start_data_table_header_row().
11425: '<th>'.&mt('Change?').'</th>'.
11426: '<th>'.&mt('Current reference').'</th>'.
11427: '<th>'.&mt('Required reference').'</th>'.
11428: &end_data_table_header_row()."\n".
11429: $modifyform.
11430: &end_data_table().'<br />'."\n".$hiddenstate.
11431: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11432: '</form>'."\n";
11433: }
11434: return;
11435: }
11436:
11437: sub modify_html_refs {
11438: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11439: my $container;
11440: if ($context eq 'portfolio') {
11441: $container = $env{'form.container'};
11442: } elsif ($context eq 'coursedoc') {
11443: $container = $env{'form.primaryurl'};
11444: } elsif ($context eq 'manage_dependencies') {
11445: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11446: $container = "/$container";
11447: } elsif ($context eq 'syllabus') {
11448: $container = $url;
11449: } else {
11450: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11451: }
11452: my (%allfiles,%codebase,$output,$content);
11453: my @changes = &get_env_multiple('form.namechange');
11454: unless ((@changes > 0) || ($context eq 'syllabus')) {
11455: if (wantarray) {
11456: return ('',0,0);
11457: } else {
11458: return;
11459: }
11460: }
11461: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11462: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11463: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11464: if (wantarray) {
11465: return ('',0,0);
11466: } else {
11467: return;
11468: }
11469: }
11470: $content = &Apache::lonnet::getfile($container);
11471: if ($content eq '-1') {
11472: if (wantarray) {
11473: return ('',0,0);
11474: } else {
11475: return;
11476: }
11477: }
11478: } else {
11479: unless ($container =~ /^\Q$dir_root\E/) {
11480: if (wantarray) {
11481: return ('',0,0);
11482: } else {
11483: return;
11484: }
11485: }
11486: if (open(my $fh,'<',$container)) {
11487: $content = join('', <$fh>);
11488: close($fh);
11489: } else {
11490: if (wantarray) {
11491: return ('',0,0);
11492: } else {
11493: return;
11494: }
11495: }
11496: }
11497: my ($count,$codebasecount) = (0,0);
11498: my $mm = new File::MMagic;
11499: my $mime_type = $mm->checktype_contents($content);
11500: if ($mime_type eq 'text/html') {
11501: my $parse_result =
11502: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11503: \%codebase,\$content);
11504: if ($parse_result eq 'ok') {
11505: foreach my $i (@changes) {
11506: my $orig = &unescape($env{'form.embedded_orig_'.$i});
11507: my $ref = &unescape($env{'form.embedded_ref_'.$i});
11508: if ($allfiles{$ref}) {
11509: my $newname = $orig;
11510: my ($attrib_regexp,$codebase);
11511: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11512: if ($attrib_regexp =~ /:/) {
11513: $attrib_regexp =~ s/\:/|/g;
11514: }
11515: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11516: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11517: $count += $numchg;
11518: $allfiles{$newname} = $allfiles{$ref};
11519: delete($allfiles{$ref});
11520: }
11521: if ($env{'form.embedded_codebase_'.$i} ne '') {
11522: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11523: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11524: $codebasecount ++;
11525: }
11526: }
11527: }
11528: my $skiprewrites;
11529: if ($count || $codebasecount) {
11530: my $saveresult;
11531: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11532: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11533: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11534: if ($url eq $container) {
11535: my ($fname) = ($container =~ m{/([^/]+)$});
11536: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11537: $count,'<span class="LC_filename">'.
11538: $fname.'</span>').'</p>';
11539: } else {
11540: $output = '<p class="LC_error">'.
11541: &mt('Error: update failed for: [_1].',
11542: '<span class="LC_filename">'.
11543: $container.'</span>').'</p>';
11544: }
11545: if ($context eq 'syllabus') {
11546: unless ($saveresult eq 'ok') {
11547: $skiprewrites = 1;
11548: }
11549: }
11550: } else {
11551: if (open(my $fh,'>',$container)) {
11552: print $fh $content;
11553: close($fh);
11554: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11555: $count,'<span class="LC_filename">'.
11556: $container.'</span>').'</p>';
11557: } else {
11558: $output = '<p class="LC_error">'.
11559: &mt('Error: could not update [_1].',
11560: '<span class="LC_filename">'.
11561: $container.'</span>').'</p>';
11562: }
11563: }
11564: }
11565: if (($context eq 'syllabus') && (!$skiprewrites)) {
11566: my ($actionurl,$state);
11567: $actionurl = "/public/$udom/$uname/syllabus";
11568: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11569: &ask_for_embedded_content($actionurl,$state,\%allfiles,
11570: \%codebase,
11571: {'context' => 'rewrites',
11572: 'ignore_remote_references' => 1,});
11573: if (ref($mapping) eq 'HASH') {
11574: my $rewrites = 0;
11575: foreach my $key (keys(%{$mapping})) {
11576: next if ($key =~ m{^https?://});
11577: my $ref = $mapping->{$key};
11578: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11579: my $attrib;
11580: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11581: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11582: }
11583: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11584: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11585: $rewrites += $numchg;
11586: }
11587: }
11588: if ($rewrites) {
11589: my $saveresult;
11590: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11591: if ($url eq $container) {
11592: my ($fname) = ($container =~ m{/([^/]+)$});
11593: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11594: $count,'<span class="LC_filename">'.
11595: $fname.'</span>').'</p>';
11596: } else {
11597: $output .= '<p class="LC_error">'.
11598: &mt('Error: could not update links in [_1].',
11599: '<span class="LC_filename">'.
11600: $container.'</span>').'</p>';
11601:
11602: }
11603: }
11604: }
11605: }
11606: } else {
11607: &logthis('Failed to parse '.$container.
11608: ' to modify references: '.$parse_result);
11609: }
11610: }
11611: if (wantarray) {
11612: return ($output,$count,$codebasecount);
11613: } else {
11614: return $output;
11615: }
11616: }
11617:
11618: sub check_for_existing {
11619: my ($path,$fname,$element) = @_;
11620: my ($state,$msg);
11621: if (-d $path.'/'.$fname) {
11622: $state = 'exists';
11623: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11624: } elsif (-e $path.'/'.$fname) {
11625: $state = 'exists';
11626: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11627: }
11628: if ($state eq 'exists') {
11629: $msg = '<span class="LC_error">'.$msg.'</span><br />';
11630: }
11631: return ($state,$msg);
11632: }
11633:
11634: sub check_for_upload {
11635: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11636: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11637: my $filesize = length($env{'form.'.$element});
11638: if (!$filesize) {
11639: my $msg = '<span class="LC_error">'.
11640: &mt('Unable to upload [_1]. (size = [_2] bytes)',
11641: '<span class="LC_filename">'.$fname.'</span>',
11642: $filesize).'<br />'.
11643: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11644: '</span>';
11645: return ('zero_bytes',$msg);
11646: }
11647: $filesize = $filesize/1000; #express in k (1024?)
11648: my $getpropath = 1;
11649: my ($dirlistref,$listerror) =
11650: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11651: my $found_file = 0;
11652: my $locked_file = 0;
11653: my @lockers;
11654: my $navmap;
11655: if ($env{'request.course.id'}) {
11656: $navmap = Apache::lonnavmaps::navmap->new();
11657: }
11658: if (ref($dirlistref) eq 'ARRAY') {
11659: foreach my $line (@{$dirlistref}) {
11660: my ($file_name,$rest)=split(/\&/,$line,2);
11661: if ($file_name eq $fname){
11662: $file_name = $path.$file_name;
11663: if ($group ne '') {
11664: $file_name = $group.$file_name;
11665: }
11666: $found_file = 1;
11667: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11668: foreach my $lock (@lockers) {
11669: if (ref($lock) eq 'ARRAY') {
11670: my ($symb,$crsid) = @{$lock};
11671: if ($crsid eq $env{'request.course.id'}) {
11672: if (ref($navmap)) {
11673: my $res = $navmap->getBySymb($symb);
11674: foreach my $part (@{$res->parts()}) {
11675: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11676: unless (($slot_status == $res->RESERVED) ||
11677: ($slot_status == $res->RESERVED_LOCATION)) {
11678: $locked_file = 1;
11679: }
11680: }
11681: } else {
11682: $locked_file = 1;
11683: }
11684: } else {
11685: $locked_file = 1;
11686: }
11687: }
11688: }
11689: } else {
11690: my @info = split(/\&/,$rest);
11691: my $currsize = $info[6]/1000;
11692: if ($currsize < $filesize) {
11693: my $extra = $filesize - $currsize;
11694: if (($current_disk_usage + $extra) > $disk_quota) {
11695: my $msg = '<p class="LC_warning">'.
11696: &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.',
11697: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11698: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11699: $disk_quota,$current_disk_usage).'</p>';
11700: return ('will_exceed_quota',$msg);
11701: }
11702: }
11703: }
11704: }
11705: }
11706: }
11707: if (($current_disk_usage + $filesize) > $disk_quota){
11708: my $msg = '<p class="LC_warning">'.
11709: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11710: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11711: return ('will_exceed_quota',$msg);
11712: } elsif ($found_file) {
11713: if ($locked_file) {
11714: my $msg = '<p class="LC_warning">';
11715: $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>');
11716: $msg .= '</p>';
11717: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11718: return ('file_locked',$msg);
11719: } else {
11720: my $msg = '<p class="LC_error">';
11721: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11722: $msg .= '</p>';
11723: return ('existingfile',$msg);
11724: }
11725: }
11726: }
11727:
11728: sub check_for_traversal {
11729: my ($path,$url,$toplevel) = @_;
11730: my @parts=split(/\//,$path);
11731: my $cleanpath;
11732: my $fullpath = $url;
11733: for (my $i=0;$i<@parts;$i++) {
11734: next if ($parts[$i] eq '.');
11735: if ($parts[$i] eq '..') {
11736: $fullpath =~ s{([^/]+/)$}{};
11737: } else {
11738: $fullpath .= $parts[$i].'/';
11739: }
11740: }
11741: if ($fullpath =~ /^\Q$url\E(.*)$/) {
11742: $cleanpath = $1;
11743: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11744: my $curr_toprel = $1;
11745: my @parts = split(/\//,$curr_toprel);
11746: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11747: my @urlparts = split(/\//,$url_toprel);
11748: my $doubledots;
11749: my $startdiff = -1;
11750: for (my $i=0; $i<@urlparts; $i++) {
11751: if ($startdiff == -1) {
11752: unless ($urlparts[$i] eq $parts[$i]) {
11753: $startdiff = $i;
11754: $doubledots .= '../';
11755: }
11756: } else {
11757: $doubledots .= '../';
11758: }
11759: }
11760: if ($startdiff > -1) {
11761: $cleanpath = $doubledots;
11762: for (my $i=$startdiff; $i<@parts; $i++) {
11763: $cleanpath .= $parts[$i].'/';
11764: }
11765: }
11766: }
11767: $cleanpath =~ s{(/)$}{};
11768: return $cleanpath;
11769: }
11770:
11771: sub is_archive_file {
11772: my ($mimetype) = @_;
11773: if (($mimetype eq 'application/octet-stream') ||
11774: ($mimetype eq 'application/x-stuffit') ||
11775: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11776: return 1;
11777: }
11778: return;
11779: }
11780:
11781: sub decompress_form {
11782: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11783: my %lt = &Apache::lonlocal::texthash (
11784: this => 'This file is an archive file.',
11785: camt => 'This file is a Camtasia archive file.',
11786: itsc => 'Its contents are as follows:',
11787: youm => 'You may wish to extract its contents.',
11788: extr => 'Extract contents',
11789: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11790: proa => 'Process automatically?',
11791: yes => 'Yes',
11792: no => 'No',
11793: fold => 'Title for folder containing movie',
11794: movi => 'Title for page containing embedded movie',
11795: );
11796: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11797: my ($is_camtasia,$topdir,%toplevel,@paths);
11798: my $info = &list_archive_contents($fileloc,\@paths);
11799: if (@paths) {
11800: foreach my $path (@paths) {
11801: $path =~ s{^/}{};
11802: if ($path =~ m{^([^/]+)/$}) {
11803: $topdir = $1;
11804: }
11805: if ($path =~ m{^([^/]+)/}) {
11806: $toplevel{$1} = $path;
11807: } else {
11808: $toplevel{$path} = $path;
11809: }
11810: }
11811: }
11812: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11813: my @camtasia6 = ("$topdir/","$topdir/index.html",
11814: "$topdir/media/",
11815: "$topdir/media/$topdir.mp4",
11816: "$topdir/media/FirstFrame.png",
11817: "$topdir/media/player.swf",
11818: "$topdir/media/swfobject.js",
11819: "$topdir/media/expressInstall.swf");
11820: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11821: "$topdir/$topdir.mp4",
11822: "$topdir/$topdir\_config.xml",
11823: "$topdir/$topdir\_controller.swf",
11824: "$topdir/$topdir\_embed.css",
11825: "$topdir/$topdir\_First_Frame.png",
11826: "$topdir/$topdir\_player.html",
11827: "$topdir/$topdir\_Thumbnails.png",
11828: "$topdir/playerProductInstall.swf",
11829: "$topdir/scripts/",
11830: "$topdir/scripts/config_xml.js",
11831: "$topdir/scripts/handlebars.js",
11832: "$topdir/scripts/jquery-1.7.1.min.js",
11833: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11834: "$topdir/scripts/modernizr.js",
11835: "$topdir/scripts/player-min.js",
11836: "$topdir/scripts/swfobject.js",
11837: "$topdir/skins/",
11838: "$topdir/skins/configuration_express.xml",
11839: "$topdir/skins/express_show/",
11840: "$topdir/skins/express_show/player-min.css",
11841: "$topdir/skins/express_show/spritesheet.png");
11842: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11843: "$topdir/$topdir.mp4",
11844: "$topdir/$topdir\_config.xml",
11845: "$topdir/$topdir\_controller.swf",
11846: "$topdir/$topdir\_embed.css",
11847: "$topdir/$topdir\_First_Frame.png",
11848: "$topdir/$topdir\_player.html",
11849: "$topdir/$topdir\_Thumbnails.png",
11850: "$topdir/playerProductInstall.swf",
11851: "$topdir/scripts/",
11852: "$topdir/scripts/config_xml.js",
11853: "$topdir/scripts/techsmith-smart-player.min.js",
11854: "$topdir/skins/",
11855: "$topdir/skins/configuration_express.xml",
11856: "$topdir/skins/express_show/",
11857: "$topdir/skins/express_show/spritesheet.min.css",
11858: "$topdir/skins/express_show/spritesheet.png",
11859: "$topdir/skins/express_show/techsmith-smart-player.min.css");
11860: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11861: if (@diffs == 0) {
11862: $is_camtasia = 6;
11863: } else {
11864: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11865: if (@diffs == 0) {
11866: $is_camtasia = 8;
11867: } else {
11868: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11869: if (@diffs == 0) {
11870: $is_camtasia = 8;
11871: }
11872: }
11873: }
11874: }
11875: my $output;
11876: if ($is_camtasia) {
11877: $output = <<"ENDCAM";
11878: <script type="text/javascript" language="Javascript">
11879: // <![CDATA[
11880:
11881: function camtasiaToggle() {
11882: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11883: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11884: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11885: document.getElementById('camtasia_titles').style.display='block';
11886: } else {
11887: document.getElementById('camtasia_titles').style.display='none';
11888: }
11889: }
11890: }
11891: return;
11892: }
11893:
11894: // ]]>
11895: </script>
11896: <p>$lt{'camt'}</p>
11897: ENDCAM
11898: } else {
11899: $output = '<p>'.$lt{'this'};
11900: if ($info eq '') {
11901: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11902: } else {
11903: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11904: '<div><pre>'.$info.'</pre></div>';
11905: }
11906: }
11907: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11908: my $duplicates;
11909: my $num = 0;
11910: if (ref($dirlist) eq 'ARRAY') {
11911: foreach my $item (@{$dirlist}) {
11912: if (ref($item) eq 'ARRAY') {
11913: if (exists($toplevel{$item->[0]})) {
11914: $duplicates .=
11915: &start_data_table_row().
11916: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11917: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11918: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11919: 'value="1" />'.&mt('Yes').'</label>'.
11920: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11921: '<td>'.$item->[0].'</td>';
11922: if ($item->[2]) {
11923: $duplicates .= '<td>'.&mt('Directory').'</td>';
11924: } else {
11925: $duplicates .= '<td>'.&mt('File').'</td>';
11926: }
11927: $duplicates .= '<td>'.$item->[3].'</td>'.
11928: '<td>'.
11929: &Apache::lonlocal::locallocaltime($item->[4]).
11930: '</td>'.
11931: &end_data_table_row();
11932: $num ++;
11933: }
11934: }
11935: }
11936: }
11937: my $itemcount;
11938: if (@paths > 0) {
11939: $itemcount = scalar(@paths);
11940: } else {
11941: $itemcount = 1;
11942: }
11943: if ($is_camtasia) {
11944: $output .= $lt{'auto'}.'<br />'.
11945: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11946: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11947: $lt{'yes'}.'</label> <label>'.
11948: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11949: $lt{'no'}.'</label></span><br />'.
11950: '<div id="camtasia_titles" style="display:block">'.
11951: &Apache::lonhtmlcommon::start_pick_box().
11952: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11953: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11954: &Apache::lonhtmlcommon::row_closure().
11955: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11956: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11957: &Apache::lonhtmlcommon::row_closure(1).
11958: &Apache::lonhtmlcommon::end_pick_box().
11959: '</div>';
11960: }
11961: $output .=
11962: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11963: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11964: "\n";
11965: if ($duplicates ne '') {
11966: $output .= '<p><span class="LC_warning">'.
11967: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
11968: &start_data_table().
11969: &start_data_table_header_row().
11970: '<th>'.&mt('Overwrite?').'</th>'.
11971: '<th>'.&mt('Name').'</th>'.
11972: '<th>'.&mt('Type').'</th>'.
11973: '<th>'.&mt('Size').'</th>'.
11974: '<th>'.&mt('Last modified').'</th>'.
11975: &end_data_table_header_row().
11976: $duplicates.
11977: &end_data_table().
11978: '</p>';
11979: }
11980: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11981: if (ref($hiddenelements) eq 'HASH') {
11982: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11983: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11984: }
11985: }
11986: $output .= <<"END";
11987: <br />
11988: <input type="submit" name="decompress" value="$lt{'extr'}" />
11989: </form>
11990: $noextract
11991: END
11992: return $output;
11993: }
11994:
11995: sub decompression_utility {
11996: my ($program) = @_;
11997: my @utilities = ('tar','gunzip','bunzip2','unzip');
11998: my $location;
11999: if (grep(/^\Q$program\E$/,@utilities)) {
12000: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12001: '/usr/sbin/') {
12002: if (-x $dir.$program) {
12003: $location = $dir.$program;
12004: last;
12005: }
12006: }
12007: }
12008: return $location;
12009: }
12010:
12011: sub list_archive_contents {
12012: my ($file,$pathsref) = @_;
12013: my (@cmd,$output);
12014: my $needsregexp;
12015: if ($file =~ /\.zip$/) {
12016: @cmd = (&decompression_utility('unzip'),"-l");
12017: $needsregexp = 1;
12018: } elsif (($file =~ m/\.tar\.gz$/) ||
12019: ($file =~ /\.tgz$/)) {
12020: @cmd = (&decompression_utility('tar'),"-ztf");
12021: } elsif ($file =~ /\.tar\.bz2$/) {
12022: @cmd = (&decompression_utility('tar'),"-jtf");
12023: } elsif ($file =~ m|\.tar$|) {
12024: @cmd = (&decompression_utility('tar'),"-tf");
12025: }
12026: if (@cmd) {
12027: undef($!);
12028: undef($@);
12029: if (open(my $fh,"-|", @cmd, $file)) {
12030: while (my $line = <$fh>) {
12031: $output .= $line;
12032: chomp($line);
12033: my $item;
12034: if ($needsregexp) {
12035: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12036: } else {
12037: $item = $line;
12038: }
12039: if ($item ne '') {
12040: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12041: push(@{$pathsref},$item);
12042: }
12043: }
12044: }
12045: close($fh);
12046: }
12047: }
12048: return $output;
12049: }
12050:
12051: sub decompress_uploaded_file {
12052: my ($file,$dir) = @_;
12053: &Apache::lonnet::appenv({'cgi.file' => $file});
12054: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12055: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12056: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12057: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12058: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12059: my $decompressed = $env{'cgi.decompressed'};
12060: &Apache::lonnet::delenv('cgi.file');
12061: &Apache::lonnet::delenv('cgi.dir');
12062: &Apache::lonnet::delenv('cgi.decompressed');
12063: return ($decompressed,$result);
12064: }
12065:
12066: sub process_decompression {
12067: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12068: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12069: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12070: &mt('Unexpected file path.').'</p>'."\n";
12071: }
12072: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12073: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12074: &mt('Unexpected course context.').'</p>'."\n";
12075: }
12076: unless ($file eq &Apache::lonnet::clean_filename($file)) {
12077: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12078: &mt('Filename contained unexpected characters.').'</p>'."\n";
12079: }
12080: my ($dir,$error,$warning,$output);
12081: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12082: $error = &mt('Filename not a supported archive file type.').
12083: '<br />'.&mt('Filename should end with one of: [_1].',
12084: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12085: } else {
12086: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12087: if ($docuhome eq 'no_host') {
12088: $error = &mt('Could not determine home server for course.');
12089: } else {
12090: my @ids=&Apache::lonnet::current_machine_ids();
12091: my $currdir = "$dir_root/$destination";
12092: if (grep(/^\Q$docuhome\E$/,@ids)) {
12093: $dir = &LONCAPA::propath($docudom,$docuname).
12094: "$dir_root/$destination";
12095: } else {
12096: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12097: "$dir_root/$docudom/$docuname/$destination";
12098: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12099: $error = &mt('Archive file not found.');
12100: }
12101: }
12102: my (@to_overwrite,@to_skip);
12103: if ($env{'form.archive_overwrite_total'} > 0) {
12104: my $total = $env{'form.archive_overwrite_total'};
12105: for (my $i=0; $i<$total; $i++) {
12106: if ($env{'form.archive_overwrite_'.$i} == 1) {
12107: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12108: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12109: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12110: }
12111: }
12112: }
12113: my $numskip = scalar(@to_skip);
12114: my $numoverwrite = scalar(@to_overwrite);
12115: if (($numskip) && (!$numoverwrite)) {
12116: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12117: } elsif ($dir eq '') {
12118: $error = &mt('Directory containing archive file unavailable.');
12119: } elsif (!$error) {
12120: my ($decompressed,$display);
12121: if (($numskip) || ($numoverwrite)) {
12122: my $tempdir = time.'_'.$$.int(rand(10000));
12123: mkdir("$dir/$tempdir",0755);
12124: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12125: ($decompressed,$display) =
12126: &decompress_uploaded_file($file,"$dir/$tempdir");
12127: foreach my $item (@to_skip) {
12128: if (($item ne '') && ($item !~ /\.\./)) {
12129: if (-f "$dir/$tempdir/$item") {
12130: unlink("$dir/$tempdir/$item");
12131: } elsif (-d "$dir/$tempdir/$item") {
12132: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12133: }
12134: }
12135: }
12136: foreach my $item (@to_overwrite) {
12137: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12138: if (($item ne '') && ($item !~ /\.\./)) {
12139: if (-f "$dir/$item") {
12140: unlink("$dir/$item");
12141: } elsif (-d "$dir/$item") {
12142: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12143: }
12144: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12145: }
12146: }
12147: }
12148: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12149: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12150: }
12151: }
12152: } else {
12153: ($decompressed,$display) =
12154: &decompress_uploaded_file($file,$dir);
12155: }
12156: if ($decompressed eq 'ok') {
12157: $output = '<p class="LC_info">'.
12158: &mt('Files extracted successfully from archive.').
12159: '</p>'."\n";
12160: my ($warning,$result,@contents);
12161: my ($newdirlistref,$newlisterror) =
12162: &Apache::lonnet::dirlist($currdir,$docudom,
12163: $docuname,1);
12164: my (%is_dir,%changes,@newitems);
12165: my $dirptr = 16384;
12166: if (ref($newdirlistref) eq 'ARRAY') {
12167: foreach my $dir_line (@{$newdirlistref}) {
12168: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12169: unless (($item =~ /^\.+$/) || ($item eq $file)) {
12170: push(@newitems,$item);
12171: if ($dirptr&$testdir) {
12172: $is_dir{$item} = 1;
12173: }
12174: $changes{$item} = 1;
12175: }
12176: }
12177: }
12178: if (keys(%changes) > 0) {
12179: foreach my $item (sort(@newitems)) {
12180: if ($changes{$item}) {
12181: push(@contents,$item);
12182: }
12183: }
12184: }
12185: if (@contents > 0) {
12186: my $wantform;
12187: unless ($env{'form.autoextract_camtasia'}) {
12188: $wantform = 1;
12189: }
12190: my (%children,%parent,%dirorder,%titles);
12191: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12192: $currdir,\%is_dir,
12193: \%children,\%parent,
12194: \@contents,\%dirorder,
12195: \%titles,$wantform);
12196: if ($datatable ne '') {
12197: $output .= &archive_options_form('decompressed',$datatable,
12198: $count,$hiddenelem);
12199: my $startcount = 6;
12200: $output .= &archive_javascript($startcount,$count,
12201: \%titles,\%children);
12202: }
12203: if ($env{'form.autoextract_camtasia'}) {
12204: my $version = $env{'form.autoextract_camtasia'};
12205: my %displayed;
12206: my $total = 1;
12207: $env{'form.archive_directory'} = [];
12208: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12209: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12210: $path =~ s{/$}{};
12211: my $item;
12212: if ($path ne '') {
12213: $item = "$path/$titles{$i}";
12214: } else {
12215: $item = $titles{$i};
12216: }
12217: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12218: if ($item eq $contents[0]) {
12219: push(@{$env{'form.archive_directory'}},$i);
12220: $env{'form.archive_'.$i} = 'display';
12221: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12222: $displayed{'folder'} = $i;
12223: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12224: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12225: $env{'form.archive_'.$i} = 'display';
12226: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12227: $displayed{'web'} = $i;
12228: } else {
12229: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12230: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12231: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12232: push(@{$env{'form.archive_directory'}},$i);
12233: }
12234: $env{'form.archive_'.$i} = 'dependency';
12235: }
12236: $total ++;
12237: }
12238: for (my $i=1; $i<$total; $i++) {
12239: next if ($i == $displayed{'web'});
12240: next if ($i == $displayed{'folder'});
12241: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12242: }
12243: $env{'form.phase'} = 'decompress_cleanup';
12244: $env{'form.archivedelete'} = 1;
12245: $env{'form.archive_count'} = $total-1;
12246: $output .=
12247: &process_extracted_files('coursedocs',$docudom,
12248: $docuname,$destination,
12249: $dir_root,$hiddenelem);
12250: }
12251: } else {
12252: $warning = &mt('No new items extracted from archive file.');
12253: }
12254: } else {
12255: $output = $display;
12256: $error = &mt('An error occurred during extraction from the archive file.');
12257: }
12258: }
12259: }
12260: }
12261: if ($error) {
12262: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12263: $error.'</p>'."\n";
12264: }
12265: if ($warning) {
12266: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12267: }
12268: return $output;
12269: }
12270:
12271: sub get_extracted {
12272: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12273: $titles,$wantform) = @_;
12274: my $count = 0;
12275: my $depth = 0;
12276: my $datatable;
12277: my @hierarchy;
12278: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12279: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12280: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12281: foreach my $item (@{$contents}) {
12282: $count ++;
12283: @{$dirorder->{$count}} = @hierarchy;
12284: $titles->{$count} = $item;
12285: &archive_hierarchy($depth,$count,$parent,$children);
12286: if ($wantform) {
12287: $datatable .= &archive_row($is_dir->{$item},$item,
12288: $currdir,$depth,$count);
12289: }
12290: if ($is_dir->{$item}) {
12291: $depth ++;
12292: push(@hierarchy,$count);
12293: $parent->{$depth} = $count;
12294: $datatable .=
12295: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12296: \$depth,\$count,\@hierarchy,$dirorder,
12297: $children,$parent,$titles,$wantform);
12298: $depth --;
12299: pop(@hierarchy);
12300: }
12301: }
12302: return ($count,$datatable);
12303: }
12304:
12305: sub recurse_extracted_archive {
12306: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12307: $children,$parent,$titles,$wantform) = @_;
12308: my $result='';
12309: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12310: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12311: (ref($dirorder) eq 'HASH')) {
12312: return $result;
12313: }
12314: my $dirptr = 16384;
12315: my ($newdirlistref,$newlisterror) =
12316: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12317: if (ref($newdirlistref) eq 'ARRAY') {
12318: foreach my $dir_line (@{$newdirlistref}) {
12319: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12320: unless ($item =~ /^\.+$/) {
12321: $$count ++;
12322: @{$dirorder->{$$count}} = @{$hierarchy};
12323: $titles->{$$count} = $item;
12324: &archive_hierarchy($$depth,$$count,$parent,$children);
12325:
12326: my $is_dir;
12327: if ($dirptr&$testdir) {
12328: $is_dir = 1;
12329: }
12330: if ($wantform) {
12331: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12332: }
12333: if ($is_dir) {
12334: $$depth ++;
12335: push(@{$hierarchy},$$count);
12336: $parent->{$$depth} = $$count;
12337: $result .=
12338: &recurse_extracted_archive("$currdir/$item",$docudom,
12339: $docuname,$depth,$count,
12340: $hierarchy,$dirorder,$children,
12341: $parent,$titles,$wantform);
12342: $$depth --;
12343: pop(@{$hierarchy});
12344: }
12345: }
12346: }
12347: }
12348: return $result;
12349: }
12350:
12351: sub archive_hierarchy {
12352: my ($depth,$count,$parent,$children) =@_;
12353: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12354: if (exists($parent->{$depth})) {
12355: $children->{$parent->{$depth}} .= $count.':';
12356: }
12357: }
12358: return;
12359: }
12360:
12361: sub archive_row {
12362: my ($is_dir,$item,$currdir,$depth,$count) = @_;
12363: my ($name) = ($item =~ m{([^/]+)$});
12364: my %choices = &Apache::lonlocal::texthash (
12365: 'display' => 'Add as file',
12366: 'dependency' => 'Include as dependency',
12367: 'discard' => 'Discard',
12368: );
12369: if ($is_dir) {
12370: $choices{'display'} = &mt('Add as folder');
12371: }
12372: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12373: my $offset = 0;
12374: foreach my $action ('display','dependency','discard') {
12375: $offset ++;
12376: if ($action ne 'display') {
12377: $offset ++;
12378: }
12379: $output .= '<td><span class="LC_nobreak">'.
12380: '<label><input type="radio" name="archive_'.$count.
12381: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12382: my $text = $choices{$action};
12383: if ($is_dir) {
12384: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12385: if ($action eq 'display') {
12386: $text = &mt('Add as folder');
12387: }
12388: } else {
12389: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12390:
12391: }
12392: $output .= ' /> '.$choices{$action}.'</label></span>';
12393: if ($action eq 'dependency') {
12394: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12395: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
12396: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12397: '<option value=""></option>'."\n".
12398: '</select>'."\n".
12399: '</div>';
12400: } elsif ($action eq 'display') {
12401: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12402: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12403: '</div>';
12404: }
12405: $output .= '</td>';
12406: }
12407: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12408: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
12409: for (my $i=0; $i<$depth; $i++) {
12410: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12411: }
12412: if ($is_dir) {
12413: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
12414: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12415: } else {
12416: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12417: }
12418: $output .= ' '.$name.'</td>'."\n".
12419: &end_data_table_row();
12420: return $output;
12421: }
12422:
12423: sub archive_options_form {
12424: my ($form,$display,$count,$hiddenelem) = @_;
12425: my %lt = &Apache::lonlocal::texthash(
12426: perm => 'Permanently remove archive file?',
12427: hows => 'How should each extracted item be incorporated in the course?',
12428: cont => 'Content actions for all',
12429: addf => 'Add as folder/file',
12430: incd => 'Include as dependency for a displayed file',
12431: disc => 'Discard',
12432: no => 'No',
12433: yes => 'Yes',
12434: save => 'Save',
12435: );
12436: my $output = <<"END";
12437: <form name="$form" method="post" action="">
12438: <p><span class="LC_nobreak">$lt{'perm'}
12439: <label>
12440: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12441: </label>
12442:
12443: <label>
12444: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12445: </span>
12446: </p>
12447: <input type="hidden" name="phase" value="decompress_cleanup" />
12448: <br />$lt{'hows'}
12449: <div class="LC_columnSection">
12450: <fieldset>
12451: <legend>$lt{'cont'}</legend>
12452: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
12453: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12454: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12455: </fieldset>
12456: </div>
12457: END
12458: return $output.
12459: &start_data_table()."\n".
12460: $display."\n".
12461: &end_data_table()."\n".
12462: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12463: $hiddenelem.
12464: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12465: '</form>';
12466: }
12467:
12468: sub archive_javascript {
12469: my ($startcount,$numitems,$titles,$children) = @_;
12470: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12471: my $maintitle = $env{'form.comment'};
12472: my $scripttag = <<START;
12473: <script type="text/javascript">
12474: // <![CDATA[
12475:
12476: function checkAll(form,prefix) {
12477: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
12478: for (var i=0; i < form.elements.length; i++) {
12479: var id = form.elements[i].id;
12480: if ((id != '') && (id != undefined)) {
12481: if (idstr.test(id)) {
12482: if (form.elements[i].type == 'radio') {
12483: form.elements[i].checked = true;
12484: var nostart = i-$startcount;
12485: var offset = nostart%7;
12486: var count = (nostart-offset)/7;
12487: dependencyCheck(form,count,offset);
12488: }
12489: }
12490: }
12491: }
12492: }
12493:
12494: function propagateCheck(form,count) {
12495: if (count > 0) {
12496: var startelement = $startcount + ((count-1) * 7);
12497: for (var j=1; j<6; j++) {
12498: if ((j != 2) && (j != 4)) {
12499: var item = startelement + j;
12500: if (form.elements[item].type == 'radio') {
12501: if (form.elements[item].checked) {
12502: containerCheck(form,count,j);
12503: break;
12504: }
12505: }
12506: }
12507: }
12508: }
12509: }
12510:
12511: numitems = $numitems
12512: var titles = new Array(numitems);
12513: var parents = new Array(numitems);
12514: for (var i=0; i<numitems; i++) {
12515: parents[i] = new Array;
12516: }
12517: var maintitle = '$maintitle';
12518:
12519: START
12520:
12521: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12522: my @contents = split(/:/,$children->{$container});
12523: for (my $i=0; $i<@contents; $i ++) {
12524: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12525: }
12526: }
12527:
12528: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12529: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12530: }
12531:
12532: $scripttag .= <<END;
12533:
12534: function containerCheck(form,count,offset) {
12535: if (count > 0) {
12536: dependencyCheck(form,count,offset);
12537: var item = (offset+$startcount)+7*(count-1);
12538: form.elements[item].checked = true;
12539: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12540: if (parents[count].length > 0) {
12541: for (var j=0; j<parents[count].length; j++) {
12542: containerCheck(form,parents[count][j],offset);
12543: }
12544: }
12545: }
12546: }
12547: }
12548:
12549: function dependencyCheck(form,count,offset) {
12550: if (count > 0) {
12551: var chosen = (offset+$startcount)+7*(count-1);
12552: var depitem = $startcount + ((count-1) * 7) + 4;
12553: var currtype = form.elements[depitem].type;
12554: if (form.elements[chosen].value == 'dependency') {
12555: document.getElementById('arc_depon_'+count).style.display='block';
12556: form.elements[depitem].options.length = 0;
12557: form.elements[depitem].options[0] = new Option('Select','',true,true);
12558: for (var i=1; i<=numitems; i++) {
12559: if (i == count) {
12560: continue;
12561: }
12562: var startelement = $startcount + (i-1) * 7;
12563: for (var j=1; j<6; j++) {
12564: if ((j != 2) && (j!= 4)) {
12565: var item = startelement + j;
12566: if (form.elements[item].type == 'radio') {
12567: if (form.elements[item].checked) {
12568: if (form.elements[item].value == 'display') {
12569: var n = form.elements[depitem].options.length;
12570: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12571: }
12572: }
12573: }
12574: }
12575: }
12576: }
12577: } else {
12578: document.getElementById('arc_depon_'+count).style.display='none';
12579: form.elements[depitem].options.length = 0;
12580: form.elements[depitem].options[0] = new Option('Select','',true,true);
12581: }
12582: titleCheck(form,count,offset);
12583: }
12584: }
12585:
12586: function propagateSelect(form,count,offset) {
12587: if (count > 0) {
12588: var item = (1+offset+$startcount)+7*(count-1);
12589: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
12590: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12591: if (parents[count].length > 0) {
12592: for (var j=0; j<parents[count].length; j++) {
12593: containerSelect(form,parents[count][j],offset,picked);
12594: }
12595: }
12596: }
12597: }
12598: }
12599:
12600: function containerSelect(form,count,offset,picked) {
12601: if (count > 0) {
12602: var item = (offset+$startcount)+7*(count-1);
12603: if (form.elements[item].type == 'radio') {
12604: if (form.elements[item].value == 'dependency') {
12605: if (form.elements[item+1].type == 'select-one') {
12606: for (var i=0; i<form.elements[item+1].options.length; i++) {
12607: if (form.elements[item+1].options[i].value == picked) {
12608: form.elements[item+1].selectedIndex = i;
12609: break;
12610: }
12611: }
12612: }
12613: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12614: if (parents[count].length > 0) {
12615: for (var j=0; j<parents[count].length; j++) {
12616: containerSelect(form,parents[count][j],offset,picked);
12617: }
12618: }
12619: }
12620: }
12621: }
12622: }
12623: }
12624:
12625: function titleCheck(form,count,offset) {
12626: if (count > 0) {
12627: var chosen = (offset+$startcount)+7*(count-1);
12628: var depitem = $startcount + ((count-1) * 7) + 2;
12629: var currtype = form.elements[depitem].type;
12630: if (form.elements[chosen].value == 'display') {
12631: document.getElementById('arc_title_'+count).style.display='block';
12632: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12633: document.getElementById('archive_title_'+count).value=maintitle;
12634: }
12635: } else {
12636: document.getElementById('arc_title_'+count).style.display='none';
12637: if (currtype == 'text') {
12638: document.getElementById('archive_title_'+count).value='';
12639: }
12640: }
12641: }
12642: return;
12643: }
12644:
12645: // ]]>
12646: </script>
12647: END
12648: return $scripttag;
12649: }
12650:
12651: sub process_extracted_files {
12652: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12653: my $numitems = $env{'form.archive_count'};
12654: return if ((!$numitems) || ($numitems =~ /\D/));
12655: my @ids=&Apache::lonnet::current_machine_ids();
12656: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12657: %folders,%containers,%mapinner,%prompttofetch);
12658: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12659: if (grep(/^\Q$docuhome\E$/,@ids)) {
12660: $prefix = &LONCAPA::propath($docudom,$docuname);
12661: $pathtocheck = "$dir_root/$destination";
12662: $dir = $dir_root;
12663: $ishome = 1;
12664: } else {
12665: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12666: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12667: $dir = "$dir_root/$docudom/$docuname";
12668: }
12669: my $currdir = "$dir_root/$destination";
12670: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12671: if ($env{'form.folderpath'}) {
12672: my @items = split('&',$env{'form.folderpath'});
12673: $folders{'0'} = $items[-2];
12674: if ($env{'form.folderpath'} =~ /\:1$/) {
12675: $containers{'0'}='page';
12676: } else {
12677: $containers{'0'}='sequence';
12678: }
12679: }
12680: my @archdirs = &get_env_multiple('form.archive_directory');
12681: if ($numitems) {
12682: for (my $i=1; $i<=$numitems; $i++) {
12683: my $path = $env{'form.archive_content_'.$i};
12684: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12685: my $item = $1;
12686: $toplevelitems{$item} = $i;
12687: if (grep(/^\Q$i\E$/,@archdirs)) {
12688: $is_dir{$item} = 1;
12689: }
12690: }
12691: }
12692: }
12693: my ($output,%children,%parent,%titles,%dirorder,$result);
12694: if (keys(%toplevelitems) > 0) {
12695: my @contents = sort(keys(%toplevelitems));
12696: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12697: \%parent,\@contents,\%dirorder,\%titles);
12698: }
12699: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12700: if ($numitems) {
12701: for (my $i=1; $i<=$numitems; $i++) {
12702: next if ($env{'form.archive_'.$i} eq 'dependency');
12703: my $path = $env{'form.archive_content_'.$i};
12704: if ($path =~ /^\Q$pathtocheck\E/) {
12705: if ($env{'form.archive_'.$i} eq 'discard') {
12706: if ($prefix ne '' && $path ne '') {
12707: if (-e $prefix.$path) {
12708: if ((@archdirs > 0) &&
12709: (grep(/^\Q$i\E$/,@archdirs))) {
12710: $todeletedir{$prefix.$path} = 1;
12711: } else {
12712: $todelete{$prefix.$path} = 1;
12713: }
12714: }
12715: }
12716: } elsif ($env{'form.archive_'.$i} eq 'display') {
12717: my ($docstitle,$title,$url,$outer);
12718: ($title) = ($path =~ m{/([^/]+)$});
12719: $docstitle = $env{'form.archive_title_'.$i};
12720: if ($docstitle eq '') {
12721: $docstitle = $title;
12722: }
12723: $outer = 0;
12724: if (ref($dirorder{$i}) eq 'ARRAY') {
12725: if (@{$dirorder{$i}} > 0) {
12726: foreach my $item (reverse(@{$dirorder{$i}})) {
12727: if ($env{'form.archive_'.$item} eq 'display') {
12728: $outer = $item;
12729: last;
12730: }
12731: }
12732: }
12733: }
12734: my ($errtext,$fatal) =
12735: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12736: '/'.$folders{$outer}.'.'.
12737: $containers{$outer});
12738: next if ($fatal);
12739: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12740: if ($context eq 'coursedocs') {
12741: $mapinner{$i} = time;
12742: $folders{$i} = 'default_'.$mapinner{$i};
12743: $containers{$i} = 'sequence';
12744: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12745: $folders{$i}.'.'.$containers{$i};
12746: my $newidx = &LONCAPA::map::getresidx();
12747: $LONCAPA::map::resources[$newidx]=
12748: $docstitle.':'.$url.':false:normal:res';
12749: push(@LONCAPA::map::order,$newidx);
12750: my ($outtext,$errtext) =
12751: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12752: $docuname.'/'.$folders{$outer}.
12753: '.'.$containers{$outer},1,1);
12754: $newseqid{$i} = $newidx;
12755: unless ($errtext) {
12756: $result .= '<li>'.&mt('Folder: [_1] added to course',
12757: &HTML::Entities::encode($docstitle,'<>&"'))..
12758: '</li>'."\n";
12759: }
12760: }
12761: } else {
12762: if ($context eq 'coursedocs') {
12763: my $newidx=&LONCAPA::map::getresidx();
12764: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12765: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12766: $title;
12767: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12768: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12769: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12770: }
12771: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12772: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12773: }
12774: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12775: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12776: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12777: unless ($ishome) {
12778: my $fetch = "$newdest{$i}/$title";
12779: $fetch =~ s/^\Q$prefix$dir\E//;
12780: $prompttofetch{$fetch} = 1;
12781: }
12782: }
12783: }
12784: $LONCAPA::map::resources[$newidx]=
12785: $docstitle.':'.$url.':false:normal:res';
12786: push(@LONCAPA::map::order, $newidx);
12787: my ($outtext,$errtext)=
12788: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12789: $docuname.'/'.$folders{$outer}.
12790: '.'.$containers{$outer},1,1);
12791: unless ($errtext) {
12792: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12793: $result .= '<li>'.&mt('File: [_1] added to course',
12794: &HTML::Entities::encode($docstitle,'<>&"')).
12795: '</li>'."\n";
12796: }
12797: }
12798: } else {
12799: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12800: &HTML::Entities::encode($path,'<>&"')).'<br />';
12801: }
12802: }
12803: }
12804: }
12805: } else {
12806: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12807: &HTML::Entities::encode($path,'<>&"')).'<br />';
12808: }
12809: }
12810: for (my $i=1; $i<=$numitems; $i++) {
12811: next unless ($env{'form.archive_'.$i} eq 'dependency');
12812: my $path = $env{'form.archive_content_'.$i};
12813: if ($path =~ /^\Q$pathtocheck\E/) {
12814: my ($title) = ($path =~ m{/([^/]+)$});
12815: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12816: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12817: if (ref($dirorder{$i}) eq 'ARRAY') {
12818: my ($itemidx,$fullpath,$relpath);
12819: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12820: my $container = $dirorder{$referrer{$i}}->[-1];
12821: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12822: if ($dirorder{$i}->[$j] eq $container) {
12823: $itemidx = $j;
12824: }
12825: }
12826: }
12827: if ($itemidx eq '') {
12828: $itemidx = 0;
12829: }
12830: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12831: if ($mapinner{$referrer{$i}}) {
12832: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12833: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12834: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12835: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12836: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12837: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12838: if (!-e $fullpath) {
12839: mkdir($fullpath,0755);
12840: }
12841: }
12842: } else {
12843: last;
12844: }
12845: }
12846: }
12847: } elsif ($newdest{$referrer{$i}}) {
12848: $fullpath = $newdest{$referrer{$i}};
12849: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12850: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12851: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12852: last;
12853: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12854: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12855: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12856: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12857: if (!-e $fullpath) {
12858: mkdir($fullpath,0755);
12859: }
12860: }
12861: } else {
12862: last;
12863: }
12864: }
12865: }
12866: if ($fullpath ne '') {
12867: if (-e "$prefix$path") {
12868: unless (rename("$prefix$path","$fullpath/$title")) {
12869: $warning .= &mt('Failed to rename dependency').'<br />';
12870: }
12871: }
12872: if (-e "$fullpath/$title") {
12873: my $showpath;
12874: if ($relpath ne '') {
12875: $showpath = "$relpath/$title";
12876: } else {
12877: $showpath = "/$title";
12878: }
12879: $result .= '<li>'.&mt('[_1] included as a dependency',
12880: &HTML::Entities::encode($showpath,'<>&"')).
12881: '</li>'."\n";
12882: unless ($ishome) {
12883: my $fetch = "$fullpath/$title";
12884: $fetch =~ s/^\Q$prefix$dir\E//;
12885: $prompttofetch{$fetch} = 1;
12886: }
12887: }
12888: }
12889: }
12890: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12891: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12892: &HTML::Entities::encode($path,'<>&"'),
12893: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12894: '<br />';
12895: }
12896: } else {
12897: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12898: &HTML::Entities::encode($path)).'<br />';
12899: }
12900: }
12901: if (keys(%todelete)) {
12902: foreach my $key (keys(%todelete)) {
12903: unlink($key);
12904: }
12905: }
12906: if (keys(%todeletedir)) {
12907: foreach my $key (keys(%todeletedir)) {
12908: rmdir($key);
12909: }
12910: }
12911: foreach my $dir (sort(keys(%is_dir))) {
12912: if (($pathtocheck ne '') && ($dir ne '')) {
12913: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12914: }
12915: }
12916: if ($result ne '') {
12917: $output .= '<ul>'."\n".
12918: $result."\n".
12919: '</ul>';
12920: }
12921: unless ($ishome) {
12922: my $replicationfail;
12923: foreach my $item (keys(%prompttofetch)) {
12924: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12925: unless ($fetchresult eq 'ok') {
12926: $replicationfail .= '<li>'.$item.'</li>'."\n";
12927: }
12928: }
12929: if ($replicationfail) {
12930: $output .= '<p class="LC_error">'.
12931: &mt('Course home server failed to retrieve:').'<ul>'.
12932: $replicationfail.
12933: '</ul></p>';
12934: }
12935: }
12936: } else {
12937: $warning = &mt('No items found in archive.');
12938: }
12939: if ($error) {
12940: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12941: $error.'</p>'."\n";
12942: }
12943: if ($warning) {
12944: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12945: }
12946: return $output;
12947: }
12948:
12949: sub cleanup_empty_dirs {
12950: my ($path) = @_;
12951: if (($path ne '') && (-d $path)) {
12952: if (opendir(my $dirh,$path)) {
12953: my @dircontents = grep(!/^\./,readdir($dirh));
12954: my $numitems = 0;
12955: foreach my $item (@dircontents) {
12956: if (-d "$path/$item") {
12957: &cleanup_empty_dirs("$path/$item");
12958: if (-e "$path/$item") {
12959: $numitems ++;
12960: }
12961: } else {
12962: $numitems ++;
12963: }
12964: }
12965: if ($numitems == 0) {
12966: rmdir($path);
12967: }
12968: closedir($dirh);
12969: }
12970: }
12971: return;
12972: }
12973:
12974: =pod
12975:
12976: =item * &get_folder_hierarchy()
12977:
12978: Provides hierarchy of names of folders/sub-folders containing the current
12979: item,
12980:
12981: Inputs: 3
12982: - $navmap - navmaps object
12983:
12984: - $map - url for map (either the trigger itself, or map containing
12985: the resource, which is the trigger).
12986:
12987: - $showitem - 1 => show title for map itself; 0 => do not show.
12988:
12989: Outputs: 1 @pathitems - array of folder/subfolder names.
12990:
12991: =cut
12992:
12993: sub get_folder_hierarchy {
12994: my ($navmap,$map,$showitem) = @_;
12995: my @pathitems;
12996: if (ref($navmap)) {
12997: my $mapres = $navmap->getResourceByUrl($map);
12998: if (ref($mapres)) {
12999: my $pcslist = $mapres->map_hierarchy();
13000: if ($pcslist ne '') {
13001: my @pcs = split(/,/,$pcslist);
13002: foreach my $pc (@pcs) {
13003: if ($pc == 1) {
13004: push(@pathitems,&mt('Main Content'));
13005: } else {
13006: my $res = $navmap->getByMapPc($pc);
13007: if (ref($res)) {
13008: my $title = $res->compTitle();
13009: $title =~ s/\W+/_/g;
13010: if ($title ne '') {
13011: push(@pathitems,$title);
13012: }
13013: }
13014: }
13015: }
13016: }
13017: if ($showitem) {
13018: if ($mapres->{ID} eq '0.0') {
13019: push(@pathitems,&mt('Main Content'));
13020: } else {
13021: my $maptitle = $mapres->compTitle();
13022: $maptitle =~ s/\W+/_/g;
13023: if ($maptitle ne '') {
13024: push(@pathitems,$maptitle);
13025: }
13026: }
13027: }
13028: }
13029: }
13030: return @pathitems;
13031: }
13032:
13033: =pod
13034:
13035: =item * &get_turnedin_filepath()
13036:
13037: Determines path in a user's portfolio file for storage of files uploaded
13038: to a specific essayresponse or dropbox item.
13039:
13040: Inputs: 3 required + 1 optional.
13041: $symb is symb for resource, $uname and $udom are for current user (required).
13042: $caller is optional (can be "submission", if routine is called when storing
13043: an upoaded file when "Submit Answer" button was pressed).
13044:
13045: Returns array containing $path and $multiresp.
13046: $path is path in portfolio. $multiresp is 1 if this resource contains more
13047: than one file upload item. Callers of routine should append partid as a
13048: subdirectory to $path in cases where $multiresp is 1.
13049:
13050: Called by: homework/essayresponse.pm and homework/structuretags.pm
13051:
13052: =cut
13053:
13054: sub get_turnedin_filepath {
13055: my ($symb,$uname,$udom,$caller) = @_;
13056: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13057: my $turnindir;
13058: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13059: $turnindir = $userhash{'turnindir'};
13060: my ($path,$multiresp);
13061: if ($turnindir eq '') {
13062: if ($caller eq 'submission') {
13063: $turnindir = &mt('turned in');
13064: $turnindir =~ s/\W+/_/g;
13065: my %newhash = (
13066: 'turnindir' => $turnindir,
13067: );
13068: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13069: }
13070: }
13071: if ($turnindir ne '') {
13072: $path = '/'.$turnindir.'/';
13073: my ($multipart,$turnin,@pathitems);
13074: my $navmap = Apache::lonnavmaps::navmap->new();
13075: if (defined($navmap)) {
13076: my $mapres = $navmap->getResourceByUrl($map);
13077: if (ref($mapres)) {
13078: my $pcslist = $mapres->map_hierarchy();
13079: if ($pcslist ne '') {
13080: foreach my $pc (split(/,/,$pcslist)) {
13081: my $res = $navmap->getByMapPc($pc);
13082: if (ref($res)) {
13083: my $title = $res->compTitle();
13084: $title =~ s/\W+/_/g;
13085: if ($title ne '') {
13086: if (($pc > 1) && (length($title) > 12)) {
13087: $title = substr($title,0,12);
13088: }
13089: push(@pathitems,$title);
13090: }
13091: }
13092: }
13093: }
13094: my $maptitle = $mapres->compTitle();
13095: $maptitle =~ s/\W+/_/g;
13096: if ($maptitle ne '') {
13097: if (length($maptitle) > 12) {
13098: $maptitle = substr($maptitle,0,12);
13099: }
13100: push(@pathitems,$maptitle);
13101: }
13102: unless ($env{'request.state'} eq 'construct') {
13103: my $res = $navmap->getBySymb($symb);
13104: if (ref($res)) {
13105: my $partlist = $res->parts();
13106: my $totaluploads = 0;
13107: if (ref($partlist) eq 'ARRAY') {
13108: foreach my $part (@{$partlist}) {
13109: my @types = $res->responseType($part);
13110: my @ids = $res->responseIds($part);
13111: for (my $i=0; $i < scalar(@ids); $i++) {
13112: if ($types[$i] eq 'essay') {
13113: my $partid = $part.'_'.$ids[$i];
13114: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13115: $totaluploads ++;
13116: }
13117: }
13118: }
13119: }
13120: if ($totaluploads > 1) {
13121: $multiresp = 1;
13122: }
13123: }
13124: }
13125: }
13126: } else {
13127: return;
13128: }
13129: } else {
13130: return;
13131: }
13132: my $restitle=&Apache::lonnet::gettitle($symb);
13133: $restitle =~ s/\W+/_/g;
13134: if ($restitle eq '') {
13135: $restitle = ($resurl =~ m{/[^/]+$});
13136: if ($restitle eq '') {
13137: $restitle = time;
13138: }
13139: }
13140: if (length($restitle) > 12) {
13141: $restitle = substr($restitle,0,12);
13142: }
13143: push(@pathitems,$restitle);
13144: $path .= join('/',@pathitems);
13145: }
13146: return ($path,$multiresp);
13147: }
13148:
13149: =pod
13150:
13151: =back
13152:
13153: =head1 CSV Upload/Handling functions
13154:
13155: =over 4
13156:
13157: =item * &upfile_store($r)
13158:
13159: Store uploaded file, $r should be the HTTP Request object,
13160: needs $env{'form.upfile'}
13161: returns $datatoken to be put into hidden field
13162:
13163: =cut
13164:
13165: sub upfile_store {
13166: my $r=shift;
13167: $env{'form.upfile'}=~s/\r/\n/gs;
13168: $env{'form.upfile'}=~s/\f/\n/gs;
13169: $env{'form.upfile'}=~s/\n+/\n/gs;
13170: $env{'form.upfile'}=~s/\n+$//gs;
13171:
13172: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13173: '_enroll_'.$env{'request.course.id'}.'_'.
13174: time.'_'.$$);
13175: return if ($datatoken eq '');
13176:
13177: {
13178: my $datafile = $r->dir_config('lonDaemons').
13179: '/tmp/'.$datatoken.'.tmp';
13180: if ( open(my $fh,'>',$datafile) ) {
13181: print $fh $env{'form.upfile'};
13182: close($fh);
13183: }
13184: }
13185: return $datatoken;
13186: }
13187:
13188: =pod
13189:
13190: =item * &load_tmp_file($r,$datatoken)
13191:
13192: Load uploaded file from tmp, $r should be the HTTP Request object,
13193: $datatoken is the name to assign to the temporary file.
13194: sets $env{'form.upfile'} to the contents of the file
13195:
13196: =cut
13197:
13198: sub load_tmp_file {
13199: my ($r,$datatoken) = @_;
13200: return if ($datatoken eq '');
13201: my @studentdata=();
13202: {
13203: my $studentfile = $r->dir_config('lonDaemons').
13204: '/tmp/'.$datatoken.'.tmp';
13205: if ( open(my $fh,'<',$studentfile) ) {
13206: @studentdata=<$fh>;
13207: close($fh);
13208: }
13209: }
13210: $env{'form.upfile'}=join('',@studentdata);
13211: }
13212:
13213: sub valid_datatoken {
13214: my ($datatoken) = @_;
13215: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13216: return $datatoken;
13217: }
13218: return;
13219: }
13220:
13221: =pod
13222:
13223: =item * &upfile_record_sep()
13224:
13225: Separate uploaded file into records
13226: returns array of records,
13227: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13228:
13229: =cut
13230:
13231: sub upfile_record_sep {
13232: if ($env{'form.upfiletype'} eq 'xml') {
13233: } else {
13234: my @records;
13235: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13236: if ($line=~/^\s*$/) { next; }
13237: push(@records,$line);
13238: }
13239: return @records;
13240: }
13241: }
13242:
13243: =pod
13244:
13245: =item * &record_sep($record)
13246:
13247: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13248:
13249: =cut
13250:
13251: sub takeleft {
13252: my $index=shift;
13253: return substr('0000'.$index,-4,4);
13254: }
13255:
13256: sub record_sep {
13257: my $record=shift;
13258: my %components=();
13259: if ($env{'form.upfiletype'} eq 'xml') {
13260: } elsif ($env{'form.upfiletype'} eq 'space') {
13261: my $i=0;
13262: foreach my $field (split(/\s+/,$record)) {
13263: $field=~s/^(\"|\')//;
13264: $field=~s/(\"|\')$//;
13265: $components{&takeleft($i)}=$field;
13266: $i++;
13267: }
13268: } elsif ($env{'form.upfiletype'} eq 'tab') {
13269: my $i=0;
13270: foreach my $field (split(/\t/,$record)) {
13271: $field=~s/^(\"|\')//;
13272: $field=~s/(\"|\')$//;
13273: $components{&takeleft($i)}=$field;
13274: $i++;
13275: }
13276: } else {
13277: my $separator=',';
13278: if ($env{'form.upfiletype'} eq 'semisv') {
13279: $separator=';';
13280: }
13281: my $i=0;
13282: # the character we are looking for to indicate the end of a quote or a record
13283: my $looking_for=$separator;
13284: # do not add the characters to the fields
13285: my $ignore=0;
13286: # we just encountered a separator (or the beginning of the record)
13287: my $just_found_separator=1;
13288: # store the field we are working on here
13289: my $field='';
13290: # work our way through all characters in record
13291: foreach my $character ($record=~/(.)/g) {
13292: if ($character eq $looking_for) {
13293: if ($character ne $separator) {
13294: # Found the end of a quote, again looking for separator
13295: $looking_for=$separator;
13296: $ignore=1;
13297: } else {
13298: # Found a separator, store away what we got
13299: $components{&takeleft($i)}=$field;
13300: $i++;
13301: $just_found_separator=1;
13302: $ignore=0;
13303: $field='';
13304: }
13305: next;
13306: }
13307: # single or double quotation marks after a separator indicate beginning of a quote
13308: # we are now looking for the end of the quote and need to ignore separators
13309: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13310: $looking_for=$character;
13311: next;
13312: }
13313: # ignore would be true after we reached the end of a quote
13314: if ($ignore) { next; }
13315: if (($just_found_separator) && ($character=~/\s/)) { next; }
13316: $field.=$character;
13317: $just_found_separator=0;
13318: }
13319: # catch the very last entry, since we never encountered the separator
13320: $components{&takeleft($i)}=$field;
13321: }
13322: return %components;
13323: }
13324:
13325: ######################################################
13326: ######################################################
13327:
13328: =pod
13329:
13330: =item * &upfile_select_html()
13331:
13332: Return HTML code to select a file from the users machine and specify
13333: the file type.
13334:
13335: =cut
13336:
13337: ######################################################
13338: ######################################################
13339: sub upfile_select_html {
13340: my %Types = (
13341: csv => &mt('CSV (comma separated values, spreadsheet)'),
13342: semisv => &mt('Semicolon separated values'),
13343: space => &mt('Space separated'),
13344: tab => &mt('Tabulator separated'),
13345: # xml => &mt('HTML/XML'),
13346: );
13347: my $Str = '<input type="file" name="upfile" size="50" />'.
13348: '<br />'.&mt('Type').': <select name="upfiletype">';
13349: foreach my $type (sort(keys(%Types))) {
13350: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13351: }
13352: $Str .= "</select>\n";
13353: return $Str;
13354: }
13355:
13356: sub get_samples {
13357: my ($records,$toget) = @_;
13358: my @samples=({});
13359: my $got=0;
13360: foreach my $rec (@$records) {
13361: my %temp = &record_sep($rec);
13362: if (! grep(/\S/, values(%temp))) { next; }
13363: if (%temp) {
13364: $samples[$got]=\%temp;
13365: $got++;
13366: if ($got == $toget) { last; }
13367: }
13368: }
13369: return \@samples;
13370: }
13371:
13372: ######################################################
13373: ######################################################
13374:
13375: =pod
13376:
13377: =item * &csv_print_samples($r,$records)
13378:
13379: Prints a table of sample values from each column uploaded $r is an
13380: Apache Request ref, $records is an arrayref from
13381: &Apache::loncommon::upfile_record_sep
13382:
13383: =cut
13384:
13385: ######################################################
13386: ######################################################
13387: sub csv_print_samples {
13388: my ($r,$records) = @_;
13389: my $samples = &get_samples($records,5);
13390:
13391: $r->print(&mt('Samples').'<br />'.&start_data_table().
13392: &start_data_table_header_row());
13393: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13394: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13395: $r->print(&end_data_table_header_row());
13396: foreach my $hash (@$samples) {
13397: $r->print(&start_data_table_row());
13398: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13399: $r->print('<td>');
13400: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13401: $r->print('</td>');
13402: }
13403: $r->print(&end_data_table_row());
13404: }
13405: $r->print(&end_data_table().'<br />'."\n");
13406: }
13407:
13408: ######################################################
13409: ######################################################
13410:
13411: =pod
13412:
13413: =item * &csv_print_select_table($r,$records,$d)
13414:
13415: Prints a table to create associations between values and table columns.
13416:
13417: $r is an Apache Request ref,
13418: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13419: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13420:
13421: =cut
13422:
13423: ######################################################
13424: ######################################################
13425: sub csv_print_select_table {
13426: my ($r,$records,$d) = @_;
13427: my $i=0;
13428: my $samples = &get_samples($records,1);
13429: $r->print(&mt('Associate columns with student attributes.')."\n".
13430: &start_data_table().&start_data_table_header_row().
13431: '<th>'.&mt('Attribute').'</th>'.
13432: '<th>'.&mt('Column').'</th>'.
13433: &end_data_table_header_row()."\n");
13434: foreach my $array_ref (@$d) {
13435: my ($value,$display,$defaultcol)=@{ $array_ref };
13436: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
13437:
13438: $r->print('<td><select name="f'.$i.'"'.
13439: ' onchange="javascript:flip(this.form,'.$i.');">');
13440: $r->print('<option value="none"></option>');
13441: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13442: $r->print('<option value="'.$sample.'"'.
13443: ($sample eq $defaultcol ? ' selected="selected" ' : '').
13444: '>'.&mt('Column [_1]',($sample+1)).'</option>');
13445: }
13446: $r->print('</select></td>'.&end_data_table_row()."\n");
13447: $i++;
13448: }
13449: $r->print(&end_data_table());
13450: $i--;
13451: return $i;
13452: }
13453:
13454: ######################################################
13455: ######################################################
13456:
13457: =pod
13458:
13459: =item * &csv_samples_select_table($r,$records,$d)
13460:
13461: Prints a table of sample values from the upload and can make associate samples to internal names.
13462:
13463: $r is an Apache Request ref,
13464: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13465: $d is an array of 2 element arrays (internal name, displayed name)
13466:
13467: =cut
13468:
13469: ######################################################
13470: ######################################################
13471: sub csv_samples_select_table {
13472: my ($r,$records,$d) = @_;
13473: my $i=0;
13474: #
13475: my $max_samples = 5;
13476: my $samples = &get_samples($records,$max_samples);
13477: $r->print(&start_data_table().
13478: &start_data_table_header_row().'<th>'.
13479: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13480: &end_data_table_header_row());
13481:
13482: foreach my $key (sort(keys(%{ $samples->[0] }))) {
13483: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13484: ' onchange="javascript:flip(this.form,'.$i.');">');
13485: foreach my $option (@$d) {
13486: my ($value,$display,$defaultcol)=@{ $option };
13487: $r->print('<option value="'.$value.'"'.
13488: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13489: $display.'</option>');
13490: }
13491: $r->print('</select></td><td>');
13492: foreach my $line (0..($max_samples-1)) {
13493: if (defined($samples->[$line]{$key})) {
13494: $r->print($samples->[$line]{$key}."<br />\n");
13495: }
13496: }
13497: $r->print('</td>'.&end_data_table_row());
13498: $i++;
13499: }
13500: $r->print(&end_data_table());
13501: $i--;
13502: return($i);
13503: }
13504:
13505: ######################################################
13506: ######################################################
13507:
13508: =pod
13509:
13510: =item * &clean_excel_name($name)
13511:
13512: Returns a replacement for $name which does not contain any illegal characters.
13513:
13514: =cut
13515:
13516: ######################################################
13517: ######################################################
13518: sub clean_excel_name {
13519: my ($name) = @_;
13520: $name =~ s/[:\*\?\/\\]//g;
13521: if (length($name) > 31) {
13522: $name = substr($name,0,31);
13523: }
13524: return $name;
13525: }
13526:
13527: =pod
13528:
13529: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13530:
13531: Returns either 1 or undef
13532:
13533: 1 if the part is to be hidden, undef if it is to be shown
13534:
13535: Arguments are:
13536:
13537: $id the id of the part to be checked
13538: $symb, optional the symb of the resource to check
13539: $udom, optional the domain of the user to check for
13540: $uname, optional the username of the user to check for
13541:
13542: =cut
13543:
13544: sub check_if_partid_hidden {
13545: my ($id,$symb,$udom,$uname) = @_;
13546: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13547: $symb,$udom,$uname);
13548: my $truth=1;
13549: #if the string starts with !, then the list is the list to show not hide
13550: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13551: my @hiddenlist=split(/,/,$hiddenparts);
13552: foreach my $checkid (@hiddenlist) {
13553: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13554: }
13555: return !$truth;
13556: }
13557:
13558:
13559: ############################################################
13560: ############################################################
13561:
13562: =pod
13563:
13564: =back
13565:
13566: =head1 cgi-bin script and graphing routines
13567:
13568: =over 4
13569:
13570: =item * &get_cgi_id()
13571:
13572: Inputs: none
13573:
13574: Returns an id which can be used to pass environment variables
13575: to various cgi-bin scripts. These environment variables will
13576: be removed from the users environment after a given time by
13577: the routine &Apache::lonnet::transfer_profile_to_env.
13578:
13579: =cut
13580:
13581: ############################################################
13582: ############################################################
13583: my $uniq=0;
13584: sub get_cgi_id {
13585: $uniq=($uniq+1)%100000;
13586: return (time.'_'.$$.'_'.$uniq);
13587: }
13588:
13589: ############################################################
13590: ############################################################
13591:
13592: =pod
13593:
13594: =item * &DrawBarGraph()
13595:
13596: Facilitates the plotting of data in a (stacked) bar graph.
13597: Puts plot definition data into the users environment in order for
13598: graph.png to plot it. Returns an <img> tag for the plot.
13599: The bars on the plot are labeled '1','2',...,'n'.
13600:
13601: Inputs:
13602:
13603: =over 4
13604:
13605: =item $Title: string, the title of the plot
13606:
13607: =item $xlabel: string, text describing the X-axis of the plot
13608:
13609: =item $ylabel: string, text describing the Y-axis of the plot
13610:
13611: =item $Max: scalar, the maximum Y value to use in the plot
13612: If $Max is < any data point, the graph will not be rendered.
13613:
13614: =item $colors: array ref holding the colors to be used for the data sets when
13615: they are plotted. If undefined, default values will be used.
13616:
13617: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13618:
13619: =item @Values: An array of array references. Each array reference holds data
13620: to be plotted in a stacked bar chart.
13621:
13622: =item If the final element of @Values is a hash reference the key/value
13623: pairs will be added to the graph definition.
13624:
13625: =back
13626:
13627: Returns:
13628:
13629: An <img> tag which references graph.png and the appropriate identifying
13630: information for the plot.
13631:
13632: =cut
13633:
13634: ############################################################
13635: ############################################################
13636: sub DrawBarGraph {
13637: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13638: #
13639: if (! defined($colors)) {
13640: $colors = ['#33ff00',
13641: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13642: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13643: ];
13644: }
13645: my $extra_settings = {};
13646: if (ref($Values[-1]) eq 'HASH') {
13647: $extra_settings = pop(@Values);
13648: }
13649: #
13650: my $identifier = &get_cgi_id();
13651: my $id = 'cgi.'.$identifier;
13652: if (! @Values || ref($Values[0]) ne 'ARRAY') {
13653: return '';
13654: }
13655: #
13656: my @Labels;
13657: if (defined($labels)) {
13658: @Labels = @$labels;
13659: } else {
13660: for (my $i=0;$i<@{$Values[0]};$i++) {
13661: push(@Labels,$i+1);
13662: }
13663: }
13664: #
13665: my $NumBars = scalar(@{$Values[0]});
13666: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13667: my %ValuesHash;
13668: my $NumSets=1;
13669: foreach my $array (@Values) {
13670: next if (! ref($array));
13671: $ValuesHash{$id.'.data.'.$NumSets++} =
13672: join(',',@$array);
13673: }
13674: #
13675: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13676: if ($NumBars < 3) {
13677: $width = 120+$NumBars*32;
13678: $xskip = 1;
13679: $bar_width = 30;
13680: } elsif ($NumBars < 5) {
13681: $width = 120+$NumBars*20;
13682: $xskip = 1;
13683: $bar_width = 20;
13684: } elsif ($NumBars < 10) {
13685: $width = 120+$NumBars*15;
13686: $xskip = 1;
13687: $bar_width = 15;
13688: } elsif ($NumBars <= 25) {
13689: $width = 120+$NumBars*11;
13690: $xskip = 5;
13691: $bar_width = 8;
13692: } elsif ($NumBars <= 50) {
13693: $width = 120+$NumBars*8;
13694: $xskip = 5;
13695: $bar_width = 4;
13696: } else {
13697: $width = 120+$NumBars*8;
13698: $xskip = 5;
13699: $bar_width = 4;
13700: }
13701: #
13702: $Max = 1 if ($Max < 1);
13703: if ( int($Max) < $Max ) {
13704: $Max++;
13705: $Max = int($Max);
13706: }
13707: $Title = '' if (! defined($Title));
13708: $xlabel = '' if (! defined($xlabel));
13709: $ylabel = '' if (! defined($ylabel));
13710: $ValuesHash{$id.'.title'} = &escape($Title);
13711: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
13712: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
13713: $ValuesHash{$id.'.y_max_value'} = $Max;
13714: $ValuesHash{$id.'.NumBars'} = $NumBars;
13715: $ValuesHash{$id.'.NumSets'} = $NumSets;
13716: $ValuesHash{$id.'.PlotType'} = 'bar';
13717: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13718: $ValuesHash{$id.'.height'} = $height;
13719: $ValuesHash{$id.'.width'} = $width;
13720: $ValuesHash{$id.'.xskip'} = $xskip;
13721: $ValuesHash{$id.'.bar_width'} = $bar_width;
13722: $ValuesHash{$id.'.labels'} = join(',',@Labels);
13723: #
13724: # Deal with other parameters
13725: while (my ($key,$value) = each(%$extra_settings)) {
13726: $ValuesHash{$id.'.'.$key} = $value;
13727: }
13728: #
13729: &Apache::lonnet::appenv(\%ValuesHash);
13730: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13731: }
13732:
13733: ############################################################
13734: ############################################################
13735:
13736: =pod
13737:
13738: =item * &DrawXYGraph()
13739:
13740: Facilitates the plotting of data in an XY graph.
13741: Puts plot definition data into the users environment in order for
13742: graph.png to plot it. Returns an <img> tag for the plot.
13743:
13744: Inputs:
13745:
13746: =over 4
13747:
13748: =item $Title: string, the title of the plot
13749:
13750: =item $xlabel: string, text describing the X-axis of the plot
13751:
13752: =item $ylabel: string, text describing the Y-axis of the plot
13753:
13754: =item $Max: scalar, the maximum Y value to use in the plot
13755: If $Max is < any data point, the graph will not be rendered.
13756:
13757: =item $colors: Array ref containing the hex color codes for the data to be
13758: plotted in. If undefined, default values will be used.
13759:
13760: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13761:
13762: =item $Ydata: Array ref containing Array refs.
13763: Each of the contained arrays will be plotted as a separate curve.
13764:
13765: =item %Values: hash indicating or overriding any default values which are
13766: passed to graph.png.
13767: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13768:
13769: =back
13770:
13771: Returns:
13772:
13773: An <img> tag which references graph.png and the appropriate identifying
13774: information for the plot.
13775:
13776: =cut
13777:
13778: ############################################################
13779: ############################################################
13780: sub DrawXYGraph {
13781: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13782: #
13783: # Create the identifier for the graph
13784: my $identifier = &get_cgi_id();
13785: my $id = 'cgi.'.$identifier;
13786: #
13787: $Title = '' if (! defined($Title));
13788: $xlabel = '' if (! defined($xlabel));
13789: $ylabel = '' if (! defined($ylabel));
13790: my %ValuesHash =
13791: (
13792: $id.'.title' => &escape($Title),
13793: $id.'.xlabel' => &escape($xlabel),
13794: $id.'.ylabel' => &escape($ylabel),
13795: $id.'.y_max_value'=> $Max,
13796: $id.'.labels' => join(',',@$Xlabels),
13797: $id.'.PlotType' => 'XY',
13798: );
13799: #
13800: if (defined($colors) && ref($colors) eq 'ARRAY') {
13801: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13802: }
13803: #
13804: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13805: return '';
13806: }
13807: my $NumSets=1;
13808: foreach my $array (@{$Ydata}){
13809: next if (! ref($array));
13810: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13811: }
13812: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13813: #
13814: # Deal with other parameters
13815: while (my ($key,$value) = each(%Values)) {
13816: $ValuesHash{$id.'.'.$key} = $value;
13817: }
13818: #
13819: &Apache::lonnet::appenv(\%ValuesHash);
13820: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13821: }
13822:
13823: ############################################################
13824: ############################################################
13825:
13826: =pod
13827:
13828: =item * &DrawXYYGraph()
13829:
13830: Facilitates the plotting of data in an XY graph with two Y axes.
13831: Puts plot definition data into the users environment in order for
13832: graph.png to plot it. Returns an <img> tag for the plot.
13833:
13834: Inputs:
13835:
13836: =over 4
13837:
13838: =item $Title: string, the title of the plot
13839:
13840: =item $xlabel: string, text describing the X-axis of the plot
13841:
13842: =item $ylabel: string, text describing the Y-axis of the plot
13843:
13844: =item $colors: Array ref containing the hex color codes for the data to be
13845: plotted in. If undefined, default values will be used.
13846:
13847: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13848:
13849: =item $Ydata1: The first data set
13850:
13851: =item $Min1: The minimum value of the left Y-axis
13852:
13853: =item $Max1: The maximum value of the left Y-axis
13854:
13855: =item $Ydata2: The second data set
13856:
13857: =item $Min2: The minimum value of the right Y-axis
13858:
13859: =item $Max2: The maximum value of the left Y-axis
13860:
13861: =item %Values: hash indicating or overriding any default values which are
13862: passed to graph.png.
13863: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13864:
13865: =back
13866:
13867: Returns:
13868:
13869: An <img> tag which references graph.png and the appropriate identifying
13870: information for the plot.
13871:
13872: =cut
13873:
13874: ############################################################
13875: ############################################################
13876: sub DrawXYYGraph {
13877: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13878: $Ydata2,$Min2,$Max2,%Values)=@_;
13879: #
13880: # Create the identifier for the graph
13881: my $identifier = &get_cgi_id();
13882: my $id = 'cgi.'.$identifier;
13883: #
13884: $Title = '' if (! defined($Title));
13885: $xlabel = '' if (! defined($xlabel));
13886: $ylabel = '' if (! defined($ylabel));
13887: my %ValuesHash =
13888: (
13889: $id.'.title' => &escape($Title),
13890: $id.'.xlabel' => &escape($xlabel),
13891: $id.'.ylabel' => &escape($ylabel),
13892: $id.'.labels' => join(',',@$Xlabels),
13893: $id.'.PlotType' => 'XY',
13894: $id.'.NumSets' => 2,
13895: $id.'.two_axes' => 1,
13896: $id.'.y1_max_value' => $Max1,
13897: $id.'.y1_min_value' => $Min1,
13898: $id.'.y2_max_value' => $Max2,
13899: $id.'.y2_min_value' => $Min2,
13900: );
13901: #
13902: if (defined($colors) && ref($colors) eq 'ARRAY') {
13903: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13904: }
13905: #
13906: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13907: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13908: return '';
13909: }
13910: my $NumSets=1;
13911: foreach my $array ($Ydata1,$Ydata2){
13912: next if (! ref($array));
13913: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13914: }
13915: #
13916: # Deal with other parameters
13917: while (my ($key,$value) = each(%Values)) {
13918: $ValuesHash{$id.'.'.$key} = $value;
13919: }
13920: #
13921: &Apache::lonnet::appenv(\%ValuesHash);
13922: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13923: }
13924:
13925: ############################################################
13926: ############################################################
13927:
13928: =pod
13929:
13930: =back
13931:
13932: =head1 Statistics helper routines?
13933:
13934: Bad place for them but what the hell.
13935:
13936: =over 4
13937:
13938: =item * &chartlink()
13939:
13940: Returns a link to the chart for a specific student.
13941:
13942: Inputs:
13943:
13944: =over 4
13945:
13946: =item $linktext: The text of the link
13947:
13948: =item $sname: The students username
13949:
13950: =item $sdomain: The students domain
13951:
13952: =back
13953:
13954: =back
13955:
13956: =cut
13957:
13958: ############################################################
13959: ############################################################
13960: sub chartlink {
13961: my ($linktext, $sname, $sdomain) = @_;
13962: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13963: '&SelectedStudent='.&escape($sname.':'.$sdomain).
13964: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
13965: '">'.$linktext.'</a>';
13966: }
13967:
13968: #######################################################
13969: #######################################################
13970:
13971: =pod
13972:
13973: =head1 Course Environment Routines
13974:
13975: =over 4
13976:
13977: =item * &restore_course_settings()
13978:
13979: =item * &store_course_settings()
13980:
13981: Restores/Store indicated form parameters from the course environment.
13982: Will not overwrite existing values of the form parameters.
13983:
13984: Inputs:
13985: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13986:
13987: a hash ref describing the data to be stored. For example:
13988:
13989: %Save_Parameters = ('Status' => 'scalar',
13990: 'chartoutputmode' => 'scalar',
13991: 'chartoutputdata' => 'scalar',
13992: 'Section' => 'array',
13993: 'Group' => 'array',
13994: 'StudentData' => 'array',
13995: 'Maps' => 'array');
13996:
13997: Returns: both routines return nothing
13998:
13999: =back
14000:
14001: =cut
14002:
14003: #######################################################
14004: #######################################################
14005: sub store_course_settings {
14006: return &store_settings($env{'request.course.id'},@_);
14007: }
14008:
14009: sub store_settings {
14010: # save to the environment
14011: # appenv the same items, just to be safe
14012: my $udom = $env{'user.domain'};
14013: my $uname = $env{'user.name'};
14014: my ($context,$prefix,$Settings) = @_;
14015: my %SaveHash;
14016: my %AppHash;
14017: while (my ($setting,$type) = each(%$Settings)) {
14018: my $basename = join('.','internal',$context,$prefix,$setting);
14019: my $envname = 'environment.'.$basename;
14020: if (exists($env{'form.'.$setting})) {
14021: # Save this value away
14022: if ($type eq 'scalar' &&
14023: (! exists($env{$envname}) ||
14024: $env{$envname} ne $env{'form.'.$setting})) {
14025: $SaveHash{$basename} = $env{'form.'.$setting};
14026: $AppHash{$envname} = $env{'form.'.$setting};
14027: } elsif ($type eq 'array') {
14028: my $stored_form;
14029: if (ref($env{'form.'.$setting})) {
14030: $stored_form = join(',',
14031: map {
14032: &escape($_);
14033: } sort(@{$env{'form.'.$setting}}));
14034: } else {
14035: $stored_form =
14036: &escape($env{'form.'.$setting});
14037: }
14038: # Determine if the array contents are the same.
14039: if ($stored_form ne $env{$envname}) {
14040: $SaveHash{$basename} = $stored_form;
14041: $AppHash{$envname} = $stored_form;
14042: }
14043: }
14044: }
14045: }
14046: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14047: $udom,$uname);
14048: if ($put_result !~ /^(ok|delayed)/) {
14049: &Apache::lonnet::logthis('unable to save form parameters, '.
14050: 'got error:'.$put_result);
14051: }
14052: # Make sure these settings stick around in this session, too
14053: &Apache::lonnet::appenv(\%AppHash);
14054: return;
14055: }
14056:
14057: sub restore_course_settings {
14058: return &restore_settings($env{'request.course.id'},@_);
14059: }
14060:
14061: sub restore_settings {
14062: my ($context,$prefix,$Settings) = @_;
14063: while (my ($setting,$type) = each(%$Settings)) {
14064: next if (exists($env{'form.'.$setting}));
14065: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14066: '.'.$setting;
14067: if (exists($env{$envname})) {
14068: if ($type eq 'scalar') {
14069: $env{'form.'.$setting} = $env{$envname};
14070: } elsif ($type eq 'array') {
14071: $env{'form.'.$setting} = [
14072: map {
14073: &unescape($_);
14074: } split(',',$env{$envname})
14075: ];
14076: }
14077: }
14078: }
14079: }
14080:
14081: #######################################################
14082: #######################################################
14083:
14084: =pod
14085:
14086: =head1 Domain E-mail Routines
14087:
14088: =over 4
14089:
14090: =item * &build_recipient_list()
14091:
14092: Build recipient lists for following types of e-mail:
14093: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14094: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14095: module change checking, student/employee ID conflict checks, as
14096: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14097: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14098:
14099: Inputs:
14100: defmail (scalar - email address of default recipient),
14101: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14102: requestsmail, updatesmail, or idconflictsmail).
14103:
14104: defdom (domain for which to retrieve configuration settings),
14105:
14106: origmail (scalar - email address of recipient from loncapa.conf,
14107: i.e., predates configuration by DC via domainprefs.pm
14108:
14109: Returns: comma separated list of addresses to which to send e-mail.
14110:
14111: =back
14112:
14113: =cut
14114:
14115: ############################################################
14116: ############################################################
14117: sub build_recipient_list {
14118: my ($defmail,$mailing,$defdom,$origmail) = @_;
14119: my @recipients;
14120: my ($otheremails,$lastresort,$allbcc,$addtext);
14121: my %domconfig =
14122: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14123: if (ref($domconfig{'contacts'}) eq 'HASH') {
14124: if (exists($domconfig{'contacts'}{$mailing})) {
14125: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14126: my @contacts = ('adminemail','supportemail');
14127: foreach my $item (@contacts) {
14128: if ($domconfig{'contacts'}{$mailing}{$item}) {
14129: my $addr = $domconfig{'contacts'}{$item};
14130: if (!grep(/^\Q$addr\E$/,@recipients)) {
14131: push(@recipients,$addr);
14132: }
14133: }
14134: }
14135: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14136: if ($mailing eq 'helpdeskmail') {
14137: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14138: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14139: my @ok_bccs;
14140: foreach my $bcc (@bccs) {
14141: $bcc =~ s/^\s+//g;
14142: $bcc =~ s/\s+$//g;
14143: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14144: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14145: push(@ok_bccs,$bcc);
14146: }
14147: }
14148: }
14149: if (@ok_bccs > 0) {
14150: $allbcc = join(', ',@ok_bccs);
14151: }
14152: }
14153: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14154: }
14155: }
14156: } elsif ($origmail ne '') {
14157: $lastresort = $origmail;
14158: }
14159: } elsif ($origmail ne '') {
14160: $lastresort = $origmail;
14161: }
14162:
14163: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14164: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14165: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14166: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14167: my %what = (
14168: perlvar => 1,
14169: );
14170: my $primary = &Apache::lonnet::domain($defdom,'primary');
14171: if ($primary) {
14172: my $gotaddr;
14173: my ($result,$returnhash) =
14174: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14175: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14176: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14177: $lastresort = $returnhash->{'lonSupportEMail'};
14178: $gotaddr = 1;
14179: }
14180: }
14181: unless ($gotaddr) {
14182: my $uintdom = &Apache::lonnet::internet_dom($primary);
14183: my $intdom = &Apache::lonnet::internet_dom($lonhost);
14184: unless ($uintdom eq $intdom) {
14185: my %domconfig =
14186: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14187: if (ref($domconfig{'contacts'}) eq 'HASH') {
14188: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14189: my @contacts = ('adminemail','supportemail');
14190: foreach my $item (@contacts) {
14191: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14192: my $addr = $domconfig{'contacts'}{$item};
14193: if (!grep(/^\Q$addr\E$/,@recipients)) {
14194: push(@recipients,$addr);
14195: }
14196: }
14197: }
14198: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14199: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14200: }
14201: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14202: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14203: my @ok_bccs;
14204: foreach my $bcc (@bccs) {
14205: $bcc =~ s/^\s+//g;
14206: $bcc =~ s/\s+$//g;
14207: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14208: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14209: push(@ok_bccs,$bcc);
14210: }
14211: }
14212: }
14213: if (@ok_bccs > 0) {
14214: $allbcc = join(', ',@ok_bccs);
14215: }
14216: }
14217: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14218: }
14219: }
14220: }
14221: }
14222: }
14223: }
14224: }
14225: if (defined($defmail)) {
14226: if ($defmail ne '') {
14227: push(@recipients,$defmail);
14228: }
14229: }
14230: if ($otheremails) {
14231: my @others;
14232: if ($otheremails =~ /,/) {
14233: @others = split(/,/,$otheremails);
14234: } else {
14235: push(@others,$otheremails);
14236: }
14237: foreach my $addr (@others) {
14238: if (!grep(/^\Q$addr\E$/,@recipients)) {
14239: push(@recipients,$addr);
14240: }
14241: }
14242: }
14243: if ($mailing eq 'helpdeskmail') {
14244: if ((!@recipients) && ($lastresort ne '')) {
14245: push(@recipients,$lastresort);
14246: }
14247: } elsif ($lastresort ne '') {
14248: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14249: push(@recipients,$lastresort);
14250: }
14251: }
14252: my $recipientlist = join(',',@recipients);
14253: if (wantarray) {
14254: return ($recipientlist,$allbcc,$addtext);
14255: } else {
14256: return $recipientlist;
14257: }
14258: }
14259:
14260: ############################################################
14261: ############################################################
14262:
14263: =pod
14264:
14265: =head1 Course Catalog Routines
14266:
14267: =over 4
14268:
14269: =item * &gather_categories()
14270:
14271: Converts category definitions - keys of categories hash stored in
14272: coursecategories in configuration.db on the primary library server in a
14273: domain - to an array. Also generates javascript and idx hash used to
14274: generate Domain Coordinator interface for editing Course Categories.
14275:
14276: Inputs:
14277:
14278: categories (reference to hash of category definitions).
14279:
14280: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14281: categories and subcategories).
14282:
14283: idx (reference to hash of counters used in Domain Coordinator interface for
14284: editing Course Categories).
14285:
14286: jsarray (reference to array of categories used to create Javascript arrays for
14287: Domain Coordinator interface for editing Course Categories).
14288:
14289: Returns: nothing
14290:
14291: Side effects: populates cats, idx and jsarray.
14292:
14293: =cut
14294:
14295: sub gather_categories {
14296: my ($categories,$cats,$idx,$jsarray) = @_;
14297: my %counters;
14298: my $num = 0;
14299: foreach my $item (keys(%{$categories})) {
14300: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14301: if ($container eq '' && $depth == 0) {
14302: $cats->[$depth][$categories->{$item}] = $cat;
14303: } else {
14304: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14305: }
14306: my ($escitem,$tail) = split(/:/,$item,2);
14307: if ($counters{$tail} eq '') {
14308: $counters{$tail} = $num;
14309: $num ++;
14310: }
14311: if (ref($idx) eq 'HASH') {
14312: $idx->{$item} = $counters{$tail};
14313: }
14314: if (ref($jsarray) eq 'ARRAY') {
14315: push(@{$jsarray->[$counters{$tail}]},$item);
14316: }
14317: }
14318: return;
14319: }
14320:
14321: =pod
14322:
14323: =item * &extract_categories()
14324:
14325: Used to generate breadcrumb trails for course categories.
14326:
14327: Inputs:
14328:
14329: categories (reference to hash of category definitions).
14330:
14331: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14332: categories and subcategories).
14333:
14334: trails (reference to array of breacrumb trails for each category).
14335:
14336: allitems (reference to hash - key is category key
14337: (format: escaped(name):escaped(parent category):depth in hierarchy).
14338:
14339: idx (reference to hash of counters used in Domain Coordinator interface for
14340: editing Course Categories).
14341:
14342: jsarray (reference to array of categories used to create Javascript arrays for
14343: Domain Coordinator interface for editing Course Categories).
14344:
14345: subcats (reference to hash of arrays containing all subcategories within each
14346: category, -recursive)
14347:
14348: maxd (reference to hash used to hold max depth for all top-level categories).
14349:
14350: Returns: nothing
14351:
14352: Side effects: populates trails and allitems hash references.
14353:
14354: =cut
14355:
14356: sub extract_categories {
14357: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14358: if (ref($categories) eq 'HASH') {
14359: &gather_categories($categories,$cats,$idx,$jsarray);
14360: if (ref($cats->[0]) eq 'ARRAY') {
14361: for (my $i=0; $i<@{$cats->[0]}; $i++) {
14362: my $name = $cats->[0][$i];
14363: my $item = &escape($name).'::0';
14364: my $trailstr;
14365: if ($name eq 'instcode') {
14366: $trailstr = &mt('Official courses (with institutional codes)');
14367: } elsif ($name eq 'communities') {
14368: $trailstr = &mt('Communities');
14369: } else {
14370: $trailstr = $name;
14371: }
14372: if ($allitems->{$item} eq '') {
14373: push(@{$trails},$trailstr);
14374: $allitems->{$item} = scalar(@{$trails})-1;
14375: }
14376: my @parents = ($name);
14377: if (ref($cats->[1]{$name}) eq 'ARRAY') {
14378: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14379: my $category = $cats->[1]{$name}[$j];
14380: if (ref($subcats) eq 'HASH') {
14381: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14382: }
14383: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14384: }
14385: } else {
14386: if (ref($subcats) eq 'HASH') {
14387: $subcats->{$item} = [];
14388: }
14389: if (ref($maxd) eq 'HASH') {
14390: $maxd->{$name} = 1;
14391: }
14392: }
14393: }
14394: }
14395: }
14396: return;
14397: }
14398:
14399: =pod
14400:
14401: =item * &recurse_categories()
14402:
14403: Recursively used to generate breadcrumb trails for course categories.
14404:
14405: Inputs:
14406:
14407: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14408: categories and subcategories).
14409:
14410: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14411:
14412: category (current course category, for which breadcrumb trail is being generated).
14413:
14414: trails (reference to array of breadcrumb trails for each category).
14415:
14416: allitems (reference to hash - key is category key
14417: (format: escaped(name):escaped(parent category):depth in hierarchy).
14418:
14419: parents (array containing containers directories for current category,
14420: back to top level).
14421:
14422: Returns: nothing
14423:
14424: Side effects: populates trails and allitems hash references
14425:
14426: =cut
14427:
14428: sub recurse_categories {
14429: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14430: my $shallower = $depth - 1;
14431: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14432: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14433: my $name = $cats->[$depth]{$category}[$k];
14434: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14435: my $trailstr = join(' -> ',(@{$parents},$category));
14436: if ($allitems->{$item} eq '') {
14437: push(@{$trails},$trailstr);
14438: $allitems->{$item} = scalar(@{$trails})-1;
14439: }
14440: my $deeper = $depth+1;
14441: push(@{$parents},$category);
14442: if (ref($subcats) eq 'HASH') {
14443: my $subcat = &escape($name).':'.$category.':'.$depth;
14444: for (my $j=@{$parents}; $j>=0; $j--) {
14445: my $higher;
14446: if ($j > 0) {
14447: $higher = &escape($parents->[$j]).':'.
14448: &escape($parents->[$j-1]).':'.$j;
14449: } else {
14450: $higher = &escape($parents->[$j]).'::'.$j;
14451: }
14452: push(@{$subcats->{$higher}},$subcat);
14453: }
14454: }
14455: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14456: $subcats,$maxd);
14457: pop(@{$parents});
14458: }
14459: } else {
14460: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14461: my $trailstr = join(' » ',(@{$parents},$category));
14462: if ($allitems->{$item} eq '') {
14463: push(@{$trails},$trailstr);
14464: $allitems->{$item} = scalar(@{$trails})-1;
14465: }
14466: if (ref($maxd) eq 'HASH') {
14467: if ($depth > $maxd->{$parents->[0]}) {
14468: $maxd->{$parents->[0]} = $depth;
14469: }
14470: }
14471: }
14472: return;
14473: }
14474:
14475: =pod
14476:
14477: =item * &assign_categories_table()
14478:
14479: Create a datatable for display of hierarchical categories in a domain,
14480: with checkboxes to allow a course to be categorized.
14481:
14482: Inputs:
14483:
14484: cathash - reference to hash of categories defined for the domain (from
14485: configuration.db)
14486:
14487: currcat - scalar with an & separated list of categories assigned to a course.
14488:
14489: type - scalar contains course type (Course or Community).
14490:
14491: disabled - scalar (optional) contains disabled="disabled" if input elements are
14492: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14493:
14494: Returns: $output (markup to be displayed)
14495:
14496: =cut
14497:
14498: sub assign_categories_table {
14499: my ($cathash,$currcat,$type,$disabled) = @_;
14500: my $output;
14501: if (ref($cathash) eq 'HASH') {
14502: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14503: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14504: $maxdepth = scalar(@cats);
14505: if (@cats > 0) {
14506: my $itemcount = 0;
14507: if (ref($cats[0]) eq 'ARRAY') {
14508: my @currcategories;
14509: if ($currcat ne '') {
14510: @currcategories = split('&',$currcat);
14511: }
14512: my $table;
14513: for (my $i=0; $i<@{$cats[0]}; $i++) {
14514: my $parent = $cats[0][$i];
14515: next if ($parent eq 'instcode');
14516: if ($type eq 'Community') {
14517: next unless ($parent eq 'communities');
14518: } else {
14519: next if ($parent eq 'communities');
14520: }
14521: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14522: my $item = &escape($parent).'::0';
14523: my $checked = '';
14524: if (@currcategories > 0) {
14525: if (grep(/^\Q$item\E$/,@currcategories)) {
14526: $checked = ' checked="checked"';
14527: }
14528: }
14529: my $parent_title = $parent;
14530: if ($parent eq 'communities') {
14531: $parent_title = &mt('Communities');
14532: }
14533: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14534: '<input type="checkbox" name="usecategory" value="'.
14535: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14536: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14537: my $depth = 1;
14538: push(@path,$parent);
14539: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14540: pop(@path);
14541: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14542: $itemcount ++;
14543: }
14544: if ($itemcount) {
14545: $output = &Apache::loncommon::start_data_table().
14546: $table.
14547: &Apache::loncommon::end_data_table();
14548: }
14549: }
14550: }
14551: }
14552: return $output;
14553: }
14554:
14555: =pod
14556:
14557: =item * &assign_category_rows()
14558:
14559: Create a datatable row for display of nested categories in a domain,
14560: with checkboxes to allow a course to be categorized,called recursively.
14561:
14562: Inputs:
14563:
14564: itemcount - track row number for alternating colors
14565:
14566: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14567: categories and subcategories.
14568:
14569: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14570:
14571: parent - parent of current category item
14572:
14573: path - Array containing all categories back up through the hierarchy from the
14574: current category to the top level.
14575:
14576: currcategories - reference to array of current categories assigned to the course
14577:
14578: disabled - scalar (optional) contains disabled="disabled" if input elements are
14579: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14580:
14581: Returns: $output (markup to be displayed).
14582:
14583: =cut
14584:
14585: sub assign_category_rows {
14586: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14587: my ($text,$name,$item,$chgstr);
14588: if (ref($cats) eq 'ARRAY') {
14589: my $maxdepth = scalar(@{$cats});
14590: if (ref($cats->[$depth]) eq 'HASH') {
14591: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14592: my $numchildren = @{$cats->[$depth]{$parent}};
14593: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14594: $text .= '<td><table class="LC_data_table">';
14595: for (my $j=0; $j<$numchildren; $j++) {
14596: $name = $cats->[$depth]{$parent}[$j];
14597: $item = &escape($name).':'.&escape($parent).':'.$depth;
14598: my $deeper = $depth+1;
14599: my $checked = '';
14600: if (ref($currcategories) eq 'ARRAY') {
14601: if (@{$currcategories} > 0) {
14602: if (grep(/^\Q$item\E$/,@{$currcategories})) {
14603: $checked = ' checked="checked"';
14604: }
14605: }
14606: }
14607: $text .= '<tr><td><span class="LC_nobreak"><label>'.
14608: '<input type="checkbox" name="usecategory" value="'.
14609: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14610: '<input type="hidden" name="catname" value="'.$name.'" />'.
14611: '</td><td>';
14612: if (ref($path) eq 'ARRAY') {
14613: push(@{$path},$name);
14614: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14615: pop(@{$path});
14616: }
14617: $text .= '</td></tr>';
14618: }
14619: $text .= '</table></td>';
14620: }
14621: }
14622: }
14623: return $text;
14624: }
14625:
14626: =pod
14627:
14628: =back
14629:
14630: =cut
14631:
14632: ############################################################
14633: ############################################################
14634:
14635:
14636: sub commit_customrole {
14637: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14638: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14639: ($start?', '.&mt('starting').' '.localtime($start):'').
14640: ($end?', ending '.localtime($end):'').': <b>'.
14641: &Apache::lonnet::assigncustomrole(
14642: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14643: '</b><br />';
14644: return $output;
14645: }
14646:
14647: sub commit_standardrole {
14648: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14649: my ($output,$logmsg,$linefeed);
14650: if ($context eq 'auto') {
14651: $linefeed = "\n";
14652: } else {
14653: $linefeed = "<br />\n";
14654: }
14655: if ($three eq 'st') {
14656: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14657: $one,$two,$sec,$context,$credits);
14658: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
14659: ($result eq 'unknown_course') || ($result eq 'refused')) {
14660: $output = $logmsg.' '.&mt('Error: ').$result."\n";
14661: } else {
14662: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14663: ($start?', '.&mt('starting').' '.localtime($start):'').
14664: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14665: if ($context eq 'auto') {
14666: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14667: } else {
14668: $output .= '<b>'.$result.'</b>'.$linefeed.
14669: &mt('Add to classlist').': <b>ok</b>';
14670: }
14671: $output .= $linefeed;
14672: }
14673: } else {
14674: $output = &mt('Assigning').' '.$three.' in '.$url.
14675: ($start?', '.&mt('starting').' '.localtime($start):'').
14676: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14677: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14678: if ($context eq 'auto') {
14679: $output .= $result.$linefeed;
14680: } else {
14681: $output .= '<b>'.$result.'</b>'.$linefeed;
14682: }
14683: }
14684: return $output;
14685: }
14686:
14687: sub commit_studentrole {
14688: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14689: $credits) = @_;
14690: my ($result,$linefeed,$oldsecurl,$newsecurl);
14691: if ($context eq 'auto') {
14692: $linefeed = "\n";
14693: } else {
14694: $linefeed = '<br />'."\n";
14695: }
14696: if (defined($one) && defined($two)) {
14697: my $cid=$one.'_'.$two;
14698: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14699: my $secchange = 0;
14700: my $expire_role_result;
14701: my $modify_section_result;
14702: if ($oldsec ne '-1') {
14703: if ($oldsec ne $sec) {
14704: $secchange = 1;
14705: my $now = time;
14706: my $uurl='/'.$cid;
14707: $uurl=~s/\_/\//g;
14708: if ($oldsec) {
14709: $uurl.='/'.$oldsec;
14710: }
14711: $oldsecurl = $uurl;
14712: $expire_role_result =
14713: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14714: if ($env{'request.course.sec'} ne '') {
14715: if ($expire_role_result eq 'refused') {
14716: my @roles = ('st');
14717: my @statuses = ('previous');
14718: my @roledoms = ($one);
14719: my $withsec = 1;
14720: my %roleshash =
14721: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14722: \@statuses,\@roles,\@roledoms,$withsec);
14723: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14724: my ($oldstart,$oldend) =
14725: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14726: if ($oldend > 0 && $oldend <= $now) {
14727: $expire_role_result = 'ok';
14728: }
14729: }
14730: }
14731: }
14732: $result = $expire_role_result;
14733: }
14734: }
14735: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14736: $modify_section_result =
14737: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14738: undef,undef,undef,$sec,
14739: $end,$start,'','',$cid,
14740: '',$context,$credits);
14741: if ($modify_section_result =~ /^ok/) {
14742: if ($secchange == 1) {
14743: if ($sec eq '') {
14744: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14745: } else {
14746: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14747: }
14748: } elsif ($oldsec eq '-1') {
14749: if ($sec eq '') {
14750: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14751: } else {
14752: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14753: }
14754: } else {
14755: if ($sec eq '') {
14756: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14757: } else {
14758: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14759: }
14760: }
14761: } else {
14762: if ($secchange) {
14763: $$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;
14764: } else {
14765: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14766: }
14767: }
14768: $result = $modify_section_result;
14769: } elsif ($secchange == 1) {
14770: if ($oldsec eq '') {
14771: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14772: } else {
14773: $$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;
14774: }
14775: if ($expire_role_result eq 'refused') {
14776: my $newsecurl = '/'.$cid;
14777: $newsecurl =~ s/\_/\//g;
14778: if ($sec ne '') {
14779: $newsecurl.='/'.$sec;
14780: }
14781: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14782: if ($sec eq '') {
14783: $$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;
14784: } else {
14785: $$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;
14786: }
14787: }
14788: }
14789: }
14790: } else {
14791: $$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;
14792: $result = "error: incomplete course id\n";
14793: }
14794: return $result;
14795: }
14796:
14797: sub show_role_extent {
14798: my ($scope,$context,$role) = @_;
14799: $scope =~ s{^/}{};
14800: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14801: push(@courseroles,'co');
14802: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14803: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14804: $scope =~ s{/}{_};
14805: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14806: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14807: my ($audom,$auname) = split(/\//,$scope);
14808: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14809: &Apache::loncommon::plainname($auname,$audom).'</span>');
14810: } else {
14811: $scope =~ s{/$}{};
14812: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14813: &Apache::lonnet::domain($scope,'description').'</span>');
14814: }
14815: }
14816:
14817: ############################################################
14818: ############################################################
14819:
14820: sub check_clone {
14821: my ($args,$linefeed) = @_;
14822: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14823: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14824: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14825: my $clonemsg;
14826: my $can_clone = 0;
14827: my $lctype = lc($args->{'crstype'});
14828: if ($lctype ne 'community') {
14829: $lctype = 'course';
14830: }
14831: if ($clonehome eq 'no_host') {
14832: if ($args->{'crstype'} eq 'Community') {
14833: $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'});
14834: } else {
14835: $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'});
14836: }
14837: } else {
14838: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14839: if ($args->{'crstype'} eq 'Community') {
14840: if ($clonedesc{'type'} ne 'Community') {
14841: $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'});
14842: return ($can_clone, $clonemsg, $cloneid, $clonehome);
14843: }
14844: }
14845: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14846: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14847: $can_clone = 1;
14848: } else {
14849: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14850: $args->{'clonedomain'},$args->{'clonecourse'});
14851: if ($clonehash{'cloners'} eq '') {
14852: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14853: if ($domdefs{'canclone'}) {
14854: unless ($domdefs{'canclone'} eq 'none') {
14855: if ($domdefs{'canclone'} eq 'domain') {
14856: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14857: $can_clone = 1;
14858: }
14859: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14860: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
14861: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14862: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14863: $can_clone = 1;
14864: }
14865: }
14866: }
14867: }
14868: } else {
14869: my @cloners = split(/,/,$clonehash{'cloners'});
14870: if (grep(/^\*$/,@cloners)) {
14871: $can_clone = 1;
14872: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14873: $can_clone = 1;
14874: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14875: $can_clone = 1;
14876: }
14877: unless ($can_clone) {
14878: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14879: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
14880: my (%gotdomdefaults,%gotcodedefaults);
14881: foreach my $cloner (@cloners) {
14882: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14883: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14884: my (%codedefaults,@code_order);
14885: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14886: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14887: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14888: }
14889: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14890: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14891: }
14892: } else {
14893: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14894: \%codedefaults,
14895: \@code_order);
14896: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14897: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14898: }
14899: if (@code_order > 0) {
14900: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14901: $cloner,$clonehash{'internal.coursecode'},
14902: $args->{'crscode'})) {
14903: $can_clone = 1;
14904: last;
14905: }
14906: }
14907: }
14908: }
14909: }
14910: }
14911: }
14912: unless ($can_clone) {
14913: my $ccrole = 'cc';
14914: if ($args->{'crstype'} eq 'Community') {
14915: $ccrole = 'co';
14916: }
14917: my %roleshash =
14918: &Apache::lonnet::get_my_roles($args->{'ccuname'},
14919: $args->{'ccdomain'},
14920: 'userroles',['active'],[$ccrole],
14921: [$args->{'clonedomain'}]);
14922: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14923: $can_clone = 1;
14924: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14925: $args->{'ccuname'},$args->{'ccdomain'})) {
14926: $can_clone = 1;
14927: }
14928: }
14929: unless ($can_clone) {
14930: if ($args->{'crstype'} eq 'Community') {
14931: $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'});
14932: } else {
14933: $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'});
14934: }
14935: }
14936: }
14937: }
14938: return ($can_clone, $clonemsg, $cloneid, $clonehome);
14939: }
14940:
14941: sub construct_course {
14942: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
14943: $cnum,$category,$coderef) = @_;
14944: my $outcome;
14945: my $linefeed = '<br />'."\n";
14946: if ($context eq 'auto') {
14947: $linefeed = "\n";
14948: }
14949:
14950: #
14951: # Are we cloning?
14952: #
14953: my ($can_clone, $clonemsg, $cloneid, $clonehome);
14954: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14955: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14956: if ($context ne 'auto') {
14957: if ($clonemsg ne '') {
14958: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14959: }
14960: }
14961: $outcome .= $clonemsg.$linefeed;
14962:
14963: if (!$can_clone) {
14964: return (0,$outcome);
14965: }
14966: }
14967:
14968: #
14969: # Open course
14970: #
14971: my $crstype = lc($args->{'crstype'});
14972: my %cenv=();
14973: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14974: $args->{'cdescr'},
14975: $args->{'curl'},
14976: $args->{'course_home'},
14977: $args->{'nonstandard'},
14978: $args->{'crscode'},
14979: $args->{'ccuname'}.':'.
14980: $args->{'ccdomain'},
14981: $args->{'crstype'},
14982: $cnum,$context,$category);
14983:
14984: # Note: The testing routines depend on this being output; see
14985: # Utils::Course. This needs to at least be output as a comment
14986: # if anyone ever decides to not show this, and Utils::Course::new
14987: # will need to be suitably modified.
14988: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14989: if ($$courseid =~ /^error:/) {
14990: return (0,$outcome);
14991: }
14992:
14993: #
14994: # Check if created correctly
14995: #
14996: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14997: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14998: if ($crsuhome eq 'no_host') {
14999: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15000: return (0,$outcome);
15001: }
15002: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15003:
15004: #
15005: # Do the cloning
15006: #
15007: if ($can_clone && $cloneid) {
15008: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15009: if ($context ne 'auto') {
15010: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15011: }
15012: $outcome .= $clonemsg.$linefeed;
15013: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15014: # Copy all files
15015: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15016: # Restore URL
15017: $cenv{'url'}=$oldcenv{'url'};
15018: # Restore title
15019: $cenv{'description'}=$oldcenv{'description'};
15020: # Restore creation date, creator and creation context.
15021: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15022: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15023: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15024: # Mark as cloned
15025: $cenv{'clonedfrom'}=$cloneid;
15026: # Need to clone grading mode
15027: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15028: $cenv{'grading'}=$newenv{'grading'};
15029: # Do not clone these environment entries
15030: &Apache::lonnet::del('environment',
15031: ['default_enrollment_start_date',
15032: 'default_enrollment_end_date',
15033: 'question.email',
15034: 'policy.email',
15035: 'comment.email',
15036: 'pch.users.denied',
15037: 'plc.users.denied',
15038: 'hidefromcat',
15039: 'checkforpriv',
15040: 'categories',
15041: 'internal.uniquecode'],
15042: $$crsudom,$$crsunum);
15043: if ($args->{'textbook'}) {
15044: $cenv{'internal.textbook'} = $args->{'textbook'};
15045: }
15046: }
15047:
15048: #
15049: # Set environment (will override cloned, if existing)
15050: #
15051: my @sections = ();
15052: my @xlists = ();
15053: if ($args->{'crstype'}) {
15054: $cenv{'type'}=$args->{'crstype'};
15055: }
15056: if ($args->{'crsid'}) {
15057: $cenv{'courseid'}=$args->{'crsid'};
15058: }
15059: if ($args->{'crscode'}) {
15060: $cenv{'internal.coursecode'}=$args->{'crscode'};
15061: }
15062: if ($args->{'crsquota'} ne '') {
15063: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15064: } else {
15065: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15066: }
15067: if ($args->{'ccuname'}) {
15068: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15069: ':'.$args->{'ccdomain'};
15070: } else {
15071: $cenv{'internal.courseowner'} = $args->{'curruser'};
15072: }
15073: if ($args->{'defaultcredits'}) {
15074: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15075: }
15076: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15077: if ($args->{'crssections'}) {
15078: $cenv{'internal.sectionnums'} = '';
15079: if ($args->{'crssections'} =~ m/,/) {
15080: @sections = split/,/,$args->{'crssections'};
15081: } else {
15082: $sections[0] = $args->{'crssections'};
15083: }
15084: if (@sections > 0) {
15085: foreach my $item (@sections) {
15086: my ($sec,$gp) = split/:/,$item;
15087: my $class = $args->{'crscode'}.$sec;
15088: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15089: $cenv{'internal.sectionnums'} .= $item.',';
15090: unless ($addcheck eq 'ok') {
15091: push(@badclasses,$class);
15092: }
15093: }
15094: $cenv{'internal.sectionnums'} =~ s/,$//;
15095: }
15096: }
15097: # do not hide course coordinator from staff listing,
15098: # even if privileged
15099: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15100: # add course coordinator's domain to domains to check for privileged users
15101: # if different to course domain
15102: if ($$crsudom ne $args->{'ccdomain'}) {
15103: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15104: }
15105: # add crosslistings
15106: if ($args->{'crsxlist'}) {
15107: $cenv{'internal.crosslistings'}='';
15108: if ($args->{'crsxlist'} =~ m/,/) {
15109: @xlists = split/,/,$args->{'crsxlist'};
15110: } else {
15111: $xlists[0] = $args->{'crsxlist'};
15112: }
15113: if (@xlists > 0) {
15114: foreach my $item (@xlists) {
15115: my ($xl,$gp) = split/:/,$item;
15116: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15117: $cenv{'internal.crosslistings'} .= $item.',';
15118: unless ($addcheck eq 'ok') {
15119: push(@badclasses,$xl);
15120: }
15121: }
15122: $cenv{'internal.crosslistings'} =~ s/,$//;
15123: }
15124: }
15125: if ($args->{'autoadds'}) {
15126: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15127: }
15128: if ($args->{'autodrops'}) {
15129: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15130: }
15131: # check for notification of enrollment changes
15132: my @notified = ();
15133: if ($args->{'notify_owner'}) {
15134: if ($args->{'ccuname'} ne '') {
15135: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15136: }
15137: }
15138: if ($args->{'notify_dc'}) {
15139: if ($uname ne '') {
15140: push(@notified,$uname.':'.$udom);
15141: }
15142: }
15143: if (@notified > 0) {
15144: my $notifylist;
15145: if (@notified > 1) {
15146: $notifylist = join(',',@notified);
15147: } else {
15148: $notifylist = $notified[0];
15149: }
15150: $cenv{'internal.notifylist'} = $notifylist;
15151: }
15152: if (@badclasses > 0) {
15153: my %lt=&Apache::lonlocal::texthash(
15154: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15155: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15156: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15157: );
15158: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15159: &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
15160: if ($context eq 'auto') {
15161: $outcome .= $badclass_msg.$linefeed;
15162: } else {
15163: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15164: }
15165: foreach my $item (@badclasses) {
15166: if ($context eq 'auto') {
15167: $outcome .= " - $item\n";
15168: } else {
15169: $outcome .= "<li>$item</li>\n";
15170: }
15171: }
15172: if ($context eq 'auto') {
15173: $outcome .= $linefeed;
15174: } else {
15175: $outcome .= "</ul><br /><br /></div>\n";
15176: }
15177: }
15178: if ($args->{'no_end_date'}) {
15179: $args->{'endaccess'} = 0;
15180: }
15181: $cenv{'internal.autostart'}=$args->{'enrollstart'};
15182: $cenv{'internal.autoend'}=$args->{'enrollend'};
15183: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15184: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15185: if ($args->{'showphotos'}) {
15186: $cenv{'internal.showphotos'}=$args->{'showphotos'};
15187: }
15188: $cenv{'internal.authtype'} = $args->{'authtype'};
15189: $cenv{'internal.autharg'} = $args->{'autharg'};
15190: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15191: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
15192: 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');
15193: if ($context eq 'auto') {
15194: $outcome .= $krb_msg;
15195: } else {
15196: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15197: }
15198: $outcome .= $linefeed;
15199: }
15200: }
15201: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15202: if ($args->{'setpolicy'}) {
15203: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15204: }
15205: if ($args->{'setcontent'}) {
15206: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15207: }
15208: if ($args->{'setcomment'}) {
15209: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15210: }
15211: }
15212: if ($args->{'reshome'}) {
15213: $cenv{'reshome'}=$args->{'reshome'}.'/';
15214: $cenv{'reshome'}=~s/\/+$/\//;
15215: }
15216: #
15217: # course has keyed access
15218: #
15219: if ($args->{'setkeys'}) {
15220: $cenv{'keyaccess'}='yes';
15221: }
15222: # if specified, key authority is not course, but user
15223: # only active if keyaccess is yes
15224: if ($args->{'keyauth'}) {
15225: my ($user,$domain) = split(':',$args->{'keyauth'});
15226: $user = &LONCAPA::clean_username($user);
15227: $domain = &LONCAPA::clean_username($domain);
15228: if ($user ne '' && $domain ne '') {
15229: $cenv{'keyauth'}=$user.':'.$domain;
15230: }
15231: }
15232:
15233: #
15234: # generate and store uniquecode (available to course requester), if course should have one.
15235: #
15236: if ($args->{'uniquecode'}) {
15237: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15238: if ($code) {
15239: $cenv{'internal.uniquecode'} = $code;
15240: my %crsinfo =
15241: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15242: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15243: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15244: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15245: }
15246: if (ref($coderef)) {
15247: $$coderef = $code;
15248: }
15249: }
15250: }
15251:
15252: if ($args->{'disresdis'}) {
15253: $cenv{'pch.roles.denied'}='st';
15254: }
15255: if ($args->{'disablechat'}) {
15256: $cenv{'plc.roles.denied'}='st';
15257: }
15258:
15259: # Record we've not yet viewed the Course Initialization Helper for this
15260: # course
15261: $cenv{'course.helper.not.run'} = 1;
15262: #
15263: # Use new Randomseed
15264: #
15265: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15266: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15267: #
15268: # The encryption code and receipt prefix for this course
15269: #
15270: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15271: $cenv{'internal.encpref'}=100+int(9*rand(99));
15272: #
15273: # By default, use standard grading
15274: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15275:
15276: $outcome .= $linefeed.&mt('Setting environment').': '.
15277: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15278: #
15279: # Open all assignments
15280: #
15281: if ($args->{'openall'}) {
15282: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15283: my %storecontent = ($storeunder => time,
15284: $storeunder.'.type' => 'date_start');
15285:
15286: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15287: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15288: }
15289: #
15290: # Set first page
15291: #
15292: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15293: || ($cloneid)) {
15294: use LONCAPA::map;
15295: $outcome .= &mt('Setting first resource').': ';
15296:
15297: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15298: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15299:
15300: $outcome .= ($fatal?$errtext:'read ok').' - ';
15301: my $title; my $url;
15302: if ($args->{'firstres'} eq 'syl') {
15303: $title=&mt('Syllabus');
15304: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15305: } else {
15306: $title=&mt('Table of Contents');
15307: $url='/adm/navmaps';
15308: }
15309:
15310: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15311: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15312:
15313: if ($errtext) { $fatal=2; }
15314: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15315: }
15316:
15317: return (1,$outcome);
15318: }
15319:
15320: sub make_unique_code {
15321: my ($cdom,$cnum) = @_;
15322: # get lock on uniquecodes db
15323: my $lockhash = {
15324: $cnum."\0".'uniquecodes' => $env{'user.name'}.
15325: ':'.$env{'user.domain'},
15326: };
15327: my $tries = 0;
15328: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15329: my ($code,$error);
15330:
15331: while (($gotlock ne 'ok') && ($tries<3)) {
15332: $tries ++;
15333: sleep 1;
15334: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15335: }
15336: if ($gotlock eq 'ok') {
15337: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15338: my $gotcode;
15339: my $attempts = 0;
15340: while ((!$gotcode) && ($attempts < 100)) {
15341: $code = &generate_code();
15342: if (!exists($currcodes{$code})) {
15343: $gotcode = 1;
15344: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15345: $error = 'nostore';
15346: }
15347: }
15348: $attempts ++;
15349: }
15350: my @del_lock = ($cnum."\0".'uniquecodes');
15351: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15352: } else {
15353: $error = 'nolock';
15354: }
15355: return ($code,$error);
15356: }
15357:
15358: sub generate_code {
15359: my $code;
15360: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15361: for (my $i=0; $i<6; $i++) {
15362: my $lettnum = int (rand 2);
15363: my $item = '';
15364: if ($lettnum) {
15365: $item = $letts[int( rand(18) )];
15366: } else {
15367: $item = 1+int( rand(8) );
15368: }
15369: $code .= $item;
15370: }
15371: return $code;
15372: }
15373:
15374: ############################################################
15375: ############################################################
15376:
15377: #SD
15378: # only Community and Course, or anything else?
15379: sub course_type {
15380: my ($cid) = @_;
15381: if (!defined($cid)) {
15382: $cid = $env{'request.course.id'};
15383: }
15384: if (defined($env{'course.'.$cid.'.type'})) {
15385: return $env{'course.'.$cid.'.type'};
15386: } else {
15387: return 'Course';
15388: }
15389: }
15390:
15391: sub group_term {
15392: my $crstype = &course_type();
15393: my %names = (
15394: 'Course' => 'group',
15395: 'Community' => 'group',
15396: );
15397: return $names{$crstype};
15398: }
15399:
15400: sub course_types {
15401: my @types = ('official','unofficial','community','textbook');
15402: my %typename = (
15403: official => 'Official course',
15404: unofficial => 'Unofficial course',
15405: community => 'Community',
15406: textbook => 'Textbook course',
15407: );
15408: return (\@types,\%typename);
15409: }
15410:
15411: sub icon {
15412: my ($file)=@_;
15413: my $curfext = lc((split(/\./,$file))[-1]);
15414: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15415: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15416: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15417: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15418: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15419: $curfext.".gif") {
15420: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15421: $curfext.".gif";
15422: }
15423: }
15424: return &lonhttpdurl($iconname);
15425: }
15426:
15427: sub lonhttpdurl {
15428: #
15429: # Had been used for "small fry" static images on separate port 8080.
15430: # Modify here if lightweight http functionality desired again.
15431: # Currently eliminated due to increasing firewall issues.
15432: #
15433: my ($url)=@_;
15434: return $url;
15435: }
15436:
15437: sub connection_aborted {
15438: my ($r)=@_;
15439: $r->print(" ");$r->rflush();
15440: my $c = $r->connection;
15441: return $c->aborted();
15442: }
15443:
15444: # Escapes strings that may have embedded 's that will be put into
15445: # strings as 'strings'.
15446: sub escape_single {
15447: my ($input) = @_;
15448: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
15449: $input =~ s/\'/\\\'/g; # Esacpe the 's....
15450: return $input;
15451: }
15452:
15453: # Same as escape_single, but escape's "'s This
15454: # can be used for "strings"
15455: sub escape_double {
15456: my ($input) = @_;
15457: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
15458: $input =~ s/\"/\\\"/g; # Esacpe the "s....
15459: return $input;
15460: }
15461:
15462: # Escapes the last element of a full URL.
15463: sub escape_url {
15464: my ($url) = @_;
15465: my @urlslices = split(/\//, $url,-1);
15466: my $lastitem = &escape(pop(@urlslices));
15467: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15468: }
15469:
15470: sub compare_arrays {
15471: my ($arrayref1,$arrayref2) = @_;
15472: my (@difference,%count);
15473: @difference = ();
15474: %count = ();
15475: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15476: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15477: foreach my $element (keys(%count)) {
15478: if ($count{$element} == 1) {
15479: push(@difference,$element);
15480: }
15481: }
15482: }
15483: return @difference;
15484: }
15485:
15486: # -------------------------------------------------------- Initialize user login
15487: sub init_user_environment {
15488: my ($r, $username, $domain, $authhost, $form, $args) = @_;
15489: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15490:
15491: my $public=($username eq 'public' && $domain eq 'public');
15492:
15493: # See if old ID present, if so, remove
15494:
15495: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15496: my $now=time;
15497:
15498: if ($public) {
15499: my $max_public=100;
15500: my $oldest;
15501: my $oldest_time=0;
15502: for(my $next=1;$next<=$max_public;$next++) {
15503: if (-e $lonids."/publicuser_$next.id") {
15504: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15505: if ($mtime<$oldest_time || !$oldest_time) {
15506: $oldest_time=$mtime;
15507: $oldest=$next;
15508: }
15509: } else {
15510: $cookie="publicuser_$next";
15511: last;
15512: }
15513: }
15514: if (!$cookie) { $cookie="publicuser_$oldest"; }
15515: } else {
15516: # if this isn't a robot, kill any existing non-robot sessions
15517: if (!$args->{'robot'}) {
15518: opendir(DIR,$lonids);
15519: while ($filename=readdir(DIR)) {
15520: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15521: unlink($lonids.'/'.$filename);
15522: }
15523: }
15524: closedir(DIR);
15525: # If there is a undeleted lockfile for the user's paste buffer remove it.
15526: my $namespace = 'nohist_courseeditor';
15527: my $lockingkey = 'paste'."\0".'locked_num';
15528: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15529: $domain,$username);
15530: if (exists($lockhash{$lockingkey})) {
15531: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15532: unless ($delresult eq 'ok') {
15533: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15534: }
15535: }
15536: }
15537: # Give them a new cookie
15538: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15539: : $now.$$.int(rand(10000)));
15540: $cookie="$username\_$id\_$domain\_$authhost";
15541:
15542: # Initialize roles
15543:
15544: ($userroles,$firstaccenv,$timerintenv) =
15545: &Apache::lonnet::rolesinit($domain,$username,$authhost);
15546: }
15547: # ------------------------------------ Check browser type and MathML capability
15548:
15549: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15550: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15551:
15552: # ------------------------------------------------------------- Get environment
15553:
15554: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15555: my ($tmp) = keys(%userenv);
15556: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15557: } else {
15558: undef(%userenv);
15559: }
15560: if (($userenv{'interface'}) && (!$form->{'interface'})) {
15561: $form->{'interface'}=$userenv{'interface'};
15562: }
15563: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15564:
15565: # --------------- Do not trust query string to be put directly into environment
15566: foreach my $option ('interface','localpath','localres') {
15567: $form->{$option}=~s/[\n\r\=]//gs;
15568: }
15569: # --------------------------------------------------------- Write first profile
15570:
15571: {
15572: my %initial_env =
15573: ("user.name" => $username,
15574: "user.domain" => $domain,
15575: "user.home" => $authhost,
15576: "browser.type" => $clientbrowser,
15577: "browser.version" => $clientversion,
15578: "browser.mathml" => $clientmathml,
15579: "browser.unicode" => $clientunicode,
15580: "browser.os" => $clientos,
15581: "browser.mobile" => $clientmobile,
15582: "browser.info" => $clientinfo,
15583: "browser.osversion" => $clientosversion,
15584: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
15585: "request.course.fn" => '',
15586: "request.course.uri" => '',
15587: "request.course.sec" => '',
15588: "request.role" => 'cm',
15589: "request.role.adv" => $env{'user.adv'},
15590: "request.host" => $ENV{'REMOTE_ADDR'},);
15591:
15592: if ($form->{'localpath'}) {
15593: $initial_env{"browser.localpath"} = $form->{'localpath'};
15594: $initial_env{"browser.localres"} = $form->{'localres'};
15595: }
15596:
15597: if ($form->{'interface'}) {
15598: $form->{'interface'}=~s/\W//gs;
15599: $initial_env{"browser.interface"} = $form->{'interface'};
15600: $env{'browser.interface'}=$form->{'interface'};
15601: }
15602:
15603: if ($form->{'iptoken'}) {
15604: my $lonhost = $r->dir_config('lonHostID');
15605: $initial_env{"user.noloadbalance"} = $lonhost;
15606: $env{'user.noloadbalance'} = $lonhost;
15607: }
15608:
15609: if ($form->{'noloadbalance'}) {
15610: my @hosts = &Apache::lonnet::current_machine_ids();
15611: my $hosthere = $form->{'noloadbalance'};
15612: if (grep(/^\Q$hosthere\E$/,@hosts)) {
15613: $initial_env{"user.noloadbalance"} = $hosthere;
15614: $env{'user.noloadbalance'} = $hosthere;
15615: }
15616: }
15617:
15618: unless ($domain eq 'public') {
15619: my %is_adv = ( is_adv => $env{'user.adv'} );
15620: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15621:
15622: foreach my $tool ('aboutme','blog','webdav','portfolio') {
15623: $userenv{'availabletools.'.$tool} =
15624: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15625: undef,\%userenv,\%domdef,\%is_adv);
15626: }
15627:
15628: foreach my $crstype ('official','unofficial','community','textbook') {
15629: $userenv{'canrequest.'.$crstype} =
15630: &Apache::lonnet::usertools_access($username,$domain,$crstype,
15631: 'reload','requestcourses',
15632: \%userenv,\%domdef,\%is_adv);
15633: }
15634:
15635: $userenv{'canrequest.author'} =
15636: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15637: 'reload','requestauthor',
15638: \%userenv,\%domdef,\%is_adv);
15639: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15640: $domain,$username);
15641: my $reqstatus = $reqauthor{'author_status'};
15642: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15643: if (ref($reqauthor{'author'}) eq 'HASH') {
15644: $userenv{'requestauthorqueued'} = $reqstatus.':'.
15645: $reqauthor{'author'}{'timestamp'};
15646: }
15647: }
15648: }
15649:
15650: $env{'user.environment'} = "$lonids/$cookie.id";
15651:
15652: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15653: &GDBM_WRCREAT(),0640)) {
15654: &_add_to_env(\%disk_env,\%initial_env);
15655: &_add_to_env(\%disk_env,\%userenv,'environment.');
15656: &_add_to_env(\%disk_env,$userroles);
15657: if (ref($firstaccenv) eq 'HASH') {
15658: &_add_to_env(\%disk_env,$firstaccenv);
15659: }
15660: if (ref($timerintenv) eq 'HASH') {
15661: &_add_to_env(\%disk_env,$timerintenv);
15662: }
15663: if (ref($args->{'extra_env'})) {
15664: &_add_to_env(\%disk_env,$args->{'extra_env'});
15665: }
15666: untie(%disk_env);
15667: } else {
15668: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15669: 'Could not create environment storage in lonauth: '.$!.'</span>');
15670: return 'error: '.$!;
15671: }
15672: }
15673: $env{'request.role'}='cm';
15674: $env{'request.role.adv'}=$env{'user.adv'};
15675: $env{'browser.type'}=$clientbrowser;
15676:
15677: return $cookie;
15678:
15679: }
15680:
15681: sub _add_to_env {
15682: my ($idf,$env_data,$prefix) = @_;
15683: if (ref($env_data) eq 'HASH') {
15684: while (my ($key,$value) = each(%$env_data)) {
15685: $idf->{$prefix.$key} = $value;
15686: $env{$prefix.$key} = $value;
15687: }
15688: }
15689: }
15690:
15691: # --- Get the symbolic name of a problem and the url
15692: sub get_symb {
15693: my ($request,$silent) = @_;
15694: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15695: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15696: if ($symb eq '') {
15697: if (!$silent) {
15698: if (ref($request)) {
15699: $request->print("Unable to handle ambiguous references:$url:.");
15700: }
15701: return ();
15702: }
15703: }
15704: &Apache::lonenc::check_decrypt(\$symb);
15705: return ($symb);
15706: }
15707:
15708: # --------------------------------------------------------------Get annotation
15709:
15710: sub get_annotation {
15711: my ($symb,$enc) = @_;
15712:
15713: my $key = $symb;
15714: if (!$enc) {
15715: $key =
15716: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15717: }
15718: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15719: return $annotation{$key};
15720: }
15721:
15722: sub clean_symb {
15723: my ($symb,$delete_enc) = @_;
15724:
15725: &Apache::lonenc::check_decrypt(\$symb);
15726: my $enc = $env{'request.enc'};
15727: if ($delete_enc) {
15728: delete($env{'request.enc'});
15729: }
15730:
15731: return ($symb,$enc);
15732: }
15733:
15734: ############################################################
15735: ############################################################
15736:
15737: =pod
15738:
15739: =head1 Routines for building display used to search for courses
15740:
15741:
15742: =over 4
15743:
15744: =item * &build_filters()
15745:
15746: Create markup for a table used to set filters to use when selecting
15747: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
15748: and quotacheck.pl
15749:
15750:
15751: Inputs:
15752:
15753: filterlist - anonymous array of fields to include as potential filters
15754:
15755: crstype - course type
15756:
15757: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15758: to pop-open a course selector (will contain "extra element").
15759:
15760: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15761:
15762: filter - anonymous hash of criteria and their values
15763:
15764: action - form action
15765:
15766: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15767:
15768: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15769:
15770: cloneruname - username of owner of new course who wants to clone
15771:
15772: clonerudom - domain of owner of new course who wants to clone
15773:
15774: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15775:
15776: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15777:
15778: codedom - domain
15779:
15780: formname - value of form element named "form".
15781:
15782: fixeddom - domain, if fixed.
15783:
15784: prevphase - value to assign to form element named "phase" when going back to the previous screen
15785:
15786: cnameelement - name of form element in form on opener page which will receive title of selected course
15787:
15788: cnumelement - name of form element in form on opener page which will receive courseID of selected course
15789:
15790: cdomelement - name of form element in form on opener page which will receive domain of selected course
15791:
15792: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15793:
15794: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15795:
15796: clonewarning - warning message about missing information for intended course owner when DC creates a course
15797:
15798:
15799: Returns: $output - HTML for display of search criteria, and hidden form elements.
15800:
15801:
15802: Side Effects: None
15803:
15804: =cut
15805:
15806: # ---------------------------------------------- search for courses based on last activity etc.
15807:
15808: sub build_filters {
15809: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15810: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15811: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15812: $cnameelement,$cnumelement,$cdomelement,$setroles,
15813: $clonetext,$clonewarning) = @_;
15814: my ($list,$jscript);
15815: my $onchange = 'javascript:updateFilters(this)';
15816: my ($domainselectform,$sincefilterform,$createdfilterform,
15817: $ownerdomselectform,$persondomselectform,$instcodeform,
15818: $typeselectform,$instcodetitle);
15819: if ($formname eq '') {
15820: $formname = $caller;
15821: }
15822: foreach my $item (@{$filterlist}) {
15823: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15824: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15825: if ($item eq 'domainfilter') {
15826: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15827: } elsif ($item eq 'coursefilter') {
15828: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15829: } elsif ($item eq 'ownerfilter') {
15830: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15831: } elsif ($item eq 'ownerdomfilter') {
15832: $filter->{'ownerdomfilter'} =
15833: &LONCAPA::clean_domain($filter->{$item});
15834: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15835: 'ownerdomfilter',1);
15836: } elsif ($item eq 'personfilter') {
15837: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15838: } elsif ($item eq 'persondomfilter') {
15839: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15840: 'persondomfilter',1);
15841: } else {
15842: $filter->{$item} =~ s/\W//g;
15843: }
15844: if (!$filter->{$item}) {
15845: $filter->{$item} = '';
15846: }
15847: }
15848: if ($item eq 'domainfilter') {
15849: my $allow_blank = 1;
15850: if ($formname eq 'portform') {
15851: $allow_blank=0;
15852: } elsif ($formname eq 'studentform') {
15853: $allow_blank=0;
15854: }
15855: if ($fixeddom) {
15856: $domainselectform = '<input type="hidden" name="domainfilter"'.
15857: ' value="'.$codedom.'" />'.
15858: &Apache::lonnet::domain($codedom,'description');
15859: } else {
15860: $domainselectform = &select_dom_form($filter->{$item},
15861: 'domainfilter',
15862: $allow_blank,'',$onchange);
15863: }
15864: } else {
15865: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15866: }
15867: }
15868:
15869: # last course activity filter and selection
15870: $sincefilterform = &timebased_select_form('sincefilter',$filter);
15871:
15872: # course created filter and selection
15873: if (exists($filter->{'createdfilter'})) {
15874: $createdfilterform = &timebased_select_form('createdfilter',$filter);
15875: }
15876:
15877: my %lt = &Apache::lonlocal::texthash(
15878: 'cac' => "$crstype Activity",
15879: 'ccr' => "$crstype Created",
15880: 'cde' => "$crstype Title",
15881: 'cdo' => "$crstype Domain",
15882: 'ins' => 'Institutional Code',
15883: 'inc' => 'Institutional Categorization',
15884: 'cow' => "$crstype Owner/Co-owner",
15885: 'cop' => "$crstype Personnel Includes",
15886: 'cog' => 'Type',
15887: );
15888:
15889: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15890: my $typeval = 'Course';
15891: if ($crstype eq 'Community') {
15892: $typeval = 'Community';
15893: }
15894: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15895: } else {
15896: $typeselectform = '<select name="type" size="1"';
15897: if ($onchange) {
15898: $typeselectform .= ' onchange="'.$onchange.'"';
15899: }
15900: $typeselectform .= '>'."\n";
15901: foreach my $posstype ('Course','Community') {
15902: $typeselectform.='<option value="'.$posstype.'"'.
15903: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15904: }
15905: $typeselectform.="</select>";
15906: }
15907:
15908: my ($cloneableonlyform,$cloneabletitle);
15909: if (exists($filter->{'cloneableonly'})) {
15910: my $cloneableon = '';
15911: my $cloneableoff = ' checked="checked"';
15912: if ($filter->{'cloneableonly'}) {
15913: $cloneableon = $cloneableoff;
15914: $cloneableoff = '';
15915: }
15916: $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/> '.&mt('Required').'</label>'.(' 'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' /> '.&mt('No restriction').'</label></span>';
15917: if ($formname eq 'ccrs') {
15918: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15919: } else {
15920: $cloneabletitle = &mt('Cloneable by you');
15921: }
15922: }
15923: my $officialjs;
15924: if ($crstype eq 'Course') {
15925: if (exists($filter->{'instcodefilter'})) {
15926: # if (($fixeddom) || ($formname eq 'requestcrs') ||
15927: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15928: if ($codedom) {
15929: $officialjs = 1;
15930: ($instcodeform,$jscript,$$numtitlesref) =
15931: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15932: $officialjs,$codetitlesref);
15933: if ($jscript) {
15934: $jscript = '<script type="text/javascript">'."\n".
15935: '// <![CDATA['."\n".
15936: $jscript."\n".
15937: '// ]]>'."\n".
15938: '</script>'."\n";
15939: }
15940: }
15941: if ($instcodeform eq '') {
15942: $instcodeform =
15943: '<input type="text" name="instcodefilter" size="10" value="'.
15944: $list->{'instcodefilter'}.'" />';
15945: $instcodetitle = $lt{'ins'};
15946: } else {
15947: $instcodetitle = $lt{'inc'};
15948: }
15949: if ($fixeddom) {
15950: $instcodetitle .= '<br />('.$codedom.')';
15951: }
15952: }
15953: }
15954: my $output = qq|
15955: <form method="post" name="filterpicker" action="$action">
15956: <input type="hidden" name="form" value="$formname" />
15957: |;
15958: if ($formname eq 'modifycourse') {
15959: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15960: '<input type="hidden" name="prevphase" value="'.
15961: $prevphase.'" />'."\n";
15962: } elsif ($formname eq 'quotacheck') {
15963: $output .= qq|
15964: <input type="hidden" name="sortby" value="" />
15965: <input type="hidden" name="sortorder" value="" />
15966: |;
15967: } else {
15968: my $name_input;
15969: if ($cnameelement ne '') {
15970: $name_input = '<input type="hidden" name="cnameelement" value="'.
15971: $cnameelement.'" />';
15972: }
15973: $output .= qq|
15974: <input type="hidden" name="cnumelement" value="$cnumelement" />
15975: <input type="hidden" name="cdomelement" value="$cdomelement" />
15976: $name_input
15977: $roleelement
15978: $multelement
15979: $typeelement
15980: |;
15981: if ($formname eq 'portform') {
15982: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15983: }
15984: }
15985: if ($fixeddom) {
15986: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15987: }
15988: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15989: if ($sincefilterform) {
15990: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15991: .$sincefilterform
15992: .&Apache::lonhtmlcommon::row_closure();
15993: }
15994: if ($createdfilterform) {
15995: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15996: .$createdfilterform
15997: .&Apache::lonhtmlcommon::row_closure();
15998: }
15999: if ($domainselectform) {
16000: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16001: .$domainselectform
16002: .&Apache::lonhtmlcommon::row_closure();
16003: }
16004: if ($typeselectform) {
16005: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16006: $output .= $typeselectform;
16007: } else {
16008: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16009: .$typeselectform
16010: .&Apache::lonhtmlcommon::row_closure();
16011: }
16012: }
16013: if ($instcodeform) {
16014: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16015: .$instcodeform
16016: .&Apache::lonhtmlcommon::row_closure();
16017: }
16018: if (exists($filter->{'ownerfilter'})) {
16019: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16020: '<table><tr><td>'.&mt('Username').'<br />'.
16021: '<input type="text" name="ownerfilter" size="20" value="'.
16022: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16023: $ownerdomselectform.'</td></tr></table>'.
16024: &Apache::lonhtmlcommon::row_closure();
16025: }
16026: if (exists($filter->{'personfilter'})) {
16027: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16028: '<table><tr><td>'.&mt('Username').'<br />'.
16029: '<input type="text" name="personfilter" size="20" value="'.
16030: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16031: $persondomselectform.'</td></tr></table>'.
16032: &Apache::lonhtmlcommon::row_closure();
16033: }
16034: if (exists($filter->{'coursefilter'})) {
16035: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16036: .'<input type="text" name="coursefilter" size="25" value="'
16037: .$list->{'coursefilter'}.'" />'
16038: .&Apache::lonhtmlcommon::row_closure();
16039: }
16040: if ($cloneableonlyform) {
16041: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16042: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16043: }
16044: if (exists($filter->{'descriptfilter'})) {
16045: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16046: .'<input type="text" name="descriptfilter" size="40" value="'
16047: .$list->{'descriptfilter'}.'" />'
16048: .&Apache::lonhtmlcommon::row_closure(1);
16049: }
16050: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16051: '<input type="hidden" name="updater" value="" />'."\n".
16052: '<input type="submit" name="gosearch" value="'.
16053: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16054: return $jscript.$clonewarning.$output;
16055: }
16056:
16057: =pod
16058:
16059: =item * &timebased_select_form()
16060:
16061: Create markup for a dropdown list used to select a time-based
16062: filter e.g., Course Activity, Course Created, when searching for courses
16063: or communities
16064:
16065: Inputs:
16066:
16067: item - name of form element (sincefilter or createdfilter)
16068:
16069: filter - anonymous hash of criteria and their values
16070:
16071: Returns: HTML for a select box contained a blank, then six time selections,
16072: with value set in incoming form variables currently selected.
16073:
16074: Side Effects: None
16075:
16076: =cut
16077:
16078: sub timebased_select_form {
16079: my ($item,$filter) = @_;
16080: if (ref($filter) eq 'HASH') {
16081: $filter->{$item} =~ s/[^\d-]//g;
16082: if (!$filter->{$item}) { $filter->{$item}=-1; }
16083: return &select_form(
16084: $filter->{$item},
16085: $item,
16086: { '-1' => '',
16087: '86400' => &mt('today'),
16088: '604800' => &mt('last week'),
16089: '2592000' => &mt('last month'),
16090: '7776000' => &mt('last three months'),
16091: '15552000' => &mt('last six months'),
16092: '31104000' => &mt('last year'),
16093: 'select_form_order' =>
16094: ['-1','86400','604800','2592000','7776000',
16095: '15552000','31104000']});
16096: }
16097: }
16098:
16099: =pod
16100:
16101: =item * &js_changer()
16102:
16103: Create script tag containing Javascript used to submit course search form
16104: when course type or domain is changed, and also to hide 'Searching ...' on
16105: page load completion for page showing search result.
16106:
16107: Inputs: None
16108:
16109: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16110:
16111: Side Effects: None
16112:
16113: =cut
16114:
16115: sub js_changer {
16116: return <<ENDJS;
16117: <script type="text/javascript">
16118: // <![CDATA[
16119: function updateFilters(caller) {
16120: if (typeof(caller) != "undefined") {
16121: document.filterpicker.updater.value = caller.name;
16122: }
16123: document.filterpicker.submit();
16124: }
16125:
16126: function hideSearching() {
16127: if (document.getElementById('searching')) {
16128: document.getElementById('searching').style.display = 'none';
16129: }
16130: return;
16131: }
16132:
16133: // ]]>
16134: </script>
16135:
16136: ENDJS
16137: }
16138:
16139: =pod
16140:
16141: =item * &search_courses()
16142:
16143: Process selected filters form course search form and pass to lonnet::courseiddump
16144: to retrieve a hash for which keys are courseIDs which match the selected filters.
16145:
16146: Inputs:
16147:
16148: dom - domain being searched
16149:
16150: type - course type ('Course' or 'Community' or '.' if any).
16151:
16152: filter - anonymous hash of criteria and their values
16153:
16154: numtitles - for institutional codes - number of categories
16155:
16156: cloneruname - optional username of new course owner
16157:
16158: clonerudom - optional domain of new course owner
16159:
16160: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16161: (used when DC is using course creation form)
16162:
16163: codetitles - reference to array of titles of components in institutional codes (official courses).
16164:
16165: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16166: (and so can clone automatically)
16167:
16168: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16169:
16170: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16171: courses to clone
16172:
16173: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16174:
16175:
16176: Side Effects: None
16177:
16178: =cut
16179:
16180:
16181: sub search_courses {
16182: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16183: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16184: my (%courses,%showcourses,$cloner);
16185: if (($filter->{'ownerfilter'} ne '') ||
16186: ($filter->{'ownerdomfilter'} ne '')) {
16187: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16188: $filter->{'ownerdomfilter'};
16189: }
16190: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16191: if (!$filter->{$item}) {
16192: $filter->{$item}='.';
16193: }
16194: }
16195: my $now = time;
16196: my $timefilter =
16197: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16198: my ($createdbefore,$createdafter);
16199: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16200: $createdbefore = $now;
16201: $createdafter = $now-$filter->{'createdfilter'};
16202: }
16203: my ($instcodefilter,$regexpok);
16204: if ($numtitles) {
16205: if ($env{'form.official'} eq 'on') {
16206: $instcodefilter =
16207: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16208: $regexpok = 1;
16209: } elsif ($env{'form.official'} eq 'off') {
16210: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16211: unless ($instcodefilter eq '') {
16212: $regexpok = -1;
16213: }
16214: }
16215: } else {
16216: $instcodefilter = $filter->{'instcodefilter'};
16217: }
16218: if ($instcodefilter eq '') { $instcodefilter = '.'; }
16219: if ($type eq '') { $type = '.'; }
16220:
16221: if (($clonerudom ne '') && ($cloneruname ne '')) {
16222: $cloner = $cloneruname.':'.$clonerudom;
16223: }
16224: %courses = &Apache::lonnet::courseiddump($dom,
16225: $filter->{'descriptfilter'},
16226: $timefilter,
16227: $instcodefilter,
16228: $filter->{'combownerfilter'},
16229: $filter->{'coursefilter'},
16230: undef,undef,$type,$regexpok,undef,undef,
16231: undef,undef,$cloner,$cc_clone,
16232: $filter->{'cloneableonly'},
16233: $createdbefore,$createdafter,undef,
16234: $domcloner,undef,$reqcrsdom,$reqinstcode);
16235: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16236: my $ccrole;
16237: if ($type eq 'Community') {
16238: $ccrole = 'co';
16239: } else {
16240: $ccrole = 'cc';
16241: }
16242: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16243: $filter->{'persondomfilter'},
16244: 'userroles',undef,
16245: [$ccrole,'in','ad','ep','ta','cr'],
16246: $dom);
16247: foreach my $role (keys(%rolehash)) {
16248: my ($cnum,$cdom,$courserole) = split(':',$role);
16249: my $cid = $cdom.'_'.$cnum;
16250: if (exists($courses{$cid})) {
16251: if (ref($courses{$cid}) eq 'HASH') {
16252: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16253: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16254: push(@{$courses{$cid}{roles}},$courserole);
16255: }
16256: } else {
16257: $courses{$cid}{roles} = [$courserole];
16258: }
16259: $showcourses{$cid} = $courses{$cid};
16260: }
16261: }
16262: }
16263: %courses = %showcourses;
16264: }
16265: return %courses;
16266: }
16267:
16268: =pod
16269:
16270: =back
16271:
16272: =head1 Routines for version requirements for current course.
16273:
16274: =over 4
16275:
16276: =item * &check_release_required()
16277:
16278: Compares required LON-CAPA version with version on server, and
16279: if required version is newer looks for a server with the required version.
16280:
16281: Looks first at servers in user's owen domain; if none suitable, looks at
16282: servers in course's domain are permitted to host sessions for user's domain.
16283:
16284: Inputs:
16285:
16286: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16287:
16288: $courseid - Course ID of current course
16289:
16290: $rolecode - User's current role in course (for switchserver query string).
16291:
16292: $required - LON-CAPA version needed by course (format: Major.Minor).
16293:
16294:
16295: Returns:
16296:
16297: $switchserver - query string tp append to /adm/switchserver call (if
16298: current server's LON-CAPA version is too old.
16299:
16300: $warning - Message is displayed if no suitable server could be found.
16301:
16302: =cut
16303:
16304: sub check_release_required {
16305: my ($loncaparev,$courseid,$rolecode,$required) = @_;
16306: my ($switchserver,$warning);
16307: if ($required ne '') {
16308: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16309: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16310: if ($reqdmajor ne '' && $reqdminor ne '') {
16311: my $otherserver;
16312: if (($major eq '' && $minor eq '') ||
16313: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16314: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16315: my $switchlcrev =
16316: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16317: $userdomserver);
16318: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16319: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16320: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16321: my $cdom = $env{'course.'.$courseid.'.domain'};
16322: if ($cdom ne $env{'user.domain'}) {
16323: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16324: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16325: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16326: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16327: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16328: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16329: my $canhost =
16330: &Apache::lonnet::can_host_session($env{'user.domain'},
16331: $coursedomserver,
16332: $remoterev,
16333: $udomdefaults{'remotesessions'},
16334: $defdomdefaults{'hostedsessions'});
16335:
16336: if ($canhost) {
16337: $otherserver = $coursedomserver;
16338: } else {
16339: $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
16340: }
16341: } else {
16342: $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
16343: }
16344: } else {
16345: $otherserver = $userdomserver;
16346: }
16347: }
16348: if ($otherserver ne '') {
16349: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
16350: }
16351: }
16352: }
16353: return ($switchserver,$warning);
16354: }
16355:
16356: =pod
16357:
16358: =item * &check_release_result()
16359:
16360: Inputs:
16361:
16362: $switchwarning - Warning message if no suitable server found to host session.
16363:
16364: $switchserver - query string to append to /adm/switchserver containing lonHostID
16365: and current role.
16366:
16367: Returns: HTML to display with information about requirement to switch server.
16368: Either displaying warning with link to Roles/Courses screen or
16369: display link to switchserver.
16370:
16371: =cut
16372:
16373: sub check_release_result {
16374: my ($switchwarning,$switchserver) = @_;
16375: my $output = &start_page('Selected course unavailable on this server').
16376: '<p class="LC_warning">';
16377: if ($switchwarning) {
16378: $output .= $switchwarning.'<br /><a href="/adm/roles">';
16379: if (&show_course()) {
16380: $output .= &mt('Display courses');
16381: } else {
16382: $output .= &mt('Display roles');
16383: }
16384: $output .= '</a>';
16385: } elsif ($switchserver) {
16386: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16387: '<br />'.
16388: '<a href="/adm/switchserver?'.$switchserver.'">'.
16389: &mt('Switch Server').
16390: '</a>';
16391: }
16392: $output .= '</p>'.&end_page();
16393: return $output;
16394: }
16395:
16396: =pod
16397:
16398: =item * &needs_coursereinit()
16399:
16400: Determine if course contents stored for user's session needs to be
16401: refreshed, because content has changed since "Big Hash" last tied.
16402:
16403: Check for change is made if time last checked is more than 10 minutes ago
16404: (by default).
16405:
16406: Inputs:
16407:
16408: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16409:
16410: $interval (optional) - Time which may elapse (in s) between last check for content
16411: change in current course. (default: 600 s).
16412:
16413: Returns: an array; first element is:
16414:
16415: =over 4
16416:
16417: 'switch' - if content updates mean user's session
16418: needs to be switched to a server running a newer LON-CAPA version
16419:
16420: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16421: on current server hosting user's session
16422:
16423: '' - if no action required.
16424:
16425: =back
16426:
16427: If first item element is 'switch':
16428:
16429: second item is $switchwarning - Warning message if no suitable server found to host session.
16430:
16431: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16432: and current role.
16433:
16434: otherwise: no other elements returned.
16435:
16436: =back
16437:
16438: =cut
16439:
16440: sub needs_coursereinit {
16441: my ($loncaparev,$interval) = @_;
16442: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16443: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16444: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16445: my $now = time;
16446: if ($interval eq '') {
16447: $interval = 600;
16448: }
16449: if (($now-$env{'request.course.timechecked'})>$interval) {
16450: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16451: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16452: if ($lastchange > $env{'request.course.tied'}) {
16453: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16454: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16455: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16456: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16457: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16458: $curr_reqd_hash{'internal.releaserequired'}});
16459: my ($switchserver,$switchwarning) =
16460: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16461: $curr_reqd_hash{'internal.releaserequired'});
16462: if ($switchwarning ne '' || $switchserver ne '') {
16463: return ('switch',$switchwarning,$switchserver);
16464: }
16465: }
16466: }
16467: return ('update');
16468: }
16469: }
16470: return ();
16471: }
16472:
16473: sub update_content_constraints {
16474: my ($cdom,$cnum,$chome,$cid) = @_;
16475: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16476: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16477: my %checkresponsetypes;
16478: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16479: my ($item,$name,$value) = split(/:/,$key);
16480: if ($item eq 'resourcetag') {
16481: if ($name eq 'responsetype') {
16482: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16483: }
16484: }
16485: }
16486: my $navmap = Apache::lonnavmaps::navmap->new();
16487: if (defined($navmap)) {
16488: my %allresponses;
16489: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16490: my %responses = $res->responseTypes();
16491: foreach my $key (keys(%responses)) {
16492: next unless(exists($checkresponsetypes{$key}));
16493: $allresponses{$key} += $responses{$key};
16494: }
16495: }
16496: foreach my $key (keys(%allresponses)) {
16497: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16498: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16499: ($reqdmajor,$reqdminor) = ($major,$minor);
16500: }
16501: }
16502: undef($navmap);
16503: }
16504: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16505: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16506: }
16507: return;
16508: }
16509:
16510: sub allmaps_incourse {
16511: my ($cdom,$cnum,$chome,$cid) = @_;
16512: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16513: $cid = $env{'request.course.id'};
16514: $cdom = $env{'course.'.$cid.'.domain'};
16515: $cnum = $env{'course.'.$cid.'.num'};
16516: $chome = $env{'course.'.$cid.'.home'};
16517: }
16518: my %allmaps = ();
16519: my $lastchange =
16520: &Apache::lonnet::get_coursechange($cdom,$cnum);
16521: if ($lastchange > $env{'request.course.tied'}) {
16522: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16523: unless ($ferr) {
16524: &update_content_constraints($cdom,$cnum,$chome,$cid);
16525: }
16526: }
16527: my $navmap = Apache::lonnavmaps::navmap->new();
16528: if (defined($navmap)) {
16529: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16530: $allmaps{$res->src()} = 1;
16531: }
16532: }
16533: return \%allmaps;
16534: }
16535:
16536: sub parse_supplemental_title {
16537: my ($title) = @_;
16538:
16539: my ($foldertitle,$renametitle);
16540: if ($title =~ /&&&/) {
16541: $title = &HTML::Entites::decode($title);
16542: }
16543: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16544: $renametitle=$4;
16545: my ($time,$uname,$udom) = ($1,$2,$3);
16546: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16547: my $name = &plainname($uname,$udom);
16548: $name = &HTML::Entities::encode($name,'"<>&\'');
16549: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16550: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16551: $name.': <br />'.$foldertitle;
16552: }
16553: if (wantarray) {
16554: return ($title,$foldertitle,$renametitle);
16555: }
16556: return $title;
16557: }
16558:
16559: sub recurse_supplemental {
16560: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16561: if ($suppmap) {
16562: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16563: if ($fatal) {
16564: $errors ++;
16565: } else {
16566: if ($#LONCAPA::map::resources > 0) {
16567: foreach my $res (@LONCAPA::map::resources) {
16568: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16569: if (($src ne '') && ($status eq 'res')) {
16570: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16571: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16572: } else {
16573: $numfiles ++;
16574: }
16575: }
16576: }
16577: }
16578: }
16579: }
16580: return ($numfiles,$errors);
16581: }
16582:
16583: sub symb_to_docspath {
16584: my ($symb,$navmapref) = @_;
16585: return unless ($symb && ref($navmapref));
16586: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16587: if ($resurl=~/\.(sequence|page)$/) {
16588: $mapurl=$resurl;
16589: } elsif ($resurl eq 'adm/navmaps') {
16590: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16591: }
16592: my $mapresobj;
16593: unless (ref($$navmapref)) {
16594: $$navmapref = Apache::lonnavmaps::navmap->new();
16595: }
16596: if (ref($$navmapref)) {
16597: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16598: }
16599: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16600: my $type=$2;
16601: my $path;
16602: if (ref($mapresobj)) {
16603: my $pcslist = $mapresobj->map_hierarchy();
16604: if ($pcslist ne '') {
16605: foreach my $pc (split(/,/,$pcslist)) {
16606: next if ($pc <= 1);
16607: my $res = $$navmapref->getByMapPc($pc);
16608: if (ref($res)) {
16609: my $thisurl = $res->src();
16610: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16611: my $thistitle = $res->title();
16612: $path .= '&'.
16613: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16614: &escape($thistitle).
16615: ':'.$res->randompick().
16616: ':'.$res->randomout().
16617: ':'.$res->encrypted().
16618: ':'.$res->randomorder().
16619: ':'.$res->is_page();
16620: }
16621: }
16622: }
16623: $path =~ s/^\&//;
16624: my $maptitle = $mapresobj->title();
16625: if ($mapurl eq 'default') {
16626: $maptitle = 'Main Content';
16627: }
16628: $path .= (($path ne '')? '&' : '').
16629: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16630: &escape($maptitle).
16631: ':'.$mapresobj->randompick().
16632: ':'.$mapresobj->randomout().
16633: ':'.$mapresobj->encrypted().
16634: ':'.$mapresobj->randomorder().
16635: ':'.$mapresobj->is_page();
16636: } else {
16637: my $maptitle = &Apache::lonnet::gettitle($mapurl);
16638: my $ispage = (($type eq 'page')? 1 : '');
16639: if ($mapurl eq 'default') {
16640: $maptitle = 'Main Content';
16641: }
16642: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16643: &escape($maptitle).':::::'.$ispage;
16644: }
16645: unless ($mapurl eq 'default') {
16646: $path = 'default&'.
16647: &escape('Main Content').
16648: ':::::&'.$path;
16649: }
16650: return $path;
16651: }
16652:
16653: sub captcha_display {
16654: my ($context,$lonhost) = @_;
16655: my ($output,$error);
16656: my ($captcha,$pubkey,$privkey,$version) =
16657: &get_captcha_config($context,$lonhost);
16658: if ($captcha eq 'original') {
16659: $output = &create_captcha();
16660: unless ($output) {
16661: $error = 'captcha';
16662: }
16663: } elsif ($captcha eq 'recaptcha') {
16664: $output = &create_recaptcha($pubkey,$version);
16665: unless ($output) {
16666: $error = 'recaptcha';
16667: }
16668: }
16669: return ($output,$error,$captcha,$version);
16670: }
16671:
16672: sub captcha_response {
16673: my ($context,$lonhost) = @_;
16674: my ($captcha_chk,$captcha_error);
16675: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16676: if ($captcha eq 'original') {
16677: ($captcha_chk,$captcha_error) = &check_captcha();
16678: } elsif ($captcha eq 'recaptcha') {
16679: $captcha_chk = &check_recaptcha($privkey,$version);
16680: } else {
16681: $captcha_chk = 1;
16682: }
16683: return ($captcha_chk,$captcha_error);
16684: }
16685:
16686: sub get_captcha_config {
16687: my ($context,$lonhost) = @_;
16688: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16689: my $hostname = &Apache::lonnet::hostname($lonhost);
16690: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16691: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16692: if ($context eq 'usercreation') {
16693: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16694: if (ref($domconfig{$context}) eq 'HASH') {
16695: $hashtocheck = $domconfig{$context}{'cancreate'};
16696: if (ref($hashtocheck) eq 'HASH') {
16697: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16698: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16699: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16700: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16701: }
16702: if ($privkey && $pubkey) {
16703: $captcha = 'recaptcha';
16704: $version = $hashtocheck->{'recaptchaversion'};
16705: if ($version ne '2') {
16706: $version = 1;
16707: }
16708: } else {
16709: $captcha = 'original';
16710: }
16711: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16712: $captcha = 'original';
16713: }
16714: }
16715: } else {
16716: $captcha = 'captcha';
16717: }
16718: } elsif ($context eq 'login') {
16719: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16720: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16721: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16722: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16723: if ($privkey && $pubkey) {
16724: $captcha = 'recaptcha';
16725: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16726: if ($version ne '2') {
16727: $version = 1;
16728: }
16729: } else {
16730: $captcha = 'original';
16731: }
16732: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16733: $captcha = 'original';
16734: }
16735: }
16736: return ($captcha,$pubkey,$privkey,$version);
16737: }
16738:
16739: sub create_captcha {
16740: my %captcha_params = &captcha_settings();
16741: my ($output,$maxtries,$tries) = ('',10,0);
16742: while ($tries < $maxtries) {
16743: $tries ++;
16744: my $captcha = Authen::Captcha->new (
16745: output_folder => $captcha_params{'output_dir'},
16746: data_folder => $captcha_params{'db_dir'},
16747: );
16748: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16749:
16750: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16751: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16752: &mt('Type in the letters/numbers shown below').' '.
16753: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16754: '<br />'.
16755: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16756: last;
16757: }
16758: }
16759: return $output;
16760: }
16761:
16762: sub captcha_settings {
16763: my %captcha_params = (
16764: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16765: www_output_dir => "/captchaspool",
16766: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16767: numchars => '5',
16768: );
16769: return %captcha_params;
16770: }
16771:
16772: sub check_captcha {
16773: my ($captcha_chk,$captcha_error);
16774: my $code = $env{'form.code'};
16775: my $md5sum = $env{'form.crypt'};
16776: my %captcha_params = &captcha_settings();
16777: my $captcha = Authen::Captcha->new(
16778: output_folder => $captcha_params{'output_dir'},
16779: data_folder => $captcha_params{'db_dir'},
16780: );
16781: $captcha_chk = $captcha->check_code($code,$md5sum);
16782: my %captcha_hash = (
16783: 0 => 'Code not checked (file error)',
16784: -1 => 'Failed: code expired',
16785: -2 => 'Failed: invalid code (not in database)',
16786: -3 => 'Failed: invalid code (code does not match crypt)',
16787: );
16788: if ($captcha_chk != 1) {
16789: $captcha_error = $captcha_hash{$captcha_chk}
16790: }
16791: return ($captcha_chk,$captcha_error);
16792: }
16793:
16794: sub create_recaptcha {
16795: my ($pubkey,$version) = @_;
16796: if ($version >= 2) {
16797: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16798: } else {
16799: my $use_ssl;
16800: if ($ENV{'SERVER_PORT'} == 443) {
16801: $use_ssl = 1;
16802: }
16803: my $captcha = Captcha::reCAPTCHA->new;
16804: return $captcha->get_options_setter({theme => 'white'})."\n".
16805: $captcha->get_html($pubkey,undef,$use_ssl).
16806: &mt('If the text is hard to read, [_1] will replace them.',
16807: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16808: '<br /><br />';
16809: }
16810: }
16811:
16812: sub check_recaptcha {
16813: my ($privkey,$version) = @_;
16814: my $captcha_chk;
16815: if ($version >= 2) {
16816: my $ua = LWP::UserAgent->new;
16817: $ua->timeout(10);
16818: my %info = (
16819: secret => $privkey,
16820: response => $env{'form.g-recaptcha-response'},
16821: remoteip => $ENV{'REMOTE_ADDR'},
16822: );
16823: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16824: if ($response->is_success) {
16825: my $data = JSON::DWIW->from_json($response->decoded_content);
16826: if (ref($data) eq 'HASH') {
16827: if ($data->{'success'}) {
16828: $captcha_chk = 1;
16829: }
16830: }
16831: }
16832: } else {
16833: my $captcha = Captcha::reCAPTCHA->new;
16834: my $captcha_result =
16835: $captcha->check_answer(
16836: $privkey,
16837: $ENV{'REMOTE_ADDR'},
16838: $env{'form.recaptcha_challenge_field'},
16839: $env{'form.recaptcha_response_field'},
16840: );
16841: if ($captcha_result->{is_valid}) {
16842: $captcha_chk = 1;
16843: }
16844: }
16845: return $captcha_chk;
16846: }
16847:
16848: sub emailusername_info {
16849: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16850: my %titles = &Apache::lonlocal::texthash (
16851: lastname => 'Last Name',
16852: firstname => 'First Name',
16853: institution => 'School/college/university',
16854: location => "School's city, state/province, country",
16855: web => "School's web address",
16856: officialemail => 'E-mail address at institution (if different)',
16857: id => 'Student/Employee ID',
16858: );
16859: return (\@fields,\%titles);
16860: }
16861:
16862: sub cleanup_html {
16863: my ($incoming) = @_;
16864: my $outgoing;
16865: if ($incoming ne '') {
16866: $outgoing = $incoming;
16867: $outgoing =~ s/;/;/g;
16868: $outgoing =~ s/\#/#/g;
16869: $outgoing =~ s/\&/&/g;
16870: $outgoing =~ s/</</g;
16871: $outgoing =~ s/>/>/g;
16872: $outgoing =~ s/\(/(/g;
16873: $outgoing =~ s/\)/)/g;
16874: $outgoing =~ s/"/"/g;
16875: $outgoing =~ s/'/'/g;
16876: $outgoing =~ s/\$/$/g;
16877: $outgoing =~ s{/}{/}g;
16878: $outgoing =~ s/=/=/g;
16879: $outgoing =~ s/\\/\/g
16880: }
16881: return $outgoing;
16882: }
16883:
16884: # Checks for critical messages and returns a redirect url if one exists.
16885: # $interval indicates how often to check for messages.
16886: sub critical_redirect {
16887: my ($interval) = @_;
16888: if ((time-$env{'user.criticalcheck.time'})>$interval) {
16889: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16890: $env{'user.name'});
16891: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16892: my $redirecturl;
16893: if ($what[0]) {
16894: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16895: $redirecturl='/adm/email?critical=display';
16896: my $url=&Apache::lonnet::absolute_url().$redirecturl;
16897: return (1, $url);
16898: }
16899: }
16900: }
16901: return ();
16902: }
16903:
16904: # Use:
16905: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16906: #
16907: ##################################################
16908: # password associated functions #
16909: ##################################################
16910: sub des_keys {
16911: # Make a new key for DES encryption.
16912: # Each key has two parts which are returned separately.
16913: # Please note: Each key must be passed through the &hex function
16914: # before it is output to the web browser. The hex versions cannot
16915: # be used to decrypt.
16916: my @hexstr=('0','1','2','3','4','5','6','7',
16917: '8','9','a','b','c','d','e','f');
16918: my $lkey='';
16919: for (0..7) {
16920: $lkey.=$hexstr[rand(15)];
16921: }
16922: my $ukey='';
16923: for (0..7) {
16924: $ukey.=$hexstr[rand(15)];
16925: }
16926: return ($lkey,$ukey);
16927: }
16928:
16929: sub des_decrypt {
16930: my ($key,$cyphertext) = @_;
16931: my $keybin=pack("H16",$key);
16932: my $cypher;
16933: if ($Crypt::DES::VERSION>=2.03) {
16934: $cypher=new Crypt::DES $keybin;
16935: } else {
16936: $cypher=new DES $keybin;
16937: }
16938: my $plaintext='';
16939: my $cypherlength = length($cyphertext);
16940: my $numchunks = int($cypherlength/32);
16941: for (my $j=0; $j<$numchunks; $j++) {
16942: my $start = $j*32;
16943: my $cypherblock = substr($cyphertext,$start,32);
16944: my $chunk =
16945: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16946: $chunk .=
16947: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16948: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16949: $plaintext .= $chunk;
16950: }
16951: return $plaintext;
16952: }
16953:
16954: 1;
16955: __END__;
16956:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>