File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1406:
download - view:
text,
annotated -
select for diffs
Sat Jun 10 23:55:36 2023 UTC (14 months, 1 week ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Move "Quick search" box to be left-most of three boxes above directory
listing
- Move "Actions for current directory" into row above, between select box
for recently accessed diretories, and disk spce utilization display.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1406 2023/06/10 23:55:36 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::lonnavmaps();
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 LONCAPA::LWPReq;
75: use LONCAPA::map();
76: use HTTP::Request;
77: use DateTime::TimeZone;
78: use DateTime::Locale;
79: use Encode();
80: use Text::Aspell;
81: use Authen::Captcha;
82: use Captcha::reCAPTCHA;
83: use JSON::DWIW;
84: use Crypt::DES;
85: use DynaLoader; # for Crypt::DES version
86: use MIME::Lite;
87: use MIME::Types;
88: use File::Copy();
89: use File::Path();
90: use String::CRC32();
91: use Short::URL();
92:
93: # ---------------------------------------------- Designs
94: use vars qw(%defaultdesign);
95:
96: my $readit;
97:
98:
99: ##
100: ## Global Variables
101: ##
102:
103:
104: # ----------------------------------------------- SSI with retries:
105: #
106:
107: =pod
108:
109: =head1 Server Side include with retries:
110:
111: =over 4
112:
113: =item * &ssi_with_retries(resource,retries form)
114:
115: Performs an ssi with some number of retries. Retries continue either
116: until the result is ok or until the retry count supplied by the
117: caller is exhausted.
118:
119: Inputs:
120:
121: =over 4
122:
123: resource - Identifies the resource to insert.
124:
125: retries - Count of the number of retries allowed.
126:
127: form - Hash that identifies the rendering options.
128:
129: =back
130:
131: Returns:
132:
133: =over 4
134:
135: content - The content of the response. If retries were exhausted this is empty.
136:
137: response - The response from the last attempt (which may or may not have been successful.
138:
139: =back
140:
141: =back
142:
143: =cut
144:
145: sub ssi_with_retries {
146: my ($resource, $retries, %form) = @_;
147:
148:
149: my $ok = 0; # True if we got a good response.
150: my $content;
151: my $response;
152:
153: # Try to get the ssi done. within the retries count:
154:
155: do {
156: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
157: $ok = $response->is_success;
158: if (!$ok) {
159: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
160: }
161: $retries--;
162: } while (!$ok && ($retries > 0));
163:
164: if (!$ok) {
165: $content = ''; # On error return an empty content.
166: }
167: return ($content, $response);
168:
169: }
170:
171:
172:
173: # ----------------------------------------------- Filetypes/Languages/Copyright
174: my %language;
175: my %supported_language;
176: my %supported_codes;
177: my %latex_language; # For choosing hyphenation in <transl..>
178: my %latex_language_bykey; # for choosing hyphenation from metadata
179: my %cprtag;
180: my %scprtag;
181: my %fe; my %fd; my %fm;
182: my %category_extensions;
183:
184: # ---------------------------------------------- Thesaurus variables
185: #
186: # %Keywords:
187: # A hash used by &keyword to determine if a word is considered a keyword.
188: # $thesaurus_db_file
189: # Scalar containing the full path to the thesaurus database.
190:
191: my %Keywords;
192: my $thesaurus_db_file;
193:
194: #
195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
196: # thesaurus.tab, and filecategories.tab.
197: #
198: BEGIN {
199: # Variable initialization
200: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
201: #
202: unless ($readit) {
203: # ------------------------------------------------------------------- languages
204: {
205: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
206: '/language.tab';
207: if ( open(my $fh,'<',$langtabfile) ) {
208: while (my $line = <$fh>) {
209: next if ($line=~/^\#/);
210: chomp($line);
211: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
212: $language{$key}=$val.' - '.$enc;
213: if ($sup) {
214: $supported_language{$key}=$sup;
215: $supported_codes{$key} = $code;
216: }
217: if ($latex) {
218: $latex_language_bykey{$key} = $latex;
219: $latex_language{$code} = $latex;
220: }
221: }
222: close($fh);
223: }
224: }
225: # ------------------------------------------------------------------ copyrights
226: {
227: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
228: '/copyright.tab';
229: if ( open (my $fh,'<',$copyrightfile) ) {
230: while (my $line = <$fh>) {
231: next if ($line=~/^\#/);
232: chomp($line);
233: my ($key,$val)=(split(/\s+/,$line,2));
234: $cprtag{$key}=$val;
235: }
236: close($fh);
237: }
238: }
239: # ----------------------------------------------------------- source copyrights
240: {
241: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
242: '/source_copyright.tab';
243: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
244: while (my $line = <$fh>) {
245: next if ($line =~ /^\#/);
246: chomp($line);
247: my ($key,$val)=(split(/\s+/,$line,2));
248: $scprtag{$key}=$val;
249: }
250: close($fh);
251: }
252: }
253:
254: # -------------------------------------------------------------- default domain designs
255: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
256: my $designfile = $designdir.'/default.tab';
257: if ( open (my $fh,'<',$designfile) ) {
258: while (my $line = <$fh>) {
259: next if ($line =~ /^\#/);
260: chomp($line);
261: my ($key,$val)=(split(/\=/,$line));
262: if ($val) { $defaultdesign{$key}=$val; }
263: }
264: close($fh);
265: }
266:
267: # ------------------------------------------------------------- file categories
268: {
269: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
270: '/filecategories.tab';
271: if ( open (my $fh,'<',$categoryfile) ) {
272: while (my $line = <$fh>) {
273: next if ($line =~ /^\#/);
274: chomp($line);
275: my ($extension,$category)=(split(/\s+/,$line,2));
276: push(@{$category_extensions{lc($category)}},$extension);
277: }
278: close($fh);
279: }
280:
281: }
282: # ------------------------------------------------------------------ file types
283: {
284: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
285: '/filetypes.tab';
286: if ( open (my $fh,'<',$typesfile) ) {
287: while (my $line = <$fh>) {
288: next if ($line =~ /^\#/);
289: chomp($line);
290: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
291: if ($descr ne '') {
292: $fe{$ending}=lc($emb);
293: $fd{$ending}=$descr;
294: if ($mime ne 'unk') { $fm{$ending}=$mime; }
295: }
296: }
297: close($fh);
298: }
299: }
300: &Apache::lonnet::logthis(
301: "<span style='color:yellow;'>INFO: Read file types</span>");
302: $readit=1;
303: } # end of unless($readit)
304:
305: }
306:
307: ###############################################################
308: ## HTML and Javascript Helper Functions ##
309: ###############################################################
310:
311: =pod
312:
313: =head1 HTML and Javascript Functions
314:
315: =over 4
316:
317: =item * &browser_and_searcher_javascript()
318:
319: X<browsing, javascript>X<searching, javascript>Returns a string
320: containing javascript with two functions, C<openbrowser> and
321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
322: tags.
323:
324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
325:
326: inputs: formname, elementname, only, omit
327:
328: formname and elementname indicate the name of the html form and name of
329: the element that the results of the browsing selection are to be placed in.
330:
331: Specifying 'only' will restrict the browser to displaying only files
332: with the given extension. Can be a comma separated list.
333:
334: Specifying 'omit' will restrict the browser to NOT displaying files
335: with the given extension. Can be a comma separated list.
336:
337: =item * &opensearcher(formname,elementname) [javascript]
338:
339: Inputs: formname, elementname
340:
341: formname and elementname specify the name of the html form and the name
342: of the element the selection from the search results will be placed in.
343:
344: =cut
345:
346: sub browser_and_searcher_javascript {
347: my ($mode)=@_;
348: if (!defined($mode)) { $mode='edit'; }
349: my $resurl=&escape_single(&lastresurl());
350: return <<END;
351: // <!-- BEGIN LON-CAPA Internal
352: var editbrowser = null;
353: function openbrowser(formname,elementname,only,omit,titleelement) {
354: var url = '$resurl/?';
355: if (editbrowser == null) {
356: url += 'launch=1&';
357: }
358: url += 'catalogmode=interactive&';
359: url += 'mode=$mode&';
360: url += 'inhibitmenu=yes&';
361: url += 'form=' + formname + '&';
362: if (only != null) {
363: url += 'only=' + only + '&';
364: } else {
365: url += 'only=&';
366: }
367: if (omit != null) {
368: url += 'omit=' + omit + '&';
369: } else {
370: url += 'omit=&';
371: }
372: if (titleelement != null) {
373: url += 'titleelement=' + titleelement + '&';
374: } else {
375: url += 'titleelement=&';
376: }
377: url += 'element=' + elementname + '';
378: var title = 'Browser';
379: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
380: options += ',width=700,height=600';
381: editbrowser = open(url,title,options,'1');
382: editbrowser.focus();
383: }
384: var editsearcher;
385: function opensearcher(formname,elementname,titleelement) {
386: var url = '/adm/searchcat?';
387: if (editsearcher == null) {
388: url += 'launch=1&';
389: }
390: url += 'catalogmode=interactive&';
391: url += 'mode=$mode&';
392: url += 'form=' + formname + '&';
393: if (titleelement != null) {
394: url += 'titleelement=' + titleelement + '&';
395: } else {
396: url += 'titleelement=&';
397: }
398: url += 'element=' + elementname + '';
399: var title = 'Search';
400: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
401: options += ',width=700,height=600';
402: editsearcher = open(url,title,options,'1');
403: editsearcher.focus();
404: }
405: // END LON-CAPA Internal -->
406: END
407: }
408:
409: sub lastresurl {
410: if ($env{'environment.lastresurl'}) {
411: return $env{'environment.lastresurl'}
412: } else {
413: return '/res';
414: }
415: }
416:
417: sub storeresurl {
418: my $resurl=&Apache::lonnet::clutter(shift);
419: unless ($resurl=~/^\/res/) { return 0; }
420: $resurl=~s/\/$//;
421: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
422: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
423: return 1;
424: }
425:
426: sub studentbrowser_javascript {
427: unless (
428: (($env{'request.course.id'}) &&
429: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
430: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
431: '/'.$env{'request.course.sec'})
432: ))
433: || ($env{'request.role'}=~/^(au|dc|su)/)
434: ) { return ''; }
435: return (<<'ENDSTDBRW');
436: <script type="text/javascript" language="Javascript">
437: // <![CDATA[
438: var stdeditbrowser;
439: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
440: var url = '/adm/pickstudent?';
441: var filter;
442: if (!ignorefilter) {
443: eval('filter=document.'+formname+'.'+uname+'.value;');
444: }
445: if (filter != null) {
446: if (filter != '') {
447: url += 'filter='+filter+'&';
448: }
449: }
450: url += 'form=' + formname + '&unameelement='+uname+
451: '&udomelement='+udom+
452: '&clicker='+clicker;
453: if (roleflag) { url+="&roles=1"; }
454: if (courseadv == 'condition') {
455: if (document.getElementById('courseadv')) {
456: courseadv = document.getElementById('courseadv').value;
457: }
458: }
459: if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
460: var title = 'Student_Browser';
461: var options = 'scrollbars=1,resizable=1,menubar=0';
462: options += ',width=700,height=600';
463: stdeditbrowser = open(url,title,options,'1');
464: stdeditbrowser.focus();
465: }
466: // ]]>
467: </script>
468: ENDSTDBRW
469: }
470:
471: sub resourcebrowser_javascript {
472: unless ($env{'request.course.id'}) { return ''; }
473: return (<<'ENDRESBRW');
474: <script type="text/javascript" language="Javascript">
475: // <![CDATA[
476: var reseditbrowser;
477: function openresbrowser(formname,reslink) {
478: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
479: var title = 'Resource_Browser';
480: var options = 'scrollbars=1,resizable=1,menubar=0';
481: options += ',width=700,height=500';
482: reseditbrowser = open(url,title,options,'1');
483: reseditbrowser.focus();
484: }
485: // ]]>
486: </script>
487: ENDRESBRW
488: }
489:
490: sub selectstudent_link {
491: my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
492: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
493: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
494: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
495: if ($env{'request.course.id'}) {
496: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
497: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
498: '/'.$env{'request.course.sec'})) {
499: return '';
500: }
501: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
502: if ($courseadv eq 'only') {
503: $callargs .= ",'',1,'$courseadv'";
504: } elsif ($courseadv eq 'none') {
505: $callargs .= ",'','','$courseadv'";
506: } elsif ($courseadv eq 'condition') {
507: $callargs .= ",'','','$courseadv'";
508: }
509: return '<span class="LC_nobreak">'.
510: '<a href="javascript:openstdbrowser('.$callargs.');">'.
511: &mt('Select User').'</a></span>';
512: }
513: if ($env{'request.role'}=~/^(au|dc|su)/) {
514: $callargs .= ",'',1";
515: return '<span class="LC_nobreak">'.
516: '<a href="javascript:openstdbrowser('.$callargs.');">'.
517: &mt('Select User').'</a></span>';
518: }
519: return '';
520: }
521:
522: sub selectresource_link {
523: my ($form,$reslink,$arg)=@_;
524:
525: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
526: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
527: unless ($env{'request.course.id'}) { return $arg; }
528: return '<span class="LC_nobreak">'.
529: '<a href="javascript:openresbrowser('.$callargs.');">'.
530: $arg.'</a></span>';
531: }
532:
533:
534:
535: sub authorbrowser_javascript {
536: return <<"ENDAUTHORBRW";
537: <script type="text/javascript" language="JavaScript">
538: // <![CDATA[
539: var stdeditbrowser;
540:
541: function openauthorbrowser(formname,udom) {
542: var url = '/adm/pickauthor?';
543: url += 'form='+formname+'&roledom='+udom;
544: var title = 'Author_Browser';
545: var options = 'scrollbars=1,resizable=1,menubar=0';
546: options += ',width=700,height=600';
547: stdeditbrowser = open(url,title,options,'1');
548: stdeditbrowser.focus();
549: }
550:
551: // ]]>
552: </script>
553: ENDAUTHORBRW
554: }
555:
556: sub coursebrowser_javascript {
557: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
558: $credits_element,$instcode) = @_;
559: my $wintitle = 'Course_Browser';
560: if ($crstype eq 'Community') {
561: $wintitle = 'Community_Browser';
562: }
563: my $id_functions = &javascript_index_functions();
564: my $output = '
565: <script type="text/javascript" language="JavaScript">
566: // <![CDATA[
567: var stdeditbrowser;'."\n";
568:
569: $output .= <<"ENDSTDBRW";
570: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
571: var url = '/adm/pickcourse?';
572: var formid = getFormIdByName(formname);
573: var domainfilter = getDomainFromSelectbox(formname,udom);
574: if (domainfilter != null) {
575: if (domainfilter != '') {
576: url += 'domainfilter='+domainfilter+'&';
577: }
578: }
579: url += 'form=' + formname + '&cnumelement='+uname+
580: '&cdomelement='+udom+
581: '&cnameelement='+desc;
582: if (extra_element !=null && extra_element != '') {
583: if (formname == 'rolechoice' || formname == 'studentform') {
584: url += '&roleelement='+extra_element;
585: if (domainfilter == null || domainfilter == '') {
586: url += '&domainfilter='+extra_element;
587: }
588: }
589: else {
590: if (formname == 'portform') {
591: url += '&setroles='+extra_element;
592: } else {
593: if (formname == 'rules') {
594: url += '&fixeddom='+extra_element;
595: }
596: }
597: }
598: }
599: if (type != null && type != '') {
600: url += '&type='+type;
601: }
602: if (type_elem != null && type_elem != '') {
603: url += '&typeelement='+type_elem;
604: }
605: if (formname == 'ccrs') {
606: var ownername = document.forms[formid].ccuname.value;
607: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
608: url += '&cloner='+ownername+':'+ownerdom;
609: if (type == 'Course') {
610: url += '&crscode='+document.forms[formid].crscode.value;
611: }
612: }
613: if (formname == 'requestcrs') {
614: url += '&crsdom=$domainfilter&crscode=$instcode';
615: }
616: if (multflag !=null && multflag != '') {
617: url += '&multiple='+multflag;
618: }
619: var title = '$wintitle';
620: var options = 'scrollbars=1,resizable=1,menubar=0';
621: options += ',width=700,height=600';
622: stdeditbrowser = open(url,title,options,'1');
623: stdeditbrowser.focus();
624: }
625: $id_functions
626: ENDSTDBRW
627: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
628: $output .= &setsec_javascript($sec_element,$formname,$role_element,
629: $credits_element);
630: }
631: $output .= '
632: // ]]>
633: </script>';
634: return $output;
635: }
636:
637: sub javascript_index_functions {
638: return <<"ENDJS";
639:
640: function getFormIdByName(formname) {
641: for (var i=0;i<document.forms.length;i++) {
642: if (document.forms[i].name == formname) {
643: return i;
644: }
645: }
646: return -1;
647: }
648:
649: function getIndexByName(formid,item) {
650: for (var i=0;i<document.forms[formid].elements.length;i++) {
651: if (document.forms[formid].elements[i].name == item) {
652: return i;
653: }
654: }
655: return -1;
656: }
657:
658: function getDomainFromSelectbox(formname,udom) {
659: var userdom;
660: var formid = getFormIdByName(formname);
661: if (formid > -1) {
662: var domid = getIndexByName(formid,udom);
663: if (domid > -1) {
664: if (document.forms[formid].elements[domid].type == 'select-one') {
665: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
666: }
667: if (document.forms[formid].elements[domid].type == 'hidden') {
668: userdom=document.forms[formid].elements[domid].value;
669: }
670: }
671: }
672: return userdom;
673: }
674:
675: ENDJS
676:
677: }
678:
679: sub javascript_array_indexof {
680: return <<ENDJS;
681: <script type="text/javascript" language="JavaScript">
682: // <![CDATA[
683:
684: if (!Array.prototype.indexOf) {
685: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
686: "use strict";
687: if (this === void 0 || this === null) {
688: throw new TypeError();
689: }
690: var t = Object(this);
691: var len = t.length >>> 0;
692: if (len === 0) {
693: return -1;
694: }
695: var n = 0;
696: if (arguments.length > 0) {
697: n = Number(arguments[1]);
698: if (n !== n) { // shortcut for verifying if it is NaN
699: n = 0;
700: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
701: n = (n > 0 || -1) * Math.floor(Math.abs(n));
702: }
703: }
704: if (n >= len) {
705: return -1;
706: }
707: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
708: for (; k < len; k++) {
709: if (k in t && t[k] === searchElement) {
710: return k;
711: }
712: }
713: return -1;
714: }
715: }
716:
717: // ]]>
718: </script>
719:
720: ENDJS
721:
722: }
723:
724: sub userbrowser_javascript {
725: my $id_functions = &javascript_index_functions();
726: return <<"ENDUSERBRW";
727:
728: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
729: var url = '/adm/pickuser?';
730: var userdom = getDomainFromSelectbox(formname,udom);
731: if (userdom != null) {
732: if (userdom != '') {
733: url += 'srchdom='+userdom+'&';
734: }
735: }
736: url += 'form=' + formname + '&unameelement='+uname+
737: '&udomelement='+udom+
738: '&ulastelement='+ulast+
739: '&ufirstelement='+ufirst+
740: '&uemailelement='+uemail+
741: '&hideudomelement='+hideudom+
742: '&coursedom='+crsdom;
743: if ((caller != null) && (caller != undefined)) {
744: url += '&caller='+caller;
745: }
746: var title = 'User_Browser';
747: var options = 'scrollbars=1,resizable=1,menubar=0';
748: options += ',width=700,height=600';
749: var stdeditbrowser = open(url,title,options,'1');
750: stdeditbrowser.focus();
751: }
752:
753: function fix_domain (formname,udom,origdom,uname) {
754: var formid = getFormIdByName(formname);
755: if (formid > -1) {
756: var unameid = getIndexByName(formid,uname);
757: var domid = getIndexByName(formid,udom);
758: var hidedomid = getIndexByName(formid,origdom);
759: if (hidedomid > -1) {
760: var fixeddom = document.forms[formid].elements[hidedomid].value;
761: var unameval = document.forms[formid].elements[unameid].value;
762: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
763: if (domid > -1) {
764: var slct = document.forms[formid].elements[domid];
765: if (slct.type == 'select-one') {
766: var i;
767: for (i=0;i<slct.length;i++) {
768: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
769: }
770: }
771: if (slct.type == 'hidden') {
772: slct.value = fixeddom;
773: }
774: }
775: }
776: }
777: }
778: return;
779: }
780:
781: $id_functions
782: ENDUSERBRW
783: }
784:
785: sub setsec_javascript {
786: my ($sec_element,$formname,$role_element,$credits_element) = @_;
787: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
788: $communityrolestr);
789: if ($role_element ne '') {
790: my @allroles = ('st','ta','ep','in','ad');
791: foreach my $crstype ('Course','Community') {
792: if ($crstype eq 'Community') {
793: foreach my $role (@allroles) {
794: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
795: }
796: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
797: } else {
798: foreach my $role (@allroles) {
799: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
800: }
801: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
802: }
803: }
804: $rolestr = '"'.join('","',@allroles).'"';
805: $courserolestr = '"'.join('","',@courserolenames).'"';
806: $communityrolestr = '"'.join('","',@communityrolenames).'"';
807: }
808: my $setsections = qq|
809: function setSect(sectionlist) {
810: var sectionsArray = new Array();
811: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
812: sectionsArray = sectionlist.split(",");
813: }
814: var numSections = sectionsArray.length;
815: document.$formname.$sec_element.length = 0;
816: if (numSections == 0) {
817: document.$formname.$sec_element.multiple=false;
818: document.$formname.$sec_element.size=1;
819: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
820: } else {
821: if (numSections == 1) {
822: document.$formname.$sec_element.multiple=false;
823: document.$formname.$sec_element.size=1;
824: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
825: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
826: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
827: } else {
828: for (var i=0; i<numSections; i++) {
829: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
830: }
831: document.$formname.$sec_element.multiple=true
832: if (numSections < 3) {
833: document.$formname.$sec_element.size=numSections;
834: } else {
835: document.$formname.$sec_element.size=3;
836: }
837: document.$formname.$sec_element.options[0].selected = false
838: }
839: }
840: }
841:
842: function setRole(crstype) {
843: |;
844: if ($role_element eq '') {
845: $setsections .= ' return;
846: }
847: ';
848: } else {
849: $setsections .= qq|
850: var elementLength = document.$formname.$role_element.length;
851: var allroles = Array($rolestr);
852: var courserolenames = Array($courserolestr);
853: var communityrolenames = Array($communityrolestr);
854: if (elementLength != undefined) {
855: if (document.$formname.$role_element.options[5].value == 'cc') {
856: if (crstype == 'Course') {
857: return;
858: } else {
859: allroles[5] = 'co';
860: for (var i=0; i<6; i++) {
861: document.$formname.$role_element.options[i].value = allroles[i];
862: document.$formname.$role_element.options[i].text = communityrolenames[i];
863: }
864: }
865: } else {
866: if (crstype == 'Community') {
867: return;
868: } else {
869: allroles[5] = 'cc';
870: for (var i=0; i<6; i++) {
871: document.$formname.$role_element.options[i].value = allroles[i];
872: document.$formname.$role_element.options[i].text = courserolenames[i];
873: }
874: }
875: }
876: }
877: return;
878: }
879: |;
880: }
881: if ($credits_element) {
882: $setsections .= qq|
883: function setCredits(defaultcredits) {
884: document.$formname.$credits_element.value = defaultcredits;
885: return;
886: }
887: |;
888: }
889: return $setsections;
890: }
891:
892: sub selectcourse_link {
893: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
894: $typeelement) = @_;
895: my $type = $selecttype;
896: my $linktext = &mt('Select Course');
897: if ($selecttype eq 'Community') {
898: $linktext = &mt('Select Community');
899: } elsif ($selecttype eq 'Placement') {
900: $linktext = &mt('Select Placement Test');
901: } elsif ($selecttype eq 'Course/Community') {
902: $linktext = &mt('Select Course/Community');
903: $type = '';
904: } elsif ($selecttype eq 'Select') {
905: $linktext = &mt('Select');
906: $type = '';
907: }
908: return '<span class="LC_nobreak">'
909: ."<a href='"
910: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
911: .'","'.$udomele.'","'.$desc.'","'.$extra_element
912: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
913: ."'>".$linktext.'</a>'
914: .'</span>';
915: }
916:
917: sub selectauthor_link {
918: my ($form,$udom)=@_;
919: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
920: &mt('Select Author').'</a>';
921: }
922:
923: sub selectuser_link {
924: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
925: $coursedom,$linktext,$caller) = @_;
926: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
927: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
928: ');">'.$linktext.'</a>';
929: }
930:
931: sub check_uncheck_jscript {
932: my $jscript = <<"ENDSCRT";
933: function checkAll(field) {
934: if (field.length > 0) {
935: for (i = 0; i < field.length; i++) {
936: if (!field[i].disabled) {
937: field[i].checked = true;
938: }
939: }
940: } else {
941: if (!field.disabled) {
942: field.checked = true;
943: }
944: }
945: }
946:
947: function uncheckAll(field) {
948: if (field.length > 0) {
949: for (i = 0; i < field.length; i++) {
950: field[i].checked = false ;
951: }
952: } else {
953: field.checked = false ;
954: }
955: }
956: ENDSCRT
957: return $jscript;
958: }
959:
960: sub select_timezone {
961: my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
962: my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
963: if ($includeempty) {
964: $output .= '<option value=""';
965: if (($selected eq '') || ($selected eq 'local')) {
966: $output .= ' selected="selected" ';
967: }
968: $output .= '> </option>';
969: }
970: my @timezones = DateTime::TimeZone->all_names;
971: foreach my $tzone (@timezones) {
972: $output.= '<option value="'.$tzone.'"';
973: if ($tzone eq $selected) {
974: $output.=' selected="selected"';
975: }
976: $output.=">$tzone</option>\n";
977: }
978: $output.="</select>";
979: return $output;
980: }
981:
982: sub select_datelocale {
983: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
984: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
985: if ($includeempty) {
986: $output .= '<option value=""';
987: if ($selected eq '') {
988: $output .= ' selected="selected" ';
989: }
990: $output .= '> </option>';
991: }
992: my @languages = &Apache::lonlocal::preferred_languages();
993: my (@possibles,%locale_names);
994: my @locales = DateTime::Locale->ids();
995: foreach my $id (@locales) {
996: if ($id ne '') {
997: my ($en_terr,$native_terr);
998: my $loc = DateTime::Locale->load($id);
999: if (ref($loc)) {
1000: $en_terr = $loc->name();
1001: $native_terr = $loc->native_name();
1002: if (grep(/^en$/,@languages) || !@languages) {
1003: if ($en_terr ne '') {
1004: $locale_names{$id} = '('.$en_terr.')';
1005: } elsif ($native_terr ne '') {
1006: $locale_names{$id} = $native_terr;
1007: }
1008: } else {
1009: if ($native_terr ne '') {
1010: $locale_names{$id} = $native_terr.' ';
1011: } elsif ($en_terr ne '') {
1012: $locale_names{$id} = '('.$en_terr.')';
1013: }
1014: }
1015: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1016: push(@possibles,$id);
1017: }
1018: }
1019: }
1020: foreach my $item (sort(@possibles)) {
1021: $output.= '<option value="'.$item.'"';
1022: if ($item eq $selected) {
1023: $output.=' selected="selected"';
1024: }
1025: $output.=">$item";
1026: if ($locale_names{$item} ne '') {
1027: $output.=' '.$locale_names{$item};
1028: }
1029: $output.="</option>\n";
1030: }
1031: $output.="</select>";
1032: return $output;
1033: }
1034:
1035: sub select_language {
1036: my ($name,$selected,$includeempty,$noedit) = @_;
1037: my %langchoices;
1038: if ($includeempty) {
1039: %langchoices = ('' => 'No language preference');
1040: }
1041: foreach my $id (&languageids()) {
1042: my $code = &supportedlanguagecode($id);
1043: if ($code) {
1044: $langchoices{$code} = &plainlanguagedescription($id);
1045: }
1046: }
1047: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1048: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1049: }
1050:
1051: =pod
1052:
1053:
1054: =item * &list_languages()
1055:
1056: Returns an array reference that is suitable for use in language prompters.
1057: Each array element is itself a two element array. The first element
1058: is the language code. The second element a descsriptiuon of the
1059: language itself. This is suitable for use in e.g.
1060: &Apache::edit::select_arg (once dereferenced that is).
1061:
1062: =cut
1063:
1064: sub list_languages {
1065: my @lang_choices;
1066:
1067: foreach my $id (&languageids()) {
1068: my $code = &supportedlanguagecode($id);
1069: if ($code) {
1070: my $selector = $supported_codes{$id};
1071: my $description = &plainlanguagedescription($id);
1072: push(@lang_choices, [$selector, $description]);
1073: }
1074: }
1075: return \@lang_choices;
1076: }
1077:
1078: =pod
1079:
1080: =item * &linked_select_forms(...)
1081:
1082: linked_select_forms returns a string containing a <script></script> block
1083: and html for two <select> menus. The select menus will be linked in that
1084: changing the value of the first menu will result in new values being placed
1085: in the second menu. The values in the select menu will appear in alphabetical
1086: order unless a defined order is provided.
1087:
1088: linked_select_forms takes the following ordered inputs:
1089:
1090: =over 4
1091:
1092: =item * $formname, the name of the <form> tag
1093:
1094: =item * $middletext, the text which appears between the <select> tags
1095:
1096: =item * $firstdefault, the default value for the first menu
1097:
1098: =item * $firstselectname, the name of the first <select> tag
1099:
1100: =item * $secondselectname, the name of the second <select> tag
1101:
1102: =item * $hashref, a reference to a hash containing the data for the menus.
1103:
1104: =item * $menuorder, the order of values in the first menu
1105:
1106: =item * $onchangefirst, additional javascript call to execute for an onchange
1107: event for the first <select> tag
1108:
1109: =item * $onchangesecond, additional javascript call to execute for an onchange
1110: event for the second <select> tag
1111:
1112: =item * $suffix, to differentiate separate uses of select2data javascript
1113: objects in a page.
1114:
1115: =back
1116:
1117: Below is an example of such a hash. Only the 'text', 'default', and
1118: 'select2' keys must appear as stated. keys(%menu) are the possible
1119: values for the first select menu. The text that coincides with the
1120: first menu value is given in $menu{$choice1}->{'text'}. The values
1121: and text for the second menu are given in the hash pointed to by
1122: $menu{$choice1}->{'select2'}.
1123:
1124: my %menu = ( A1 => { text =>"Choice A1" ,
1125: default => "B3",
1126: select2 => {
1127: B1 => "Choice B1",
1128: B2 => "Choice B2",
1129: B3 => "Choice B3",
1130: B4 => "Choice B4"
1131: },
1132: order => ['B4','B3','B1','B2'],
1133: },
1134: A2 => { text =>"Choice A2" ,
1135: default => "C2",
1136: select2 => {
1137: C1 => "Choice C1",
1138: C2 => "Choice C2",
1139: C3 => "Choice C3"
1140: },
1141: order => ['C2','C1','C3'],
1142: },
1143: A3 => { text =>"Choice A3" ,
1144: default => "D6",
1145: select2 => {
1146: D1 => "Choice D1",
1147: D2 => "Choice D2",
1148: D3 => "Choice D3",
1149: D4 => "Choice D4",
1150: D5 => "Choice D5",
1151: D6 => "Choice D6",
1152: D7 => "Choice D7"
1153: },
1154: order => ['D4','D3','D2','D1','D7','D6','D5'],
1155: }
1156: );
1157:
1158: =cut
1159:
1160: sub linked_select_forms {
1161: my ($formname,
1162: $middletext,
1163: $firstdefault,
1164: $firstselectname,
1165: $secondselectname,
1166: $hashref,
1167: $menuorder,
1168: $onchangefirst,
1169: $onchangesecond,
1170: $suffix
1171: ) = @_;
1172: my $second = "document.$formname.$secondselectname";
1173: my $first = "document.$formname.$firstselectname";
1174: # output the javascript to do the changing
1175: my $result = '';
1176: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1177: $result.="// <![CDATA[\n";
1178: $result.="var select2data${suffix} = new Object();\n";
1179: $" = '","';
1180: my $debug = '';
1181: foreach my $s1 (sort(keys(%$hashref))) {
1182: $result.="select2data${suffix}['d_$s1'] = new Object();\n";
1183: $result.="select2data${suffix}['d_$s1'].def = new String('".
1184: $hashref->{$s1}->{'default'}."');\n";
1185: $result.="select2data${suffix}['d_$s1'].values = new Array(";
1186: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1187: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1188: @s2values = @{$hashref->{$s1}->{'order'}};
1189: }
1190: $result.="\"@s2values\");\n";
1191: $result.="select2data${suffix}['d_$s1'].texts = new Array(";
1192: my @s2texts;
1193: foreach my $value (@s2values) {
1194: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1195: }
1196: $result.="\"@s2texts\");\n";
1197: }
1198: $"=' ';
1199: $result.= <<"END";
1200:
1201: function select1${suffix}_changed() {
1202: // Determine new choice
1203: var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1204: // update select2
1205: var values = select2data${suffix}[newvalue].values;
1206: var texts = select2data${suffix}[newvalue].texts;
1207: var select2def = select2data${suffix}[newvalue].def;
1208: var i;
1209: // out with the old
1210: $second.options.length = 0;
1211: // in with the new
1212: for (i=0;i<values.length; i++) {
1213: $second.options[i] = new Option(values[i]);
1214: $second.options[i].value = values[i];
1215: $second.options[i].text = texts[i];
1216: if (values[i] == select2def) {
1217: $second.options[i].selected = true;
1218: }
1219: }
1220: }
1221: // ]]>
1222: </script>
1223: END
1224: # output the initial values for the selection lists
1225: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1226: my @order = sort(keys(%{$hashref}));
1227: if (ref($menuorder) eq 'ARRAY') {
1228: @order = @{$menuorder};
1229: }
1230: foreach my $value (@order) {
1231: $result.=" <option value=\"$value\" ";
1232: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1233: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1234: }
1235: $result .= "</select>\n";
1236: my %select2;
1237: if (ref($hashref->{$firstdefault}) eq 'HASH') {
1238: if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
1239: %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1240: }
1241: }
1242: $result .= $middletext;
1243: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1244: if ($onchangesecond) {
1245: $result .= ' onchange="'.$onchangesecond.'"';
1246: }
1247: $result .= ">\n";
1248: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1249:
1250: my @secondorder = sort(keys(%select2));
1251: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1252: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1253: }
1254: foreach my $value (@secondorder) {
1255: $result.=" <option value=\"$value\" ";
1256: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1257: $result.=">".&mt($select2{$value})."</option>\n";
1258: }
1259: $result .= "</select>\n";
1260: # return $debug;
1261: return $result;
1262: } # end of sub linked_select_forms {
1263:
1264: =pod
1265:
1266: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1267:
1268: Returns a string corresponding to an HTML link to the given help
1269: $topic, where $topic corresponds to the name of a .tex file in
1270: /home/httpd/html/adm/help/tex, with underscores replaced by
1271: spaces.
1272:
1273: $text will optionally be linked to the same topic, allowing you to
1274: link text in addition to the graphic. If you do not want to link
1275: text, but wish to specify one of the later parameters, pass an
1276: empty string.
1277:
1278: $stayOnPage is a value that will be interpreted as a boolean. If true,
1279: the link will not open a new window. If false, the link will open
1280: a new window using Javascript. (Default is false.)
1281:
1282: $width and $height are optional numerical parameters that will
1283: override the width and height of the popped up window, which may
1284: be useful for certain help topics with big pictures included.
1285:
1286: $imgid is the id of the img tag used for the help icon. This may be
1287: used in a javascript call to switch the image src. See
1288: lonhtmlcommon::htmlareaselectactive() for an example.
1289:
1290: $links_target will optionally be set to a target (_top, _parent or _self).
1291:
1292: =cut
1293:
1294: sub help_open_topic {
1295: my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1296: $text = "" if (not defined $text);
1297: $stayOnPage = 0 if (not defined $stayOnPage);
1298: $width = 500 if (not defined $width);
1299: $height = 400 if (not defined $height);
1300: my $filename = $topic;
1301: $filename =~ s/ /_/g;
1302:
1303: my $template = "";
1304: my $link;
1305:
1306: $topic=~s/\W/\_/g;
1307:
1308: if (!$stayOnPage) {
1309: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1310: } elsif ($stayOnPage eq 'popup') {
1311: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1312: } else {
1313: $link = "/adm/help/${filename}.hlp";
1314: }
1315:
1316: # Add the text
1317: my $target = ' target="_top"';
1318: if ($links_target) {
1319: $target = ' target="'.$links_target.'"';
1320: } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1321: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1322: $target = '';
1323: }
1324: if ($text ne "") {
1325: $template.='<span class="LC_help_open_topic">'
1326: .'<a'.$target.' href="'.$link.'">'
1327: .$text.'</a>';
1328: }
1329:
1330: # (Always) Add the graphic
1331: my $title = &mt('Online Help');
1332: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1333: if ($imgid ne '') {
1334: $imgid = ' id="'.$imgid.'"';
1335: }
1336: $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1337: .'<img src="'.$helpicon.'" border="0"'
1338: .' alt="'.&mt('Help: [_1]',$topic).'"'
1339: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1340: .' /></a>';
1341: if ($text ne "") {
1342: $template.='</span>';
1343: }
1344: return $template;
1345:
1346: }
1347:
1348: # This is a quicky function for Latex cheatsheet editing, since it
1349: # appears in at least four places
1350: sub helpLatexCheatsheet {
1351: my ($topic,$text,$not_author,$stayOnPage) = @_;
1352: my $out;
1353: my $addOther = '';
1354: if ($topic) {
1355: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1356: }
1357: $out = '<span>' # Start cheatsheet
1358: .$addOther
1359: .'<span>'
1360: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1361: .'</span> <span>'
1362: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1363: .'</span>';
1364: unless ($not_author) {
1365: $out .= '<span>'
1366: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1367: .'</span> <span>'
1368: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1369: .'</span>';
1370: }
1371: $out .= '</span>'; # End cheatsheet
1372: return $out;
1373: }
1374:
1375: sub general_help {
1376: my $helptopic='Student_Intro';
1377: if ($env{'request.role'}=~/^(ca|au)/) {
1378: $helptopic='Authoring_Intro';
1379: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1380: $helptopic='Course_Coordination_Intro';
1381: } elsif ($env{'request.role'}=~/^dc/) {
1382: $helptopic='Domain_Coordination_Intro';
1383: }
1384: return $helptopic;
1385: }
1386:
1387: sub update_help_link {
1388: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1389: my $origurl = $ENV{'REQUEST_URI'};
1390: $origurl=~s|^/~|/priv/|;
1391: my $timestamp = time;
1392: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1393: $$datum = &escape($$datum);
1394: }
1395:
1396: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1397: my $output .= <<"ENDOUTPUT";
1398: <script type="text/javascript">
1399: // <![CDATA[
1400: banner_link = '$banner_link';
1401: // ]]>
1402: </script>
1403: ENDOUTPUT
1404: return $output;
1405: }
1406:
1407: # now just updates the help link and generates a blue icon
1408: sub help_open_menu {
1409: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target)
1410: = @_;
1411: $stayOnPage = 1;
1412: my $output;
1413: if ($component_help) {
1414: if (!$text) {
1415: $output=&help_open_topic($component_help,undef,$stayOnPage,
1416: $width,$height,'',$links_target);
1417: } else {
1418: my $help_text;
1419: $help_text=&unescape($topic);
1420: $output='<table><tr><td>'.
1421: &help_open_topic($component_help,$help_text,$stayOnPage,
1422: $width,$height,'',$links_target).'</td></tr></table>';
1423: }
1424: }
1425: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1426: return $output.$banner_link;
1427: }
1428:
1429: sub top_nav_help {
1430: my ($text,$linkattr) = @_;
1431: $text = &mt($text);
1432: my $stay_on_page = 1;
1433:
1434: my ($link,$banner_link);
1435: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1436: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1437: : "javascript:helpMenu('open')";
1438: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1439: }
1440: my $title = &mt('Get help');
1441: if ($link) {
1442: return <<"END";
1443: $banner_link
1444: <a href="$link" title="$title" $linkattr>$text</a>
1445: END
1446: } else {
1447: return ' '.$text.' ';
1448: }
1449: }
1450:
1451: sub help_menu_js {
1452: my ($httphost) = @_;
1453: my $stayOnPage = 1;
1454: my $width = 620;
1455: my $height = 600;
1456: my $helptopic=&general_help();
1457: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1458: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1459: my $start_page =
1460: &Apache::loncommon::start_page('Help Menu', undef,
1461: {'frameset' => 1,
1462: 'js_ready' => 1,
1463: 'use_absolute' => $httphost,
1464: 'add_entries' => {
1465: 'border' => '0',
1466: 'rows' => "110,*",},});
1467: my $end_page =
1468: &Apache::loncommon::end_page({'frameset' => 1,
1469: 'js_ready' => 1,});
1470:
1471: my $template .= <<"ENDTEMPLATE";
1472: <script type="text/javascript">
1473: // <![CDATA[
1474: // <!-- BEGIN LON-CAPA Internal
1475: var banner_link = '';
1476: function helpMenu(target) {
1477: var caller = this;
1478: if (target == 'open') {
1479: var newWindow = null;
1480: try {
1481: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1482: }
1483: catch(error) {
1484: writeHelp(caller);
1485: return;
1486: }
1487: if (newWindow) {
1488: caller = newWindow;
1489: }
1490: }
1491: writeHelp(caller);
1492: return;
1493: }
1494: function writeHelp(caller) {
1495: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1496: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1497: caller.document.close();
1498: caller.focus();
1499: }
1500: // END LON-CAPA Internal -->
1501: // ]]>
1502: </script>
1503: ENDTEMPLATE
1504: return $template;
1505: }
1506:
1507: sub help_open_bug {
1508: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1509: unless ($env{'user.adv'}) { return ''; }
1510: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1511: $text = "" if (not defined $text);
1512: $stayOnPage=1;
1513: $width = 600 if (not defined $width);
1514: $height = 600 if (not defined $height);
1515:
1516: $topic=~s/\W+/\+/g;
1517: my $link='';
1518: my $template='';
1519: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1520: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1521: if (!$stayOnPage)
1522: {
1523: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1524: }
1525: else
1526: {
1527: $link = $url;
1528: }
1529:
1530: my $target = '_top';
1531: if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1532: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1533: $target = '_blank';
1534: }
1535:
1536: # Add the text
1537: if ($text ne "")
1538: {
1539: $template .=
1540: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1541: "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1542: }
1543:
1544: # Add the graphic
1545: my $title = &mt('Report a Bug');
1546: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1547: $template .= <<"ENDTEMPLATE";
1548: <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1549: ENDTEMPLATE
1550: if ($text ne '') { $template.='</td></tr></table>' };
1551: return $template;
1552:
1553: }
1554:
1555: sub help_open_faq {
1556: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1557: unless ($env{'user.adv'}) { return ''; }
1558: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1559: $text = "" if (not defined $text);
1560: $stayOnPage=1;
1561: $width = 350 if (not defined $width);
1562: $height = 400 if (not defined $height);
1563:
1564: $topic=~s/\W+/\+/g;
1565: my $link='';
1566: my $template='';
1567: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1568: if (!$stayOnPage)
1569: {
1570: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1571: }
1572: else
1573: {
1574: $link = $url;
1575: }
1576:
1577: # Add the text
1578: if ($text ne "")
1579: {
1580: $template .=
1581: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1582: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1583: }
1584:
1585: # Add the graphic
1586: my $title = &mt('View the FAQ');
1587: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1588: $template .= <<"ENDTEMPLATE";
1589: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1590: ENDTEMPLATE
1591: if ($text ne '') { $template.='</td></tr></table>' };
1592: return $template;
1593:
1594: }
1595:
1596: ###############################################################
1597: ###############################################################
1598:
1599: =pod
1600:
1601: =item * &change_content_javascript():
1602:
1603: This and the next function allow you to create small sections of an
1604: otherwise static HTML page that you can update on the fly with
1605: Javascript, even in Netscape 4.
1606:
1607: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1608: must be written to the HTML page once. It will prove the Javascript
1609: function "change(name, content)". Calling the change function with the
1610: name of the section
1611: you want to update, matching the name passed to C<changable_area>, and
1612: the new content you want to put in there, will put the content into
1613: that area.
1614:
1615: B<Note>: Netscape 4 only reserves enough space for the changable area
1616: to contain room for the original contents. You need to "make space"
1617: for whatever changes you wish to make, and be B<sure> to check your
1618: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1619: it's adequate for updating a one-line status display, but little more.
1620: This script will set the space to 100% width, so you only need to
1621: worry about height in Netscape 4.
1622:
1623: Modern browsers are much less limiting, and if you can commit to the
1624: user not using Netscape 4, this feature may be used freely with
1625: pretty much any HTML.
1626:
1627: =cut
1628:
1629: sub change_content_javascript {
1630: # If we're on Netscape 4, we need to use Layer-based code
1631: if ($env{'browser.type'} eq 'netscape' &&
1632: $env{'browser.version'} =~ /^4\./) {
1633: return (<<NETSCAPE4);
1634: function change(name, content) {
1635: doc = document.layers[name+"___escape"].layers[0].document;
1636: doc.open();
1637: doc.write(content);
1638: doc.close();
1639: }
1640: NETSCAPE4
1641: } else {
1642: # Otherwise, we need to use semi-standards-compliant code
1643: # (technically, "innerHTML" isn't standard but the equivalent
1644: # is really scary, and every useful browser supports it
1645: return (<<DOMBASED);
1646: function change(name, content) {
1647: element = document.getElementById(name);
1648: element.innerHTML = content;
1649: }
1650: DOMBASED
1651: }
1652: }
1653:
1654: =pod
1655:
1656: =item * &changable_area($name,$origContent):
1657:
1658: This provides a "changable area" that can be modified on the fly via
1659: the Javascript code provided in C<change_content_javascript>. $name is
1660: the name you will use to reference the area later; do not repeat the
1661: same name on a given HTML page more then once. $origContent is what
1662: the area will originally contain, which can be left blank.
1663:
1664: =cut
1665:
1666: sub changable_area {
1667: my ($name, $origContent) = @_;
1668:
1669: if ($env{'browser.type'} eq 'netscape' &&
1670: $env{'browser.version'} =~ /^4\./) {
1671: # If this is netscape 4, we need to use the Layer tag
1672: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1673: } else {
1674: return "<span id='$name'>$origContent</span>";
1675: }
1676: }
1677:
1678: =pod
1679:
1680: =item * &viewport_geometry_js
1681:
1682: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1683:
1684: =cut
1685:
1686:
1687: sub viewport_geometry_js {
1688: return <<"GEOMETRY";
1689: var Geometry = {};
1690: function init_geometry() {
1691: if (Geometry.init) { return };
1692: Geometry.init=1;
1693: if (window.innerHeight) {
1694: Geometry.getViewportHeight = function() { return window.innerHeight; };
1695: Geometry.getViewportWidth = function() { return window.innerWidth; };
1696: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1697: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1698: }
1699: else if (document.documentElement && document.documentElement.clientHeight) {
1700: Geometry.getViewportHeight =
1701: function() { return document.documentElement.clientHeight; };
1702: Geometry.getViewportWidth =
1703: function() { return document.documentElement.clientWidth; };
1704:
1705: Geometry.getHorizontalScroll =
1706: function() { return document.documentElement.scrollLeft; };
1707: Geometry.getVerticalScroll =
1708: function() { return document.documentElement.scrollTop; };
1709: }
1710: else if (document.body.clientHeight) {
1711: Geometry.getViewportHeight =
1712: function() { return document.body.clientHeight; };
1713: Geometry.getViewportWidth =
1714: function() { return document.body.clientWidth; };
1715: Geometry.getHorizontalScroll =
1716: function() { return document.body.scrollLeft; };
1717: Geometry.getVerticalScroll =
1718: function() { return document.body.scrollTop; };
1719: }
1720: }
1721:
1722: GEOMETRY
1723: }
1724:
1725: =pod
1726:
1727: =item * &viewport_size_js()
1728:
1729: 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.
1730:
1731: =cut
1732:
1733: sub viewport_size_js {
1734: my $geometry = &viewport_geometry_js();
1735: return <<"DIMS";
1736:
1737: $geometry
1738:
1739: function getViewportDims(width,height) {
1740: init_geometry();
1741: width.value = Geometry.getViewportWidth();
1742: height.value = Geometry.getViewportHeight();
1743: return;
1744: }
1745:
1746: DIMS
1747: }
1748:
1749: =pod
1750:
1751: =item * &resize_textarea_js()
1752:
1753: emits the needed javascript to resize a textarea to be as big as possible
1754:
1755: creates a function resize_textrea that takes two IDs first should be
1756: the id of the element to resize, second should be the id of a div that
1757: surrounds everything that comes after the textarea, this routine needs
1758: to be attached to the <body> for the onload and onresize events.
1759:
1760: =back
1761:
1762: =cut
1763:
1764: sub resize_textarea_js {
1765: my $geometry = &viewport_geometry_js();
1766: return <<"RESIZE";
1767: <script type="text/javascript">
1768: // <![CDATA[
1769: $geometry
1770:
1771: function getX(element) {
1772: var x = 0;
1773: while (element) {
1774: x += element.offsetLeft;
1775: element = element.offsetParent;
1776: }
1777: return x;
1778: }
1779: function getY(element) {
1780: var y = 0;
1781: while (element) {
1782: y += element.offsetTop;
1783: element = element.offsetParent;
1784: }
1785: return y;
1786: }
1787:
1788:
1789: function resize_textarea(textarea_id,bottom_id) {
1790: init_geometry();
1791: var textarea = document.getElementById(textarea_id);
1792: //alert(textarea);
1793:
1794: var textarea_top = getY(textarea);
1795: var textarea_height = textarea.offsetHeight;
1796: var bottom = document.getElementById(bottom_id);
1797: var bottom_top = getY(bottom);
1798: var bottom_height = bottom.offsetHeight;
1799: var window_height = Geometry.getViewportHeight();
1800: var fudge = 23;
1801: var new_height = window_height-fudge-textarea_top-bottom_height;
1802: if (new_height < 300) {
1803: new_height = 300;
1804: }
1805: textarea.style.height=new_height+'px';
1806: }
1807: // ]]>
1808: </script>
1809: RESIZE
1810:
1811: }
1812:
1813: sub colorfuleditor_js {
1814: my $browse_or_search;
1815: my $respath;
1816: my ($cnum,$cdom) = &crsauthor_url();
1817: if ($cnum) {
1818: $respath = "/res/$cdom/$cnum/";
1819: my %js_lt = &Apache::lonlocal::texthash(
1820: sunm => 'Sub-directory name',
1821: save => 'Save page to make this permanent',
1822: );
1823: &js_escape(\%js_lt);
1824: my $showfile_js = &show_crsfiles_js();
1825: $browse_or_search = <<"END";
1826:
1827: $showfile_js
1828:
1829: function toggleChooser(form,element,titleid,only,search) {
1830: var disp = 'none';
1831: if (document.getElementById('chooser_'+element)) {
1832: var curr = document.getElementById('chooser_'+element).style.display;
1833: if (curr == 'none') {
1834: disp='inline';
1835: if (form.elements['chooser_'+element].length) {
1836: for (var i=0; i<form.elements['chooser_'+element].length; i++) {
1837: form.elements['chooser_'+element][i].checked = false;
1838: }
1839: }
1840: toggleResImport(form,element);
1841: }
1842: document.getElementById('chooser_'+element).style.display = disp;
1843: var dirsel = '';
1844: var filesel = '';
1845: if (document.getElementById('chooser_'+element+'_crsres')) {
1846: var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
1847: if (currcrsres == 'none') {
1848: dirsel = 'coursepath_'+element;
1849: var filesel = 'coursefile_'+element;
1850: var include;
1851: if (document.getElementById('crsres_include_'+element)) {
1852: include = document.getElementById('crsres_include_'+element).value;
1853: }
1854: populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1855: }
1856: }
1857: if (document.getElementById('chooser_'+element+'_upload')) {
1858: var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
1859: if (currcrsupload == 'none') {
1860: dirsel = 'crsauthorpath_'+element;
1861: filesel = '';
1862: populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1863: }
1864: }
1865: }
1866: }
1867:
1868: function toggleCrsFile(form,element) {
1869: if (document.getElementById('chooser_'+element+'_crsres')) {
1870: var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
1871: if (curr == 'none') {
1872: if (document.getElementById('coursepath_'+element)) {
1873: var numdirs;
1874: if (document.getElementById('coursepath_'+element).length) {
1875: numdirs = document.getElementById('coursepath_'+element).length;
1876: }
1877: if ((document.getElementById('hascrsres_'+element)) &&
1878: (document.getElementById('nocrsres_'+element))) {
1879: if (numdirs) {
1880: document.getElementById('hascrsres_'+element).style.display='inline-block';
1881: document.getElementById('nocrsres_'+element).style.display='none';
1882: } else {
1883: document.getElementById('hascrsres_'+element).style.display='none';
1884: document.getElementById('nocrsres_'+element).style.display='inline-block';
1885: }
1886: }
1887: form.elements['coursepath_'+element].selectedIndex = 0;
1888: if (numdirs > 1) {
1889: var selelem = form.elements['coursefile_'+element];
1890: var i, len = selelem.options.length -1;
1891: if (len >=0) {
1892: for (i = len; i >= 0; i--) {
1893: selelem.remove(i);
1894: }
1895: selelem.options[0] = new Option('','');
1896: }
1897: }
1898: }
1899: }
1900: document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
1901: }
1902: if (document.getElementById('chooser_'+element+'_upload')) {
1903: document.getElementById('chooser_'+element+'_upload').style.display = 'none';
1904: if (document.getElementById('uploadcrsres_'+element)) {
1905: document.getElementById('uploadcrsres_'+element).value = '';
1906: }
1907: }
1908: return;
1909: }
1910:
1911: function toggleCrsUpload(form,element) {
1912: if (document.getElementById('chooser_'+element+'_crsres')) {
1913: document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
1914: }
1915: if (document.getElementById('chooser_'+element+'_upload')) {
1916: var curr = document.getElementById('chooser_'+element+'_upload').style.display;
1917: if (curr == 'none') {
1918: form.elements['newsubdir_'+element][0].checked = true;
1919: toggleNewsubdir(form,element);
1920: document.getElementById('chooser_'+element+'_upload').style.display = 'block';
1921: if (document.getElementById('uploadcrsres_'+element)) {
1922: document.getElementById('uploadcrsres_'+element).value = '';
1923: }
1924: }
1925: }
1926: return;
1927: }
1928:
1929: function toggleResImport(form,element) {
1930: var choices = new Array('crsres','upload');
1931: for (var i=0; i<choices.length; i++) {
1932: if (document.getElementById('chooser_'+element+'_'+choices[i])) {
1933: document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
1934: }
1935: }
1936: }
1937:
1938: function toggleNewsubdir(form,element) {
1939: var newsub = form.elements['newsubdir_'+element];
1940: if (newsub) {
1941: if (newsub.length) {
1942: for (var j=0; j<newsub.length; j++) {
1943: if (newsub[j].checked) {
1944: if (document.getElementById('newsubdirname_'+element)) {
1945: if (newsub[j].value == '1') {
1946: document.getElementById('newsubdirname_'+element).type = "text";
1947: if (document.getElementById('newsubdir_'+element)) {
1948: document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
1949: }
1950: } else {
1951: document.getElementById('newsubdirname_'+element).type = "hidden";
1952: document.getElementById('newsubdirname_'+element).value = "";
1953: document.getElementById('newsubdir_'+element).innerHTML = "";
1954: }
1955: }
1956: break;
1957: }
1958: }
1959: }
1960: }
1961: }
1962:
1963: function updateCrsFile(form,element) {
1964: var directory = form.elements['coursepath_'+element];
1965: var filename = form.elements['coursefile_'+element];
1966: var path = directory.options[directory.selectedIndex].value;
1967: var file = filename.options[filename.selectedIndex].value;
1968: if (file != '') {
1969: form.elements[element].value = '$respath';
1970: if (path == '/') {
1971: form.elements[element].value += file;
1972: } else {
1973: form.elements[element].value += path+'/'+file;
1974: }
1975: unClean();
1976: if (document.getElementById('previewimg_'+element)) {
1977: document.getElementById('previewimg_'+element).src = form.elements[element].value;
1978: var newsrc = document.getElementById('previewimg_'+element).src;
1979: }
1980: if (document.getElementById('showimg_'+element)) {
1981: document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
1982: }
1983: }
1984: toggleChooser(form,element);
1985: return;
1986: }
1987:
1988: function uploadDone(suffix,name) {
1989: if (name) {
1990: document.forms["lonhomework"].elements[suffix].value = name;
1991: unClean();
1992: toggleChooser(document.forms["lonhomework"],suffix);
1993: }
1994: }
1995:
1996: \$(document).ready(function(){
1997:
1998: \$(document).delegate('form :submit', 'click', function( event ) {
1999: if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
2000: var buttonId = this.id;
2001: var suffix = buttonId.toString();
2002: suffix = suffix.replace(/^crsupload_/,'');
2003: event.preventDefault();
2004: document.lonhomework.target = 'crsupload_target_'+suffix;
2005: document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
2006: \$(this.form).submit();
2007: document.lonhomework.target = '';
2008: if (document.getElementById('crsuploadto_'+suffix)) {
2009: document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
2010: }
2011: return false;
2012: }
2013: });
2014: });
2015: END
2016: }
2017: return <<"COLORFULEDIT"
2018: <script type="text/javascript">
2019: // <![CDATA[>
2020: function fold_box(curDepth, lastresource){
2021:
2022: // we need a list because there can be several blocks you need to fold in one tag
2023: var block = document.getElementsByName('foldblock_'+curDepth);
2024: // but there is only one folding button per tag
2025: var foldbutton = document.getElementById('folding_btn_'+curDepth);
2026:
2027: if(block.item(0).style.display == 'none'){
2028:
2029: foldbutton.value = '@{[&mt("Hide")]}';
2030: for (i = 0; i < block.length; i++){
2031: block.item(i).style.display = '';
2032: }
2033: }else{
2034:
2035: foldbutton.value = '@{[&mt("Show")]}';
2036: for (i = 0; i < block.length; i++){
2037: // block.item(i).style.visibility = 'collapse';
2038: block.item(i).style.display = 'none';
2039: }
2040: };
2041: saveState(lastresource);
2042: }
2043:
2044: function saveState (lastresource) {
2045:
2046: var tag_list = getTagList();
2047: if(tag_list != null){
2048: var timestamp = new Date().getTime();
2049: var key = lastresource;
2050:
2051: // the value pattern is: 'time;key1,value1;key2,value2; ... '
2052: // starting with timestamp
2053: var value = timestamp+';';
2054:
2055: // building the list of key-value pairs
2056: for(var i = 0; i < tag_list.length; i++){
2057: value += tag_list[i]+',';
2058: value += document.getElementsByName(tag_list[i])[0].style.display+';';
2059: }
2060:
2061: // only iterate whole storage if nothing to override
2062: if(localStorage.getItem(key) == null){
2063:
2064: // prevent storage from growing large
2065: if(localStorage.length > 50){
2066: var regex_getTimestamp = /^(?:\d)+;/;
2067: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
2068: var oldest_key;
2069:
2070: for(var i = 1; i < localStorage.length; i++){
2071: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
2072: oldest_key = localStorage.key(i);
2073: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
2074: }
2075: }
2076: localStorage.removeItem(oldest_key);
2077: }
2078: }
2079: localStorage.setItem(key,value);
2080: }
2081: }
2082:
2083: // restore folding status of blocks (on page load)
2084: function restoreState (lastresource) {
2085: if(localStorage.getItem(lastresource) != null){
2086: var key = lastresource;
2087: var value = localStorage.getItem(key);
2088: var regex_delTimestamp = /^\d+;/;
2089:
2090: value.replace(regex_delTimestamp, '');
2091:
2092: var valueArr = value.split(';');
2093: var pairs;
2094: var elements;
2095: for (var i = 0; i < valueArr.length; i++){
2096: pairs = valueArr[i].split(',');
2097: elements = document.getElementsByName(pairs[0]);
2098:
2099: for (var j = 0; j < elements.length; j++){
2100: elements[j].style.display = pairs[1];
2101: if (pairs[1] == "none"){
2102: var regex_id = /([_\\d]+)\$/;
2103: regex_id.exec(pairs[0]);
2104: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
2105: }
2106: }
2107: }
2108: }
2109: }
2110:
2111: function getTagList () {
2112:
2113: var stringToSearch = document.lonhomework.innerHTML;
2114:
2115: var ret = new Array();
2116: var regex_findBlock = /(foldblock_.*?)"/g;
2117: var tag_list = stringToSearch.match(regex_findBlock);
2118:
2119: if(tag_list != null){
2120: for(var i = 0; i < tag_list.length; i++){
2121: ret.push(tag_list[i].replace(/"/, ''));
2122: }
2123: }
2124: return ret;
2125: }
2126:
2127: function saveScrollPosition (resource) {
2128: var tag_list = getTagList();
2129:
2130: // we dont always want to jump to the first block
2131: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
2132: if(\$(window).scrollTop() > 170){
2133: if(tag_list != null){
2134: var result;
2135: for(var i = 0; i < tag_list.length; i++){
2136: if(isElementInViewport(tag_list[i])){
2137: result += tag_list[i]+';';
2138: }
2139: }
2140: sessionStorage.setItem('anchor_'+resource, result);
2141: }
2142: } else {
2143: // we dont need to save zero, just delete the item to leave everything tidy
2144: sessionStorage.removeItem('anchor_'+resource);
2145: }
2146: }
2147:
2148: function restoreScrollPosition(resource){
2149:
2150: var elem = sessionStorage.getItem('anchor_'+resource);
2151: if(elem != null){
2152: var tag_list = elem.split(';');
2153: var elem_list;
2154:
2155: for(var i = 0; i < tag_list.length; i++){
2156: elem_list = document.getElementsByName(tag_list[i]);
2157:
2158: if(elem_list.length > 0){
2159: elem = elem_list[0];
2160: break;
2161: }
2162: }
2163: elem.scrollIntoView();
2164: }
2165: }
2166:
2167: function isElementInViewport(el) {
2168:
2169: // change to last element instead of first
2170: var elem = document.getElementsByName(el);
2171: var rect = elem[0].getBoundingClientRect();
2172:
2173: return (
2174: rect.top >= 0 &&
2175: rect.left >= 0 &&
2176: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
2177: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
2178: );
2179: }
2180:
2181: function autosize(depth){
2182: var cmInst = window['cm'+depth];
2183: var fitsizeButton = document.getElementById('fitsize'+depth);
2184:
2185: // is fixed size, switching to dynamic
2186: if (sessionStorage.getItem("autosized_"+depth) == null) {
2187: cmInst.setSize("","auto");
2188: fitsizeButton.value = "@{[&mt('Fixed size')]}";
2189: sessionStorage.setItem("autosized_"+depth, "yes");
2190:
2191: // is dynamic size, switching to fixed
2192: } else {
2193: cmInst.setSize("","300px");
2194: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
2195: sessionStorage.removeItem("autosized_"+depth);
2196: }
2197: }
2198:
2199: $browse_or_search
2200:
2201: // ]]>
2202: </script>
2203: COLORFULEDIT
2204: }
2205:
2206: sub xmleditor_js {
2207: return <<XMLEDIT
2208: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
2209: <script type="text/javascript">
2210: // <![CDATA[>
2211:
2212: function saveScrollPosition (resource) {
2213:
2214: var scrollPos = \$(window).scrollTop();
2215: sessionStorage.setItem(resource,scrollPos);
2216: }
2217:
2218: function restoreScrollPosition(resource){
2219:
2220: var scrollPos = sessionStorage.getItem(resource);
2221: \$(window).scrollTop(scrollPos);
2222: }
2223:
2224: // unless internet explorer
2225: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
2226:
2227: \$(document).ready(function() {
2228: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
2229: });
2230: }
2231:
2232: // inserts text at cursor position into codemirror (xml editor only)
2233: function insertText(text){
2234: cm.focus();
2235: var curPos = cm.getCursor();
2236: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2237: }
2238: // ]]>
2239: </script>
2240: XMLEDIT
2241: }
2242:
2243: sub insert_folding_button {
2244: my $curDepth = $Apache::lonxml::curdepth;
2245: my $lastresource = $env{'request.ambiguous'};
2246:
2247: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2248: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2249: }
2250:
2251: sub crsauthor_url {
2252: my ($url) = @_;
2253: if ($url eq '') {
2254: $url = $ENV{'REQUEST_URI'};
2255: }
2256: my ($cnum,$cdom);
2257: if ($env{'request.course.id'}) {
2258: my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
2259: if ($audom ne '' && $auname ne '') {
2260: if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
2261: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
2262: $cnum = $auname;
2263: $cdom = $audom;
2264: }
2265: }
2266: }
2267: return ($cnum,$cdom);
2268: }
2269:
2270: sub import_crsauthor_form {
2271: my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
2272: return (0) unless ($env{'request.course.id'});
2273: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2274: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2275: my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
2276: return (0) unless (($cnum ne '') && ($cdom ne ''));
2277: my @ids=&Apache::lonnet::current_machine_ids();
2278: my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
2279:
2280: if (grep(/^\Q$crshome\E$/,@ids)) {
2281: $is_home = 1;
2282: }
2283: $toppath = "/priv/$cdom/$cnum";
2284: my $nonemptydir = 1;
2285: my $js_only;
2286: if ($only) {
2287: map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
2288: $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
2289: }
2290: $exclude = &Apache::lonnet::priv_exclude();
2291: &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
2292: my $numdirs = scalar(keys(%files));
2293: my %lt = &Apache::lonlocal::texthash (
2294: fnam => 'Filename',
2295: dire => 'Directory',
2296: se => 'Select',
2297: );
2298: $output = $lt{'dire'}.': '.
2299: '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
2300: 'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
2301: '<option value="" selected="selected">'.$lt{'se'}.'</option>';
2302: if ($files{'/'}) {
2303: $output .= '<option value="/">/</option>'."\n";
2304: }
2305: foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
2306: next if ($key eq '/');
2307: $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
2308: }
2309: $output .= '</select><br />'."\n".
2310: $lt{'fnam'}.': <select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
2311: '<option value="" selected="selected"></option>'."\n".
2312: '</select>'."\n".
2313: '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
2314: return ($numdirs,$output);
2315: }
2316:
2317: sub show_crsfiles_js {
2318: my $excluderef = &Apache::lonnet::priv_exclude();
2319: my $se = &js_escape(&mt('Select'));
2320: my $exclude;
2321: if (ref($excluderef) eq 'HASH') {
2322: $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
2323: }
2324: my $js = <<"END";
2325:
2326:
2327: function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
2328: var relpath = '';
2329: if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
2330: var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
2331: if (currdir == '') {
2332: if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2333: selelem = form.elements[filesel];
2334: var j, numfiles = selelem.options.length -1;
2335: if (numfiles >=0) {
2336: for (j = numfiles; j >= 0; j--) {
2337: selelem.remove(j);
2338: }
2339: }
2340: if (selelem.options.length == 0) {
2341: selelem.options[selelem.options.length] = new Option('','');
2342: selelem.selectedIndex = 0;
2343: }
2344: }
2345: return;
2346: } else {
2347: relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
2348: }
2349: }
2350: var http = new XMLHttpRequest();
2351: var url = "/adm/courseauthor";
2352: var crsrole = "$env{'request.role'}";
2353: var exclude = '';
2354: if (exc) {
2355: exclude = '$exclude';
2356: }
2357: var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
2358: http.open("POST", url, true);
2359: http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
2360: http.onreadystatechange = function() {
2361: if (http.readyState == 4 && http.status == 200) {
2362: var data = JSON.parse(http.responseText);
2363: var selelem;
2364: if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
2365: if (Array.isArray(data.dirs)) {
2366: selelem = form.elements[dirsel];
2367: var i, numdirs = selelem.options.length -1;
2368: if (numdirs >=0) {
2369: for (i = numdirs; i >= 0; i--) {
2370: selelem.remove(i);
2371: }
2372: }
2373: var len = data.dirs.length;
2374: if (len) {
2375: selelem.options[selelem.options.length] = new Option('$se','');
2376: var j;
2377: for (j = 0; j < len; j++) {
2378: selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
2379: }
2380: selelem.selectedIndex = 0;
2381: }
2382: if (!setfile) {
2383: if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2384: selelem = form.elements[filesel];
2385: var j, numfiles = selelem.options.length -1;
2386: if (numfiles >=0) {
2387: for (j = numfiles; j >= 0; j--) {
2388: selelem.remove(j);
2389: }
2390: }
2391: if (selelem.options.length == 0) {
2392: selelem.options[selelem.options.length] = new Option('','');
2393: selelem.selectedIndex = 0;
2394: }
2395: }
2396: }
2397: }
2398: }
2399: if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2400: selelem = form.elements[filesel];
2401: var i, numfiles = selelem.options.length -1;
2402: if (numfiles >=0) {
2403: for (i = numfiles; i >= 0; i--) {
2404: selelem.remove(i);
2405: }
2406: }
2407: var x;
2408: for (x in data.files) {
2409: if (Array.isArray(data.files[x])) {
2410: if (data.files[x].length > 1) {
2411: selelem.options[selelem.options.length] = new Option('$se','');
2412: }
2413: var len = data.files[x].length;
2414: if (len) {
2415: var k;
2416: for (k = 0; k < len; k++) {
2417: selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
2418: }
2419: selelem.selectedIndex = 0;
2420: }
2421: }
2422: }
2423: if (selelem.options.length == 0) {
2424: selelem.options[selelem.options.length] = new Option('','');
2425: selelem.selectedIndex = 0;
2426: }
2427: }
2428: }
2429: }
2430: http.send(params);
2431: }
2432: END
2433: }
2434:
2435: =pod
2436:
2437: =head1 Excel and CSV file utility routines
2438:
2439: =cut
2440:
2441: ###############################################################
2442: ###############################################################
2443:
2444: =pod
2445:
2446: =over 4
2447:
2448: =item * &csv_translate($text)
2449:
2450: Translate $text to allow it to be output as a 'comma separated values'
2451: format.
2452:
2453: =cut
2454:
2455: ###############################################################
2456: ###############################################################
2457: sub csv_translate {
2458: my $text = shift;
2459: $text =~ s/\"/\"\"/g;
2460: $text =~ s/\n/ /g;
2461: return $text;
2462: }
2463:
2464: ###############################################################
2465: ###############################################################
2466:
2467: =pod
2468:
2469: =item * &define_excel_formats()
2470:
2471: Define some commonly used Excel cell formats.
2472:
2473: Currently supported formats:
2474:
2475: =over 4
2476:
2477: =item header
2478:
2479: =item bold
2480:
2481: =item h1
2482:
2483: =item h2
2484:
2485: =item h3
2486:
2487: =item h4
2488:
2489: =item i
2490:
2491: =item date
2492:
2493: =back
2494:
2495: Inputs: $workbook
2496:
2497: Returns: $format, a hash reference.
2498:
2499:
2500: =cut
2501:
2502: ###############################################################
2503: ###############################################################
2504: sub define_excel_formats {
2505: my ($workbook) = @_;
2506: my $format;
2507: $format->{'header'} = $workbook->add_format(bold => 1,
2508: bottom => 1,
2509: align => 'center');
2510: $format->{'bold'} = $workbook->add_format(bold=>1);
2511: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2512: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2513: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2514: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2515: $format->{'i'} = $workbook->add_format(italic=>1);
2516: $format->{'date'} = $workbook->add_format(num_format=>
2517: 'mm/dd/yyyy hh:mm:ss');
2518: return $format;
2519: }
2520:
2521: ###############################################################
2522: ###############################################################
2523:
2524: =pod
2525:
2526: =item * &create_workbook()
2527:
2528: Create an Excel worksheet. If it fails, output message on the
2529: request object and return undefs.
2530:
2531: Inputs: Apache request object
2532:
2533: Returns (undef) on failure,
2534: Excel worksheet object, scalar with filename, and formats
2535: from &Apache::loncommon::define_excel_formats on success
2536:
2537: =cut
2538:
2539: ###############################################################
2540: ###############################################################
2541: sub create_workbook {
2542: my ($r) = @_;
2543: #
2544: # Create the excel spreadsheet
2545: my $filename = '/prtspool/'.
2546: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2547: time.'_'.rand(1000000000).'.xls';
2548: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2549: if (! defined($workbook)) {
2550: $r->log_error("Error creating excel spreadsheet $filename: $!");
2551: $r->print(
2552: '<p class="LC_error">'
2553: .&mt('Problems occurred in creating the new Excel file.')
2554: .' '.&mt('This error has been logged.')
2555: .' '.&mt('Please alert your LON-CAPA administrator.')
2556: .'</p>'
2557: );
2558: return (undef);
2559: }
2560: #
2561: $workbook->set_tempdir(LONCAPA::tempdir());
2562: #
2563: my $format = &Apache::loncommon::define_excel_formats($workbook);
2564: return ($workbook,$filename,$format);
2565: }
2566:
2567: ###############################################################
2568: ###############################################################
2569:
2570: =pod
2571:
2572: =item * &create_text_file()
2573:
2574: Create a file to write to and eventually make available to the user.
2575: If file creation fails, outputs an error message on the request object and
2576: return undefs.
2577:
2578: Inputs: Apache request object, and file suffix
2579:
2580: Returns (undef) on failure,
2581: Filehandle and filename on success.
2582:
2583: =cut
2584:
2585: ###############################################################
2586: ###############################################################
2587: sub create_text_file {
2588: my ($r,$suffix) = @_;
2589: if (! defined($suffix)) { $suffix = 'txt'; };
2590: my $fh;
2591: my $filename = '/prtspool/'.
2592: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2593: time.'_'.rand(1000000000).'.'.$suffix;
2594: $fh = Apache::File->new('>/home/httpd'.$filename);
2595: if (! defined($fh)) {
2596: $r->log_error("Couldn't open $filename for output $!");
2597: $r->print(
2598: '<p class="LC_error">'
2599: .&mt('Problems occurred in creating the output file.')
2600: .' '.&mt('This error has been logged.')
2601: .' '.&mt('Please alert your LON-CAPA administrator.')
2602: .'</p>'
2603: );
2604: }
2605: return ($fh,$filename)
2606: }
2607:
2608:
2609: =pod
2610:
2611: =back
2612:
2613: =cut
2614:
2615: ###############################################################
2616: ## Home server <option> list generating code ##
2617: ###############################################################
2618:
2619: # ------------------------------------------
2620:
2621: sub domain_select {
2622: my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
2623: my @possdoms;
2624: if (ref($incdoms) eq 'ARRAY') {
2625: @possdoms = @{$incdoms};
2626: } else {
2627: @possdoms = &Apache::lonnet::all_domains();
2628: }
2629:
2630: my %domains=map {
2631: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2632: } @possdoms;
2633:
2634: if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
2635: foreach my $dom (@{$excdoms}) {
2636: delete($domains{$dom});
2637: }
2638: }
2639:
2640: if ($multiple) {
2641: $domains{''}=&mt('Any domain');
2642: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2643: return &multiple_select_form($name,$value,4,\%domains);
2644: } else {
2645: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2646: return &select_form($name,$value,\%domains);
2647: }
2648: }
2649:
2650: #-------------------------------------------
2651:
2652: =pod
2653:
2654: =head1 Routines for form select boxes
2655:
2656: =over 4
2657:
2658: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2659:
2660: Returns a string containing a <select> element int multiple mode
2661:
2662:
2663: Args:
2664: $name - name of the <select> element
2665: $value - scalar or array ref of values that should already be selected
2666: $size - number of rows long the select element is
2667: $hash - the elements should be 'option' => 'shown text'
2668: (shown text should already have been &mt())
2669: $order - (optional) array ref of the order to show the elements in
2670:
2671: =cut
2672:
2673: #-------------------------------------------
2674: sub multiple_select_form {
2675: my ($name,$value,$size,$hash,$order)=@_;
2676: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2677: my $output='';
2678: if (! defined($size)) {
2679: $size = 4;
2680: if (scalar(keys(%$hash))<4) {
2681: $size = scalar(keys(%$hash));
2682: }
2683: }
2684: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2685: my @order;
2686: if (ref($order) eq 'ARRAY') {
2687: @order = @{$order};
2688: } else {
2689: @order = sort(keys(%$hash));
2690: }
2691: if (exists($$hash{'select_form_order'})) {
2692: @order = @{$$hash{'select_form_order'}};
2693: }
2694:
2695: foreach my $key (@order) {
2696: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2697: $output.='selected="selected" ' if ($selected{$key});
2698: $output.='>'.$hash->{$key}."</option>\n";
2699: }
2700: $output.="</select>\n";
2701: return $output;
2702: }
2703:
2704: #-------------------------------------------
2705:
2706: =pod
2707:
2708: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2709:
2710: Returns a string containing a <select name='$name' size='1'> form to
2711: allow a user to select options from a ref to a hash containing:
2712: option_name => displayed text. An optional $onchange can include
2713: a javascript onchange item, e.g., onchange="this.form.submit();".
2714: An optional arg -- $readonly -- if true will cause the select form
2715: to be disabled, e.g., for the case where an instructor has a section-
2716: specific role, and is viewing/modifying parameters.
2717:
2718: See lonrights.pm for an example invocation and use.
2719:
2720: =cut
2721:
2722: #-------------------------------------------
2723: sub select_form {
2724: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2725: return unless (ref($hashref) eq 'HASH');
2726: if ($onchange) {
2727: $onchange = ' onchange="'.$onchange.'"';
2728: }
2729: my $disabled;
2730: if ($readonly) {
2731: $disabled = ' disabled="disabled"';
2732: }
2733: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2734: my @keys;
2735: if (exists($hashref->{'select_form_order'})) {
2736: @keys=@{$hashref->{'select_form_order'}};
2737: } else {
2738: @keys=sort(keys(%{$hashref}));
2739: }
2740: foreach my $key (@keys) {
2741: $selectform.=
2742: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2743: ($key eq $def ? 'selected="selected" ' : '').
2744: ">".$hashref->{$key}."</option>\n";
2745: }
2746: $selectform.="</select>";
2747: return $selectform;
2748: }
2749:
2750: # For display filters
2751:
2752: sub display_filter {
2753: my ($context) = @_;
2754: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2755: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2756: my $phraseinput = 'hidden';
2757: my $includeinput = 'hidden';
2758: my ($checked,$includetypestext);
2759: if ($env{'form.displayfilter'} eq 'containing') {
2760: $phraseinput = 'text';
2761: if ($context eq 'parmslog') {
2762: $includeinput = 'checkbox';
2763: if ($env{'form.includetypes'}) {
2764: $checked = ' checked="checked"';
2765: }
2766: $includetypestext = &mt('Include parameter types');
2767: }
2768: } else {
2769: $includetypestext = ' ';
2770: }
2771: my ($additional,$secondid,$thirdid);
2772: if ($context eq 'parmslog') {
2773: $additional =
2774: '<label><input type="'.$includeinput.'" name="includetypes"'.
2775: $checked.' name="includetypes" value="1" id="includetypes" />'.
2776: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2777: '</label>';
2778: $secondid = 'includetypes';
2779: $thirdid = 'includetypestext';
2780: }
2781: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2782: '$secondid','$thirdid')";
2783: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2784: &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
2785: (&mt('all'),10,20,50,100,1000,10000))).
2786: '</label></span> <span class="LC_nobreak">'.
2787: &mt('Filter: [_1]',
2788: &select_form($env{'form.displayfilter'},
2789: 'displayfilter',
2790: {'currentfolder' => 'Current folder/page',
2791: 'containing' => 'Containing phrase',
2792: 'none' => 'None'},$onchange)).' '.
2793: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2794: &HTML::Entities::encode($env{'form.containingphrase'}).
2795: '" />'.$additional;
2796: }
2797:
2798: sub display_filter_js {
2799: my $includetext = &mt('Include parameter types');
2800: return <<"ENDJS";
2801:
2802: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2803: var firstType = 'hidden';
2804: if (setter.options[setter.selectedIndex].value == 'containing') {
2805: firstType = 'text';
2806: }
2807: firstObject = document.getElementById(firstid);
2808: if (typeof(firstObject) == 'object') {
2809: if (firstObject.type != firstType) {
2810: changeInputType(firstObject,firstType);
2811: }
2812: }
2813: if (context == 'parmslog') {
2814: var secondType = 'hidden';
2815: if (firstType == 'text') {
2816: secondType = 'checkbox';
2817: }
2818: secondObject = document.getElementById(secondid);
2819: if (typeof(secondObject) == 'object') {
2820: if (secondObject.type != secondType) {
2821: changeInputType(secondObject,secondType);
2822: }
2823: }
2824: var textItem = document.getElementById(thirdid);
2825: var currtext = textItem.innerHTML;
2826: var newtext;
2827: if (firstType == 'text') {
2828: newtext = '$includetext';
2829: } else {
2830: newtext = ' ';
2831: }
2832: if (currtext != newtext) {
2833: textItem.innerHTML = newtext;
2834: }
2835: }
2836: return;
2837: }
2838:
2839: function changeInputType(oldObject,newType) {
2840: var newObject = document.createElement('input');
2841: newObject.type = newType;
2842: if (oldObject.size) {
2843: newObject.size = oldObject.size;
2844: }
2845: if (oldObject.value) {
2846: newObject.value = oldObject.value;
2847: }
2848: if (oldObject.name) {
2849: newObject.name = oldObject.name;
2850: }
2851: if (oldObject.id) {
2852: newObject.id = oldObject.id;
2853: }
2854: oldObject.parentNode.replaceChild(newObject,oldObject);
2855: return;
2856: }
2857:
2858: ENDJS
2859: }
2860:
2861: sub gradeleveldescription {
2862: my $gradelevel=shift;
2863: my %gradelevels=(0 => 'Not specified',
2864: 1 => 'Grade 1',
2865: 2 => 'Grade 2',
2866: 3 => 'Grade 3',
2867: 4 => 'Grade 4',
2868: 5 => 'Grade 5',
2869: 6 => 'Grade 6',
2870: 7 => 'Grade 7',
2871: 8 => 'Grade 8',
2872: 9 => 'Grade 9',
2873: 10 => 'Grade 10',
2874: 11 => 'Grade 11',
2875: 12 => 'Grade 12',
2876: 13 => 'Grade 13',
2877: 14 => '100 Level',
2878: 15 => '200 Level',
2879: 16 => '300 Level',
2880: 17 => '400 Level',
2881: 18 => 'Graduate Level');
2882: return &mt($gradelevels{$gradelevel});
2883: }
2884:
2885: sub select_level_form {
2886: my ($deflevel,$name)=@_;
2887: unless ($deflevel) { $deflevel=0; }
2888: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2889: for (my $i=0; $i<=18; $i++) {
2890: $selectform.="<option value=\"$i\" ".
2891: ($i==$deflevel ? 'selected="selected" ' : '').
2892: ">".&gradeleveldescription($i)."</option>\n";
2893: }
2894: $selectform.="</select>";
2895: return $selectform;
2896: }
2897:
2898: #-------------------------------------------
2899:
2900: =pod
2901:
2902: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2903:
2904: Returns a string containing a <select name='$name' size='1'> form to
2905: allow a user to select the domain to preform an operation in.
2906: See loncreateuser.pm for an example invocation and use.
2907:
2908: If the $includeempty flag is set, it also includes an empty choice ("no domain
2909: selected");
2910:
2911: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2912:
2913: 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.
2914:
2915: The optional $incdoms is a reference to an array of domains which will be the only available options.
2916:
2917: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2918:
2919: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2920:
2921: =cut
2922:
2923: #-------------------------------------------
2924: sub select_dom_form {
2925: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2926: if ($onchange) {
2927: $onchange = ' onchange="'.$onchange.'"';
2928: }
2929: if ($disabled) {
2930: $disabled = ' disabled="disabled"';
2931: }
2932: my (@domains,%exclude);
2933: if (ref($incdoms) eq 'ARRAY') {
2934: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2935: } else {
2936: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2937: }
2938: if ($includeempty) { @domains=('',@domains); }
2939: if (ref($excdoms) eq 'ARRAY') {
2940: map { $exclude{$_} = 1; } @{$excdoms};
2941: }
2942: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2943: foreach my $dom (@domains) {
2944: next if ($exclude{$dom});
2945: $selectdomain.="<option value=\"$dom\" ".
2946: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2947: if ($showdomdesc) {
2948: if ($dom ne '') {
2949: my $domdesc = &Apache::lonnet::domain($dom,'description');
2950: if ($domdesc ne '') {
2951: $selectdomain .= ' ('.$domdesc.')';
2952: }
2953: }
2954: }
2955: $selectdomain .= "</option>\n";
2956: }
2957: $selectdomain.="</select>";
2958: return $selectdomain;
2959: }
2960:
2961: #-------------------------------------------
2962:
2963: =pod
2964:
2965: =item * &home_server_form_item($domain,$name,$defaultflag)
2966:
2967: input: 4 arguments (two required, two optional) -
2968: $domain - domain of new user
2969: $name - name of form element
2970: $default - Value of 'default' causes a default item to be first
2971: option, and selected by default.
2972: $hide - Value of 'hide' causes hiding of the name of the server,
2973: if 1 server found, or default, if 0 found.
2974: output: returns 2 items:
2975: (a) form element which contains either:
2976: (i) <select name="$name">
2977: <option value="$hostid1">$hostid $servers{$hostid}</option>
2978: <option value="$hostid2">$hostid $servers{$hostid}</option>
2979: </select>
2980: form item if there are multiple library servers in $domain, or
2981: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2982: if there is only one library server in $domain.
2983:
2984: (b) number of library servers found.
2985:
2986: See loncreateuser.pm for example of use.
2987:
2988: =cut
2989:
2990: #-------------------------------------------
2991: sub home_server_form_item {
2992: my ($domain,$name,$default,$hide) = @_;
2993: my %servers = &Apache::lonnet::get_servers($domain,'library');
2994: my $result;
2995: my $numlib = keys(%servers);
2996: if ($numlib > 1) {
2997: $result .= '<select name="'.$name.'" />'."\n";
2998: if ($default) {
2999: $result .= '<option value="default" selected="selected">'.&mt('default').
3000: '</option>'."\n";
3001: }
3002: foreach my $hostid (sort(keys(%servers))) {
3003: $result.= '<option value="'.$hostid.'">'.
3004: $hostid.' '.$servers{$hostid}."</option>\n";
3005: }
3006: $result .= '</select>'."\n";
3007: } elsif ($numlib == 1) {
3008: my $hostid;
3009: foreach my $item (keys(%servers)) {
3010: $hostid = $item;
3011: }
3012: $result .= '<input type="hidden" name="'.$name.'" value="'.
3013: $hostid.'" />';
3014: if (!$hide) {
3015: $result .= $hostid.' '.$servers{$hostid};
3016: }
3017: $result .= "\n";
3018: } elsif ($default) {
3019: $result .= '<input type="hidden" name="'.$name.
3020: '" value="default" />';
3021: if (!$hide) {
3022: $result .= &mt('default');
3023: }
3024: $result .= "\n";
3025: }
3026: return ($result,$numlib);
3027: }
3028:
3029: =pod
3030:
3031: =back
3032:
3033: =cut
3034:
3035: ###############################################################
3036: ## Decoding User Agent ##
3037: ###############################################################
3038:
3039: =pod
3040:
3041: =head1 Decoding the User Agent
3042:
3043: =over 4
3044:
3045: =item * &decode_user_agent()
3046:
3047: Inputs: $r
3048:
3049: Outputs:
3050:
3051: =over 4
3052:
3053: =item * $httpbrowser
3054:
3055: =item * $clientbrowser
3056:
3057: =item * $clientversion
3058:
3059: =item * $clientmathml
3060:
3061: =item * $clientunicode
3062:
3063: =item * $clientos
3064:
3065: =item * $clientmobile
3066:
3067: =item * $clientinfo
3068:
3069: =item * $clientosversion
3070:
3071: =back
3072:
3073: =back
3074:
3075: =cut
3076:
3077: ###############################################################
3078: ###############################################################
3079: sub decode_user_agent {
3080: my ($r)=@_;
3081: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
3082: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
3083: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
3084: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
3085: my $clientbrowser='unknown';
3086: my $clientversion='0';
3087: my $clientmathml='';
3088: my $clientunicode='0';
3089: my $clientmobile=0;
3090: my $clientosversion='';
3091: for (my $i=0;$i<=$#browsertype;$i++) {
3092: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
3093: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
3094: $clientbrowser=$bname;
3095: $httpbrowser=~/$vreg/i;
3096: $clientversion=$1;
3097: $clientmathml=($clientversion>=$minv);
3098: $clientunicode=($clientversion>=$univ);
3099: }
3100: }
3101: my $clientos='unknown';
3102: my $clientinfo;
3103: if (($httpbrowser=~/linux/i) ||
3104: ($httpbrowser=~/unix/i) ||
3105: ($httpbrowser=~/ux/i) ||
3106: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
3107: if (($httpbrowser=~/vax/i) ||
3108: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
3109: if ($httpbrowser=~/next/i) { $clientos='next'; }
3110: if (($httpbrowser=~/mac/i) ||
3111: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
3112: if ($httpbrowser=~/win/i) {
3113: $clientos='win';
3114: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
3115: $clientosversion = $1;
3116: }
3117: }
3118: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
3119: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
3120: $clientmobile=lc($1);
3121: }
3122: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
3123: $clientinfo = 'firefox-'.$1;
3124: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
3125: $clientinfo = 'chromeframe-'.$1;
3126: }
3127: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
3128: $clientunicode,$clientos,$clientmobile,$clientinfo,
3129: $clientosversion);
3130: }
3131:
3132: ###############################################################
3133: ## Authentication changing form generation subroutines ##
3134: ###############################################################
3135: ##
3136: ## All of the authform_xxxxxxx subroutines take their inputs in a
3137: ## hash, and have reasonable default values.
3138: ##
3139: ## formname = the name given in the <form> tag.
3140: #-------------------------------------------
3141:
3142: =pod
3143:
3144: =head1 Authentication Routines
3145:
3146: =over 4
3147:
3148: =item * &authform_xxxxxx()
3149:
3150: The authform_xxxxxx subroutines provide javascript and html forms which
3151: handle some of the conveniences required for authentication forms.
3152: This is not an optimal method, but it works.
3153:
3154: =over 4
3155:
3156: =item * authform_header
3157:
3158: =item * authform_authorwarning
3159:
3160: =item * authform_nochange
3161:
3162: =item * authform_kerberos
3163:
3164: =item * authform_internal
3165:
3166: =item * authform_filesystem
3167:
3168: =item * authform_lti
3169:
3170: =back
3171:
3172: See loncreateuser.pm for invocation and use examples.
3173:
3174: =cut
3175:
3176: #-------------------------------------------
3177: sub authform_header{
3178: my %in = (
3179: formname => 'cu',
3180: kerb_def_dom => '',
3181: @_,
3182: );
3183: $in{'formname'} = 'document.' . $in{'formname'};
3184: my $result='';
3185:
3186: #---------------------------------------------- Code for upper case translation
3187: my $Javascript_toUpperCase;
3188: unless ($in{kerb_def_dom}) {
3189: $Javascript_toUpperCase =<<"END";
3190: switch (choice) {
3191: case 'krb': currentform.elements[choicearg].value =
3192: currentform.elements[choicearg].value.toUpperCase();
3193: break;
3194: default:
3195: }
3196: END
3197: } else {
3198: $Javascript_toUpperCase = "";
3199: }
3200:
3201: my $radioval = "'nochange'";
3202: if (defined($in{'curr_authtype'})) {
3203: if ($in{'curr_authtype'} ne '') {
3204: $radioval = "'".$in{'curr_authtype'}."arg'";
3205: }
3206: }
3207: my $argfield = 'null';
3208: if (defined($in{'mode'})) {
3209: if ($in{'mode'} eq 'modifycourse') {
3210: if (defined($in{'curr_autharg'})) {
3211: if ($in{'curr_autharg'} ne '') {
3212: $argfield = "'$in{'curr_autharg'}'";
3213: }
3214: }
3215: }
3216: }
3217:
3218: $result.=<<"END";
3219: var current = new Object();
3220: current.radiovalue = $radioval;
3221: current.argfield = $argfield;
3222:
3223: function changed_radio(choice,currentform) {
3224: var choicearg = choice + 'arg';
3225: // If a radio button in changed, we need to change the argfield
3226: if (current.radiovalue != choice) {
3227: current.radiovalue = choice;
3228: if (current.argfield != null) {
3229: currentform.elements[current.argfield].value = '';
3230: }
3231: if (choice == 'nochange') {
3232: current.argfield = null;
3233: } else {
3234: current.argfield = choicearg;
3235: switch(choice) {
3236: case 'krb':
3237: currentform.elements[current.argfield].value =
3238: "$in{'kerb_def_dom'}";
3239: break;
3240: default:
3241: break;
3242: }
3243: }
3244: }
3245: return;
3246: }
3247:
3248: function changed_text(choice,currentform) {
3249: var choicearg = choice + 'arg';
3250: if (currentform.elements[choicearg].value !='') {
3251: $Javascript_toUpperCase
3252: // clear old field
3253: if ((current.argfield != choicearg) && (current.argfield != null)) {
3254: currentform.elements[current.argfield].value = '';
3255: }
3256: current.argfield = choicearg;
3257: }
3258: set_auth_radio_buttons(choice,currentform);
3259: return;
3260: }
3261:
3262: function set_auth_radio_buttons(newvalue,currentform) {
3263: var numauthchoices = currentform.login.length;
3264: if (typeof numauthchoices == "undefined") {
3265: return;
3266: }
3267: var i=0;
3268: while (i < numauthchoices) {
3269: if (currentform.login[i].value == newvalue) { break; }
3270: i++;
3271: }
3272: if (i == numauthchoices) {
3273: return;
3274: }
3275: current.radiovalue = newvalue;
3276: currentform.login[i].checked = true;
3277: return;
3278: }
3279: END
3280: return $result;
3281: }
3282:
3283: sub authform_authorwarning {
3284: my $result='';
3285: $result='<i>'.
3286: &mt('As a general rule, only authors or co-authors should be '.
3287: 'filesystem authenticated '.
3288: '(which allows access to the server filesystem).')."</i>\n";
3289: return $result;
3290: }
3291:
3292: sub authform_nochange {
3293: my %in = (
3294: formname => 'document.cu',
3295: kerb_def_dom => 'MSU.EDU',
3296: @_,
3297: );
3298: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3299: my $result;
3300: if (!$authnum) {
3301: $result = &mt('Under your current role you are not permitted to change login settings for this user');
3302: } else {
3303: $result = '<label>'.&mt('[_1] Do not change login data',
3304: '<input type="radio" name="login" value="nochange" '.
3305: 'checked="checked" onclick="'.
3306: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
3307: '</label>';
3308: }
3309: return $result;
3310: }
3311:
3312: sub authform_kerberos {
3313: my %in = (
3314: formname => 'document.cu',
3315: kerb_def_dom => 'MSU.EDU',
3316: kerb_def_auth => 'krb4',
3317: @_,
3318: );
3319: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
3320: $autharg,$jscall,$disabled);
3321: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3322: if ($in{'kerb_def_auth'} eq 'krb5') {
3323: $check5 = ' checked="checked"';
3324: } else {
3325: $check4 = ' checked="checked"';
3326: }
3327: if ($in{'readonly'}) {
3328: $disabled = ' disabled="disabled"';
3329: }
3330: $krbarg = $in{'kerb_def_dom'};
3331: if (defined($in{'curr_authtype'})) {
3332: if ($in{'curr_authtype'} eq 'krb') {
3333: $krbcheck = ' checked="checked"';
3334: if (defined($in{'mode'})) {
3335: if ($in{'mode'} eq 'modifyuser') {
3336: $krbcheck = '';
3337: }
3338: }
3339: if (defined($in{'curr_kerb_ver'})) {
3340: if ($in{'curr_krb_ver'} eq '5') {
3341: $check5 = ' checked="checked"';
3342: $check4 = '';
3343: } else {
3344: $check4 = ' checked="checked"';
3345: $check5 = '';
3346: }
3347: }
3348: if (defined($in{'curr_autharg'})) {
3349: $krbarg = $in{'curr_autharg'};
3350: }
3351: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3352: if (defined($in{'curr_autharg'})) {
3353: $result =
3354: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3355: $in{'curr_autharg'},$krbver);
3356: } else {
3357: $result =
3358: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3359: }
3360: return $result;
3361: }
3362: }
3363: } else {
3364: if ($authnum == 1) {
3365: $authtype = '<input type="hidden" name="login" value="krb" />';
3366: }
3367: }
3368: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3369: return;
3370: } elsif ($authtype eq '') {
3371: if (defined($in{'mode'})) {
3372: if ($in{'mode'} eq 'modifycourse') {
3373: if ($authnum == 1) {
3374: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
3375: }
3376: }
3377: }
3378: }
3379: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3380: if ($authtype eq '') {
3381: $authtype = '<input type="radio" name="login" value="krb" '.
3382: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3383: $krbcheck.$disabled.' />';
3384: }
3385: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3386: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3387: $in{'curr_authtype'} eq 'krb5') ||
3388: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3389: $in{'curr_authtype'} eq 'krb4')) {
3390: $result .= &mt
3391: ('[_1] Kerberos authenticated with domain [_2] '.
3392: '[_3] Version 4 [_4] Version 5 [_5]',
3393: '<label>'.$authtype,
3394: '</label><input type="text" size="10" name="krbarg" '.
3395: 'value="'.$krbarg.'" '.
3396: 'onchange="'.$jscall.'"'.$disabled.' />',
3397: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
3398: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
3399: '</label>');
3400: } elsif ($can_assign{'krb4'}) {
3401: $result .= &mt
3402: ('[_1] Kerberos authenticated with domain [_2] '.
3403: '[_3] Version 4 [_4]',
3404: '<label>'.$authtype,
3405: '</label><input type="text" size="10" name="krbarg" '.
3406: 'value="'.$krbarg.'" '.
3407: 'onchange="'.$jscall.'"'.$disabled.' />',
3408: '<label><input type="hidden" name="krbver" value="4" />',
3409: '</label>');
3410: } elsif ($can_assign{'krb5'}) {
3411: $result .= &mt
3412: ('[_1] Kerberos authenticated with domain [_2] '.
3413: '[_3] Version 5 [_4]',
3414: '<label>'.$authtype,
3415: '</label><input type="text" size="10" name="krbarg" '.
3416: 'value="'.$krbarg.'" '.
3417: 'onchange="'.$jscall.'"'.$disabled.' />',
3418: '<label><input type="hidden" name="krbver" value="5" />',
3419: '</label>');
3420: }
3421: return $result;
3422: }
3423:
3424: sub authform_internal {
3425: my %in = (
3426: formname => 'document.cu',
3427: kerb_def_dom => 'MSU.EDU',
3428: @_,
3429: );
3430: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
3431: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3432: if ($in{'readonly'}) {
3433: $disabled = ' disabled="disabled"';
3434: }
3435: if (defined($in{'curr_authtype'})) {
3436: if ($in{'curr_authtype'} eq 'int') {
3437: if ($can_assign{'int'}) {
3438: $intcheck = 'checked="checked" ';
3439: if (defined($in{'mode'})) {
3440: if ($in{'mode'} eq 'modifyuser') {
3441: $intcheck = '';
3442: }
3443: }
3444: if (defined($in{'curr_autharg'})) {
3445: $intarg = $in{'curr_autharg'};
3446: }
3447: } else {
3448: $result = &mt('Currently internally authenticated.');
3449: return $result;
3450: }
3451: }
3452: } else {
3453: if ($authnum == 1) {
3454: $authtype = '<input type="hidden" name="login" value="int" />';
3455: }
3456: }
3457: if (!$can_assign{'int'}) {
3458: return;
3459: } elsif ($authtype eq '') {
3460: if (defined($in{'mode'})) {
3461: if ($in{'mode'} eq 'modifycourse') {
3462: if ($authnum == 1) {
3463: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3464: }
3465: }
3466: }
3467: }
3468: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3469: if ($authtype eq '') {
3470: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3471: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3472: }
3473: $autharg = '<input type="password" size="10" name="intarg" value="'.
3474: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3475: $result = &mt
3476: ('[_1] Internally authenticated (with initial password [_2])',
3477: '<label>'.$authtype,'</label>'.$autharg);
3478: $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>';
3479: return $result;
3480: }
3481:
3482: sub authform_local {
3483: my %in = (
3484: formname => 'document.cu',
3485: kerb_def_dom => 'MSU.EDU',
3486: @_,
3487: );
3488: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3489: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3490: if ($in{'readonly'}) {
3491: $disabled = ' disabled="disabled"';
3492: }
3493: if (defined($in{'curr_authtype'})) {
3494: if ($in{'curr_authtype'} eq 'loc') {
3495: if ($can_assign{'loc'}) {
3496: $loccheck = 'checked="checked" ';
3497: if (defined($in{'mode'})) {
3498: if ($in{'mode'} eq 'modifyuser') {
3499: $loccheck = '';
3500: }
3501: }
3502: if (defined($in{'curr_autharg'})) {
3503: $locarg = $in{'curr_autharg'};
3504: }
3505: } else {
3506: $result = &mt('Currently using local (institutional) authentication.');
3507: return $result;
3508: }
3509: }
3510: } else {
3511: if ($authnum == 1) {
3512: $authtype = '<input type="hidden" name="login" value="loc" />';
3513: }
3514: }
3515: if (!$can_assign{'loc'}) {
3516: return;
3517: } elsif ($authtype eq '') {
3518: if (defined($in{'mode'})) {
3519: if ($in{'mode'} eq 'modifycourse') {
3520: if ($authnum == 1) {
3521: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3522: }
3523: }
3524: }
3525: }
3526: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3527: if ($authtype eq '') {
3528: $authtype = '<input type="radio" name="login" value="loc" '.
3529: $loccheck.' onchange="'.$jscall.'" onclick="'.
3530: $jscall.'"'.$disabled.' />';
3531: }
3532: $autharg = '<input type="text" size="10" name="locarg" value="'.
3533: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3534: $result = &mt('[_1] Local Authentication with argument [_2]',
3535: '<label>'.$authtype,'</label>'.$autharg);
3536: return $result;
3537: }
3538:
3539: sub authform_filesystem {
3540: my %in = (
3541: formname => 'document.cu',
3542: kerb_def_dom => 'MSU.EDU',
3543: @_,
3544: );
3545: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3546: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3547: if ($in{'readonly'}) {
3548: $disabled = ' disabled="disabled"';
3549: }
3550: if (defined($in{'curr_authtype'})) {
3551: if ($in{'curr_authtype'} eq 'fsys') {
3552: if ($can_assign{'fsys'}) {
3553: $fsyscheck = 'checked="checked" ';
3554: if (defined($in{'mode'})) {
3555: if ($in{'mode'} eq 'modifyuser') {
3556: $fsyscheck = '';
3557: }
3558: }
3559: } else {
3560: $result = &mt('Currently Filesystem Authenticated.');
3561: return $result;
3562: }
3563: }
3564: } else {
3565: if ($authnum == 1) {
3566: $authtype = '<input type="hidden" name="login" value="fsys" />';
3567: }
3568: }
3569: if (!$can_assign{'fsys'}) {
3570: return;
3571: } elsif ($authtype eq '') {
3572: if (defined($in{'mode'})) {
3573: if ($in{'mode'} eq 'modifycourse') {
3574: if ($authnum == 1) {
3575: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3576: }
3577: }
3578: }
3579: }
3580: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3581: if ($authtype eq '') {
3582: $authtype = '<input type="radio" name="login" value="fsys" '.
3583: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3584: $jscall.'"'.$disabled.' />';
3585: }
3586: $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
3587: ' onchange="'.$jscall.'"'.$disabled.' />';
3588: $result = &mt
3589: ('[_1] Filesystem Authenticated (with initial password [_2])',
3590: '<label>'.$authtype,'</label>'.$autharg);
3591: return $result;
3592: }
3593:
3594: sub authform_lti {
3595: my %in = (
3596: formname => 'document.cu',
3597: kerb_def_dom => 'MSU.EDU',
3598: @_,
3599: );
3600: my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
3601: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3602: if ($in{'readonly'}) {
3603: $disabled = ' disabled="disabled"';
3604: }
3605: if (defined($in{'curr_authtype'})) {
3606: if ($in{'curr_authtype'} eq 'lti') {
3607: if ($can_assign{'lti'}) {
3608: $lticheck = 'checked="checked" ';
3609: if (defined($in{'mode'})) {
3610: if ($in{'mode'} eq 'modifyuser') {
3611: $lticheck = '';
3612: }
3613: }
3614: } else {
3615: $result = &mt('Currently LTI Authenticated.');
3616: return $result;
3617: }
3618: }
3619: } else {
3620: if ($authnum == 1) {
3621: $authtype = '<input type="hidden" name="login" value="lti" />';
3622: }
3623: }
3624: if (!$can_assign{'lti'}) {
3625: return;
3626: } elsif ($authtype eq '') {
3627: if (defined($in{'mode'})) {
3628: if ($in{'mode'} eq 'modifycourse') {
3629: if ($authnum == 1) {
3630: $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
3631: }
3632: }
3633: }
3634: }
3635: $jscall = "javascript:changed_radio('lti',$in{'formname'});";
3636: if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
3637: $authtype = '<input type="radio" name="login" value="lti" '.
3638: $lticheck.' onchange="'.$jscall.'" onclick="'.
3639: $jscall.'"'.$disabled.' />';
3640: }
3641: $autharg = '<input type="hidden" name="ltiarg" value="" />';
3642: if ($authtype) {
3643: $result = &mt('[_1] LTI Authenticated',
3644: '<label>'.$authtype.'</label>'.$autharg);
3645: } else {
3646: $result = '<b>'.&mt('LTI Authenticated').'</b>'.
3647: $autharg;
3648: }
3649: return $result;
3650: }
3651:
3652: sub get_assignable_auth {
3653: my ($dom) = @_;
3654: if ($dom eq '') {
3655: $dom = $env{'request.role.domain'};
3656: }
3657: my %can_assign = (
3658: krb4 => 1,
3659: krb5 => 1,
3660: int => 1,
3661: loc => 1,
3662: lti => 1,
3663: );
3664: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3665: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3666: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3667: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3668: my $context;
3669: if ($env{'request.role'} =~ /^au/) {
3670: $context = 'author';
3671: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3672: $context = 'domain';
3673: } elsif ($env{'request.course.id'}) {
3674: $context = 'course';
3675: }
3676: if ($context) {
3677: if (ref($authhash->{$context}) eq 'HASH') {
3678: %can_assign = %{$authhash->{$context}};
3679: }
3680: }
3681: }
3682: }
3683: my $authnum = 0;
3684: foreach my $key (keys(%can_assign)) {
3685: if ($can_assign{$key}) {
3686: $authnum ++;
3687: }
3688: }
3689: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3690: $authnum --;
3691: }
3692: return ($authnum,%can_assign);
3693: }
3694:
3695: sub check_passwd_rules {
3696: my ($domain,$plainpass) = @_;
3697: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3698: my ($min,$max,@chars,@brokerule,$warning);
3699: $min = $Apache::lonnet::passwdmin;
3700: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3701: if ($passwdconf{'min'} =~ /^\d+$/) {
3702: if ($passwdconf{'min'} > $min) {
3703: $min = $passwdconf{'min'};
3704: }
3705: }
3706: if ($passwdconf{'max'} =~ /^\d+$/) {
3707: $max = $passwdconf{'max'};
3708: }
3709: @chars = @{$passwdconf{'chars'}};
3710: }
3711: if (($min) && (length($plainpass) < $min)) {
3712: push(@brokerule,'min');
3713: }
3714: if (($max) && (length($plainpass) > $max)) {
3715: push(@brokerule,'max');
3716: }
3717: if (@chars) {
3718: my %rules;
3719: map { $rules{$_} = 1; } @chars;
3720: if ($rules{'uc'}) {
3721: unless ($plainpass =~ /[A-Z]/) {
3722: push(@brokerule,'uc');
3723: }
3724: }
3725: if ($rules{'lc'}) {
3726: unless ($plainpass =~ /[a-z]/) {
3727: push(@brokerule,'lc');
3728: }
3729: }
3730: if ($rules{'num'}) {
3731: unless ($plainpass =~ /\d/) {
3732: push(@brokerule,'num');
3733: }
3734: }
3735: if ($rules{'spec'}) {
3736: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3737: push(@brokerule,'spec');
3738: }
3739: }
3740: }
3741: if (@brokerule) {
3742: my %rulenames = &Apache::lonlocal::texthash(
3743: uc => 'At least one upper case letter',
3744: lc => 'At least one lower case letter',
3745: num => 'At least one number',
3746: spec => 'At least one non-alphanumeric',
3747: );
3748: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3749: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3750: $rulenames{'num'} .= ': 0123456789';
3751: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3752: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3753: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3754: $warning = &mt('Password did not satisfy the following:').'<ul>';
3755: foreach my $rule ('min','max','uc','lc','num','spec') {
3756: if (grep(/^$rule$/,@brokerule)) {
3757: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3758: }
3759: }
3760: $warning .= '</ul>';
3761: }
3762: if (wantarray) {
3763: return @brokerule;
3764: }
3765: return $warning;
3766: }
3767:
3768: sub passwd_validation_js {
3769: my ($currpasswdval,$domain,$context,$id) = @_;
3770: my (%passwdconf,$alertmsg);
3771: if ($context eq 'linkprot') {
3772: my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
3773: if (ref($domconfig{'ltisec'}) eq 'HASH') {
3774: if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
3775: %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
3776: }
3777: }
3778: if ($id eq 'add') {
3779: $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
3780: } elsif ($id =~ /^\d+$/) {
3781: my $pos = $id+1;
3782: $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
3783: } else {
3784: $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
3785: }
3786: } else {
3787: %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3788: $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
3789: }
3790: my ($min,$max,@chars,$numrules,$intargjs,%alert);
3791: $numrules = 0;
3792: $min = $Apache::lonnet::passwdmin;
3793: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3794: if ($passwdconf{'min'} =~ /^\d+$/) {
3795: if ($passwdconf{'min'} > $min) {
3796: $min = $passwdconf{'min'};
3797: }
3798: }
3799: if ($passwdconf{'max'} =~ /^\d+$/) {
3800: $max = $passwdconf{'max'};
3801: $numrules ++;
3802: }
3803: @chars = @{$passwdconf{'chars'}};
3804: if (@chars) {
3805: $numrules ++;
3806: }
3807: }
3808: if ($min > 0) {
3809: $numrules ++;
3810: }
3811: if (($min > 0) || ($max ne '') || (@chars > 0)) {
3812: if ($min) {
3813: $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
3814: }
3815: if ($max) {
3816: $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
3817: }
3818: my (@charalerts,@charrules);
3819: if (@chars) {
3820: if (grep(/^uc$/,@chars)) {
3821: push(@charalerts,&mt('contain at least one upper case letter'));
3822: push(@charrules,'uc');
3823: }
3824: if (grep(/^lc$/,@chars)) {
3825: push(@charalerts,&mt('contain at least one lower case letter'));
3826: push(@charrules,'lc');
3827: }
3828: if (grep(/^num$/,@chars)) {
3829: push(@charalerts,&mt('contain at least one number'));
3830: push(@charrules,'num');
3831: }
3832: if (grep(/^spec$/,@chars)) {
3833: push(@charalerts,&mt('contain at least one non-alphanumeric'));
3834: push(@charrules,'spec');
3835: }
3836: }
3837: $intargjs = qq| var rulesmsg = '';\n|.
3838: qq| var currpwval = $currpasswdval;\n|;
3839: if ($min) {
3840: $intargjs .= qq|
3841: if (currpwval.length < $min) {
3842: rulesmsg += ' - $alert{min}';
3843: }
3844: |;
3845: }
3846: if ($max) {
3847: $intargjs .= qq|
3848: if (currpwval.length > $max) {
3849: rulesmsg += ' - $alert{max}';
3850: }
3851: |;
3852: }
3853: if (@chars > 0) {
3854: my $charrulestr = '"'.join('","',@charrules).'"';
3855: my $charalertstr = '"'.join('","',@charalerts).'"';
3856: $intargjs .= qq| var brokerules = new Array();\n|.
3857: qq| var charrules = new Array($charrulestr);\n|.
3858: qq| var charalerts = new Array($charalertstr);\n|;
3859: my %rules;
3860: map { $rules{$_} = 1; } @chars;
3861: if ($rules{'uc'}) {
3862: $intargjs .= qq|
3863: var ucRegExp = /[A-Z]/;
3864: if (!ucRegExp.test(currpwval)) {
3865: brokerules.push('uc');
3866: }
3867: |;
3868: }
3869: if ($rules{'lc'}) {
3870: $intargjs .= qq|
3871: var lcRegExp = /[a-z]/;
3872: if (!lcRegExp.test(currpwval)) {
3873: brokerules.push('lc');
3874: }
3875: |;
3876: }
3877: if ($rules{'num'}) {
3878: $intargjs .= qq|
3879: var numRegExp = /[0-9]/;
3880: if (!numRegExp.test(currpwval)) {
3881: brokerules.push('num');
3882: }
3883: |;
3884: }
3885: if ($rules{'spec'}) {
3886: $intargjs .= q|
3887: var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
3888: if (!specRegExp.test(currpwval)) {
3889: brokerules.push('spec');
3890: }
3891: |;
3892: }
3893: $intargjs .= qq|
3894: if (brokerules.length > 0) {
3895: for (var i=0; i<brokerules.length; i++) {
3896: for (var j=0; j<charrules.length; j++) {
3897: if (brokerules[i] == charrules[j]) {
3898: rulesmsg += ' - '+charalerts[j]+'\\n';
3899: break;
3900: }
3901: }
3902: }
3903: }
3904: |;
3905: }
3906: $intargjs .= qq|
3907: if (rulesmsg != '') {
3908: rulesmsg = '$alertmsg'+rulesmsg;
3909: alert(rulesmsg);
3910: return false;
3911: }
3912: |;
3913: }
3914: return ($numrules,$intargjs);
3915: }
3916:
3917: ###############################################################
3918: ## Get Kerberos Defaults for Domain ##
3919: ###############################################################
3920: ##
3921: ## Returns default kerberos version and an associated argument
3922: ## as listed in file domain.tab. If not listed, provides
3923: ## appropriate default domain and kerberos version.
3924: ##
3925: #-------------------------------------------
3926:
3927: =pod
3928:
3929: =item * &get_kerberos_defaults()
3930:
3931: get_kerberos_defaults($target_domain) returns the default kerberos
3932: version and domain. If not found, it defaults to version 4 and the
3933: domain of the server.
3934:
3935: =over 4
3936:
3937: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3938:
3939: =back
3940:
3941: =back
3942:
3943: =cut
3944:
3945: #-------------------------------------------
3946: sub get_kerberos_defaults {
3947: my $domain=shift;
3948: my ($krbdef,$krbdefdom);
3949: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3950: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3951: $krbdef = $domdefaults{'auth_def'};
3952: $krbdefdom = $domdefaults{'auth_arg_def'};
3953: } else {
3954: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3955: my $krbdefdom=$1;
3956: $krbdefdom=~tr/a-z/A-Z/;
3957: $krbdef = "krb4";
3958: }
3959: return ($krbdef,$krbdefdom);
3960: }
3961:
3962:
3963: ###############################################################
3964: ## Thesaurus Functions ##
3965: ###############################################################
3966:
3967: =pod
3968:
3969: =head1 Thesaurus Functions
3970:
3971: =over 4
3972:
3973: =item * &initialize_keywords()
3974:
3975: Initializes the package variable %Keywords if it is empty. Uses the
3976: package variable $thesaurus_db_file.
3977:
3978: =cut
3979:
3980: ###################################################
3981:
3982: sub initialize_keywords {
3983: return 1 if (scalar keys(%Keywords));
3984: # If we are here, %Keywords is empty, so fill it up
3985: # Make sure the file we need exists...
3986: if (! -e $thesaurus_db_file) {
3987: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3988: " failed because it does not exist");
3989: return 0;
3990: }
3991: # Set up the hash as a database
3992: my %thesaurus_db;
3993: if (! tie(%thesaurus_db,'GDBM_File',
3994: $thesaurus_db_file,&GDBM_READER(),0640)){
3995: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3996: $thesaurus_db_file);
3997: return 0;
3998: }
3999: # Get the average number of appearances of a word.
4000: my $avecount = $thesaurus_db{'average.count'};
4001: # Put keywords (those that appear > average) into %Keywords
4002: while (my ($word,$data)=each (%thesaurus_db)) {
4003: my ($count,undef) = split /:/,$data;
4004: $Keywords{$word}++ if ($count > $avecount);
4005: }
4006: untie %thesaurus_db;
4007: # Remove special values from %Keywords.
4008: foreach my $value ('total.count','average.count') {
4009: delete($Keywords{$value}) if (exists($Keywords{$value}));
4010: }
4011: return 1;
4012: }
4013:
4014: ###################################################
4015:
4016: =pod
4017:
4018: =item * &keyword($word)
4019:
4020: Returns true if $word is a keyword. A keyword is a word that appears more
4021: than the average number of times in the thesaurus database. Calls
4022: &initialize_keywords
4023:
4024: =cut
4025:
4026: ###################################################
4027:
4028: sub keyword {
4029: return if (!&initialize_keywords());
4030: my $word=lc(shift());
4031: $word=~s/\W//g;
4032: return exists($Keywords{$word});
4033: }
4034:
4035: ###############################################################
4036:
4037: =pod
4038:
4039: =item * &get_related_words()
4040:
4041: Look up a word in the thesaurus. Takes a scalar argument and returns
4042: an array of words. If the keyword is not in the thesaurus, an empty array
4043: will be returned. The order of the words returned is determined by the
4044: database which holds them.
4045:
4046: Uses global $thesaurus_db_file.
4047:
4048:
4049: =cut
4050:
4051: ###############################################################
4052: sub get_related_words {
4053: my $keyword = shift;
4054: my %thesaurus_db;
4055: if (! -e $thesaurus_db_file) {
4056: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
4057: "failed because the file does not exist");
4058: return ();
4059: }
4060: if (! tie(%thesaurus_db,'GDBM_File',
4061: $thesaurus_db_file,&GDBM_READER(),0640)){
4062: return ();
4063: }
4064: my @Words=();
4065: my $count=0;
4066: if (exists($thesaurus_db{$keyword})) {
4067: # The first element is the number of times
4068: # the word appears. We do not need it now.
4069: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
4070: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
4071: my $threshold=$mostfrequentcount/10;
4072: foreach my $possibleword (@RelatedWords) {
4073: my ($word,$wordcount)=split(/\,/,$possibleword);
4074: if ($wordcount>$threshold) {
4075: push(@Words,$word);
4076: $count++;
4077: if ($count>10) { last; }
4078: }
4079: }
4080: }
4081: untie %thesaurus_db;
4082: return @Words;
4083: }
4084: ###############################################################
4085: #
4086: # Spell checking
4087: #
4088:
4089: =pod
4090:
4091: =back
4092:
4093: =head1 Spell checking
4094:
4095: =over 4
4096:
4097: =item * &check_spelling($wordlist $language)
4098:
4099: Takes a string containing words and feeds it to an external
4100: spellcheck program via a pipeline. Returns a string containing
4101: them mis-spelled words.
4102:
4103: Parameters:
4104:
4105: =over 4
4106:
4107: =item - $wordlist
4108:
4109: String that will be fed into the spellcheck program.
4110:
4111: =item - $language
4112:
4113: Language string that specifies the language for which the spell
4114: check will be performed.
4115:
4116: =back
4117:
4118: =back
4119:
4120: Note: This sub assumes that aspell is installed.
4121:
4122:
4123: =cut
4124:
4125:
4126: sub check_spelling {
4127: my ($wordlist, $language) = @_;
4128: my @misspellings;
4129:
4130: # Generate the speller and set the langauge.
4131: # if explicitly selected:
4132:
4133: my $speller = Text::Aspell->new;
4134: if ($language) {
4135: $speller->set_option('lang', $language);
4136: }
4137:
4138: # Turn the word list into an array of words by splittingon whitespace
4139:
4140: my @words = split(/\s+/, $wordlist);
4141:
4142: foreach my $word (@words) {
4143: if(! $speller->check($word)) {
4144: push(@misspellings, $word);
4145: }
4146: }
4147: return join(' ', @misspellings);
4148:
4149: }
4150:
4151: # -------------------------------------------------------------- Plaintext name
4152: =pod
4153:
4154: =head1 User Name Functions
4155:
4156: =over 4
4157:
4158: =item * &plainname($uname,$udom,$first)
4159:
4160: Takes a users logon name and returns it as a string in
4161: "first middle last generation" form
4162: if $first is set to 'lastname' then it returns it as
4163: 'lastname generation, firstname middlename' if their is a lastname
4164:
4165: =cut
4166:
4167:
4168: ###############################################################
4169: sub plainname {
4170: my ($uname,$udom,$first)=@_;
4171: return if (!defined($uname) || !defined($udom));
4172: my %names=&getnames($uname,$udom);
4173: my $name=&Apache::lonnet::format_name($names{'firstname'},
4174: $names{'middlename'},
4175: $names{'lastname'},
4176: $names{'generation'},$first);
4177: $name=~s/^\s+//;
4178: $name=~s/\s+$//;
4179: $name=~s/\s+/ /g;
4180: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
4181: return $name;
4182: }
4183:
4184: # -------------------------------------------------------------------- Nickname
4185: =pod
4186:
4187: =item * &nickname($uname,$udom)
4188:
4189: Gets a users name and returns it as a string as
4190:
4191: ""nickname""
4192:
4193: if the user has a nickname or
4194:
4195: "first middle last generation"
4196:
4197: if the user does not
4198:
4199: =cut
4200:
4201: sub nickname {
4202: my ($uname,$udom)=@_;
4203: return if (!defined($uname) || !defined($udom));
4204: my %names=&getnames($uname,$udom);
4205: my $name=$names{'nickname'};
4206: if ($name) {
4207: $name='"'.$name.'"';
4208: } else {
4209: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
4210: $names{'lastname'}.' '.$names{'generation'};
4211: $name=~s/\s+$//;
4212: $name=~s/\s+/ /g;
4213: }
4214: return $name;
4215: }
4216:
4217: sub getnames {
4218: my ($uname,$udom)=@_;
4219: return if (!defined($uname) || !defined($udom));
4220: if ($udom eq 'public' && $uname eq 'public') {
4221: return ('lastname' => &mt('Public'));
4222: }
4223: my $id=$uname.':'.$udom;
4224: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
4225: if ($cached) {
4226: return %{$names};
4227: } else {
4228: my %loadnames=&Apache::lonnet::get('environment',
4229: ['firstname','middlename','lastname','generation','nickname'],
4230: $udom,$uname);
4231: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
4232: return %loadnames;
4233: }
4234: }
4235:
4236: # -------------------------------------------------------------------- getemails
4237:
4238: =pod
4239:
4240: =item * &getemails($uname,$udom)
4241:
4242: Gets a user's email information and returns it as a hash with keys:
4243: notification, critnotification, permanentemail
4244:
4245: For notification and critnotification, values are comma-separated lists
4246: of e-mail addresses; for permanentemail, value is a single e-mail address.
4247:
4248:
4249: =cut
4250:
4251:
4252: sub getemails {
4253: my ($uname,$udom)=@_;
4254: if ($udom eq 'public' && $uname eq 'public') {
4255: return;
4256: }
4257: if (!$udom) { $udom=$env{'user.domain'}; }
4258: if (!$uname) { $uname=$env{'user.name'}; }
4259: my $id=$uname.':'.$udom;
4260: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
4261: if ($cached) {
4262: return %{$names};
4263: } else {
4264: my %loadnames=&Apache::lonnet::get('environment',
4265: ['notification','critnotification',
4266: 'permanentemail'],
4267: $udom,$uname);
4268: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
4269: return %loadnames;
4270: }
4271: }
4272:
4273: sub flush_email_cache {
4274: my ($uname,$udom)=@_;
4275: if (!$udom) { $udom =$env{'user.domain'}; }
4276: if (!$uname) { $uname=$env{'user.name'}; }
4277: return if ($udom eq 'public' && $uname eq 'public');
4278: my $id=$uname.':'.$udom;
4279: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
4280: }
4281:
4282: # -------------------------------------------------------------------- getlangs
4283:
4284: =pod
4285:
4286: =item * &getlangs($uname,$udom)
4287:
4288: Gets a user's language preference and returns it as a hash with key:
4289: language.
4290:
4291: =cut
4292:
4293:
4294: sub getlangs {
4295: my ($uname,$udom) = @_;
4296: if (!$udom) { $udom =$env{'user.domain'}; }
4297: if (!$uname) { $uname=$env{'user.name'}; }
4298: my $id=$uname.':'.$udom;
4299: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
4300: if ($cached) {
4301: return %{$langs};
4302: } else {
4303: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
4304: $udom,$uname);
4305: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
4306: return %loadlangs;
4307: }
4308: }
4309:
4310: sub flush_langs_cache {
4311: my ($uname,$udom)=@_;
4312: if (!$udom) { $udom =$env{'user.domain'}; }
4313: if (!$uname) { $uname=$env{'user.name'}; }
4314: return if ($udom eq 'public' && $uname eq 'public');
4315: my $id=$uname.':'.$udom;
4316: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
4317: }
4318:
4319: # ------------------------------------------------------------------ Screenname
4320:
4321: =pod
4322:
4323: =item * &screenname($uname,$udom)
4324:
4325: Gets a users screenname and returns it as a string
4326:
4327: =cut
4328:
4329: sub screenname {
4330: my ($uname,$udom)=@_;
4331: if ($uname eq $env{'user.name'} &&
4332: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
4333: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
4334: return $names{'screenname'};
4335: }
4336:
4337:
4338: # ------------------------------------------------------------- Confirm Wrapper
4339: =pod
4340:
4341: =item * &confirmwrapper($message)
4342:
4343: Wrap messages about completion of operation in box
4344:
4345: =cut
4346:
4347: sub confirmwrapper {
4348: my ($message)=@_;
4349: if ($message) {
4350: return "\n".'<div class="LC_confirm_box">'."\n"
4351: .$message."\n"
4352: .'</div>'."\n";
4353: } else {
4354: return $message;
4355: }
4356: }
4357:
4358: # ------------------------------------------------------------- Message Wrapper
4359:
4360: sub messagewrapper {
4361: my ($link,$username,$domain,$subject,$text)=@_;
4362: return
4363: '<a href="/adm/email?compose=individual&'.
4364: 'recname='.$username.'&recdom='.$domain.
4365: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
4366: 'title="'.&mt('Send message').'">'.$link.'</a>';
4367: }
4368:
4369: # --------------------------------------------------------------- Notes Wrapper
4370:
4371: sub noteswrapper {
4372: my ($link,$un,$do)=@_;
4373: return
4374: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
4375: }
4376:
4377: # ------------------------------------------------------------- Aboutme Wrapper
4378:
4379: sub aboutmewrapper {
4380: my ($link,$username,$domain,$target,$class)=@_;
4381: if (!defined($username) && !defined($domain)) {
4382: return;
4383: }
4384: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
4385: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
4386: }
4387:
4388: # ------------------------------------------------------------ Syllabus Wrapper
4389:
4390: sub syllabuswrapper {
4391: my ($linktext,$coursedir,$domain)=@_;
4392: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
4393: }
4394:
4395: # -----------------------------------------------------------------------------
4396:
4397: sub aboutme_on {
4398: my ($uname,$udom)=@_;
4399: unless ($uname) { $uname=$env{'user.name'}; }
4400: unless ($udom) { $udom=$env{'user.domain'}; }
4401: return if ($udom eq 'public' && $uname eq 'public');
4402: my $hashkey=$uname.':'.$udom;
4403: my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
4404: if ($cached) {
4405: return $aboutme;
4406: }
4407: $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
4408: &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
4409: return $aboutme;
4410: }
4411:
4412: sub devalidate_aboutme_cache {
4413: my ($uname,$udom)=@_;
4414: if (!$udom) { $udom =$env{'user.domain'}; }
4415: if (!$uname) { $uname=$env{'user.name'}; }
4416: return if ($udom eq 'public' && $uname eq 'public');
4417: my $id=$uname.':'.$udom;
4418: &Apache::lonnet::devalidate_cache_new('aboutme',$id);
4419: }
4420:
4421: sub track_student_link {
4422: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
4423: my $link ="/adm/trackstudent?";
4424: my $title = 'View recent activity';
4425: if (defined($sname) && $sname !~ /^\s*$/ &&
4426: defined($sdom) && $sdom !~ /^\s*$/) {
4427: $link .= "selected_student=$sname:$sdom";
4428: $title .= ' of this student';
4429: }
4430: if (defined($target) && $target !~ /^\s*$/) {
4431: $target = qq{target="$target"};
4432: } else {
4433: $target = '';
4434: }
4435: if ($start) { $link.='&start='.$start; }
4436: if ($only_body) { $link .= '&only_body=1'; }
4437: $title = &mt($title);
4438: $linktext = &mt($linktext);
4439: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
4440: &help_open_topic('View_recent_activity');
4441: }
4442:
4443: sub slot_reservations_link {
4444: my ($linktext,$sname,$sdom,$target) = @_;
4445: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
4446: my $title = 'View slot reservation history';
4447: if (defined($sname) && $sname !~ /^\s*$/ &&
4448: defined($sdom) && $sdom !~ /^\s*$/) {
4449: $link .= "&uname=$sname&udom=$sdom";
4450: $title .= ' of this student';
4451: }
4452: if (defined($target) && $target !~ /^\s*$/) {
4453: $target = qq{target="$target"};
4454: } else {
4455: $target = '';
4456: }
4457: $title = &mt($title);
4458: $linktext = &mt($linktext);
4459: return qq{<a href="$link" title="$title" $target>$linktext</a>};
4460: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
4461:
4462: }
4463:
4464: # ===================================================== Display a student photo
4465:
4466:
4467: sub student_image_tag {
4468: my ($domain,$user)=@_;
4469: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
4470: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
4471: return '<img src="'.$imgsrc.'" align="right" />';
4472: } else {
4473: return '';
4474: }
4475: }
4476:
4477: =pod
4478:
4479: =back
4480:
4481: =head1 Access .tab File Data
4482:
4483: =over 4
4484:
4485: =item * &languageids()
4486:
4487: returns list of all language ids
4488:
4489: =cut
4490:
4491: sub languageids {
4492: return sort(keys(%language));
4493: }
4494:
4495: =pod
4496:
4497: =item * &languagedescription()
4498:
4499: returns description of a specified language id
4500:
4501: =cut
4502:
4503: sub languagedescription {
4504: my $code=shift;
4505: return ($supported_language{$code}?'* ':'').
4506: $language{$code}.
4507: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4508: }
4509:
4510: =pod
4511:
4512: =item * &plainlanguagedescription
4513:
4514: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4515: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4516:
4517: =cut
4518:
4519: sub plainlanguagedescription {
4520: my $code=shift;
4521: return $language{$code};
4522: }
4523:
4524: =pod
4525:
4526: =item * &supportedlanguagecode
4527:
4528: Returns the supported language code (e.g. sptutf maps to pt) given a language
4529: code.
4530:
4531: =cut
4532:
4533: sub supportedlanguagecode {
4534: my $code=shift;
4535: return $supported_language{$code};
4536: }
4537:
4538: =pod
4539:
4540: =item * &latexlanguage()
4541:
4542: Given a language key code returns the correspondnig language to use
4543: to select the correct hyphenation on LaTeX printouts. This is undef if there
4544: is no supported hyphenation for the language code.
4545:
4546: =cut
4547:
4548: sub latexlanguage {
4549: my $code = shift;
4550: return $latex_language{$code};
4551: }
4552:
4553: =pod
4554:
4555: =item * &latexhyphenation()
4556:
4557: Same as above but what's supplied is the language as it might be stored
4558: in the metadata.
4559:
4560: =cut
4561:
4562: sub latexhyphenation {
4563: my $key = shift;
4564: return $latex_language_bykey{$key};
4565: }
4566:
4567: =pod
4568:
4569: =item * ©rightids()
4570:
4571: returns list of all copyrights
4572:
4573: =cut
4574:
4575: sub copyrightids {
4576: return sort(keys(%cprtag));
4577: }
4578:
4579: =pod
4580:
4581: =item * ©rightdescription()
4582:
4583: returns description of a specified copyright id
4584:
4585: =cut
4586:
4587: sub copyrightdescription {
4588: return &mt($cprtag{shift(@_)});
4589: }
4590:
4591: =pod
4592:
4593: =item * &source_copyrightids()
4594:
4595: returns list of all source copyrights
4596:
4597: =cut
4598:
4599: sub source_copyrightids {
4600: return sort(keys(%scprtag));
4601: }
4602:
4603: =pod
4604:
4605: =item * &source_copyrightdescription()
4606:
4607: returns description of a specified source copyright id
4608:
4609: =cut
4610:
4611: sub source_copyrightdescription {
4612: return &mt($scprtag{shift(@_)});
4613: }
4614:
4615: =pod
4616:
4617: =item * &filecategories()
4618:
4619: returns list of all file categories
4620:
4621: =cut
4622:
4623: sub filecategories {
4624: return sort(keys(%category_extensions));
4625: }
4626:
4627: =pod
4628:
4629: =item * &filecategorytypes()
4630:
4631: returns list of file types belonging to a given file
4632: category
4633:
4634: =cut
4635:
4636: sub filecategorytypes {
4637: my ($cat) = @_;
4638: if (ref($category_extensions{lc($cat)}) eq 'ARRAY') {
4639: return @{$category_extensions{lc($cat)}};
4640: } else {
4641: return ();
4642: }
4643: }
4644:
4645: =pod
4646:
4647: =item * &fileembstyle()
4648:
4649: returns embedding style for a specified file type
4650:
4651: =cut
4652:
4653: sub fileembstyle {
4654: return $fe{lc(shift(@_))};
4655: }
4656:
4657: sub filemimetype {
4658: return $fm{lc(shift(@_))};
4659: }
4660:
4661:
4662: sub filecategoryselect {
4663: my ($name,$value)=@_;
4664: return &select_form($value,$name,
4665: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4666: }
4667:
4668: =pod
4669:
4670: =item * &filedescription()
4671:
4672: returns description for a specified file type
4673:
4674: =cut
4675:
4676: sub filedescription {
4677: my $file_description = $fd{lc(shift())};
4678: $file_description =~ s:([\[\]]):~$1:g;
4679: return &mt($file_description);
4680: }
4681:
4682: =pod
4683:
4684: =item * &filedescriptionex()
4685:
4686: returns description for a specified file type with
4687: extra formatting
4688:
4689: =cut
4690:
4691: sub filedescriptionex {
4692: my $ex=shift;
4693: my $file_description = $fd{lc($ex)};
4694: $file_description =~ s:([\[\]]):~$1:g;
4695: return '.'.$ex.' '.&mt($file_description);
4696: }
4697:
4698: # End of .tab access
4699: =pod
4700:
4701: =back
4702:
4703: =cut
4704:
4705: # ------------------------------------------------------------------ File Types
4706: sub fileextensions {
4707: return sort(keys(%fe));
4708: }
4709:
4710: # ----------------------------------------------------------- Display Languages
4711: # returns a hash with all desired display languages
4712: #
4713:
4714: sub display_languages {
4715: my %languages=();
4716: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4717: $languages{$lang}=1;
4718: }
4719: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4720: if ($env{'form.displaylanguage'}) {
4721: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4722: $languages{$lang}=1;
4723: }
4724: }
4725: return %languages;
4726: }
4727:
4728: sub languages {
4729: my ($possible_langs) = @_;
4730: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4731: if (!ref($possible_langs)) {
4732: if( wantarray ) {
4733: return @preferred_langs;
4734: } else {
4735: return $preferred_langs[0];
4736: }
4737: }
4738: my %possibilities = map { $_ => 1 } (@$possible_langs);
4739: my @preferred_possibilities;
4740: foreach my $preferred_lang (@preferred_langs) {
4741: if (exists($possibilities{$preferred_lang})) {
4742: push(@preferred_possibilities, $preferred_lang);
4743: }
4744: }
4745: if( wantarray ) {
4746: return @preferred_possibilities;
4747: }
4748: return $preferred_possibilities[0];
4749: }
4750:
4751: sub user_lang {
4752: my ($touname,$toudom,$fromcid) = @_;
4753: my @userlangs;
4754: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4755: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4756: $env{'course.'.$fromcid.'.languages'}));
4757: } else {
4758: my %langhash = &getlangs($touname,$toudom);
4759: if ($langhash{'languages'} ne '') {
4760: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4761: } else {
4762: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4763: if ($domdefs{'lang_def'} ne '') {
4764: @userlangs = ($domdefs{'lang_def'});
4765: }
4766: }
4767: }
4768: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4769: my $user_lh = Apache::localize->get_handle(@languages);
4770: return $user_lh;
4771: }
4772:
4773:
4774: ###############################################################
4775: ## Student Answer Attempts ##
4776: ###############################################################
4777:
4778: =pod
4779:
4780: =head1 Alternate Problem Views
4781:
4782: =over 4
4783:
4784: =item * &get_previous_attempt($symb, $username, $domain, $course,
4785: $getattempt, $regexp, $gradesub, $usec, $identifier)
4786:
4787: Return string with previous attempt on problem. Arguments:
4788:
4789: =over 4
4790:
4791: =item * $symb: Problem, including path
4792:
4793: =item * $username: username of the desired student
4794:
4795: =item * $domain: domain of the desired student
4796:
4797: =item * $course: Course ID
4798:
4799: =item * $getattempt: Leave blank for all attempts, otherwise put
4800: something
4801:
4802: =item * $regexp: if string matches this regexp, the string will be
4803: sent to $gradesub
4804:
4805: =item * $gradesub: routine that processes the string if it matches $regexp
4806:
4807: =item * $usec: section of the desired student
4808:
4809: =item * $identifier: counter for student (multiple students one problem) or
4810: problem (one student; whole sequence).
4811:
4812: =back
4813:
4814: The output string is a table containing all desired attempts, if any.
4815:
4816: =cut
4817:
4818: sub get_previous_attempt {
4819: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4820: my $prevattempts='';
4821: no strict 'refs';
4822: if ($symb) {
4823: my (%returnhash)=
4824: &Apache::lonnet::restore($symb,$course,$domain,$username);
4825: if ($returnhash{'version'}) {
4826: my %lasthash=();
4827: my $version;
4828: for ($version=1;$version<=$returnhash{'version'};$version++) {
4829: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4830: if ($key =~ /\.rawrndseed$/) {
4831: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4832: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4833: } else {
4834: $lasthash{$key}=$returnhash{$version.':'.$key};
4835: }
4836: }
4837: }
4838: $prevattempts=&start_data_table().&start_data_table_header_row();
4839: $prevattempts.='<th>'.&mt('History').'</th>';
4840: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4841: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4842: foreach my $key (sort(keys(%lasthash))) {
4843: my ($ign,@parts) = split(/\./,$key);
4844: if ($#parts > 0) {
4845: my $data=$parts[-1];
4846: next if ($data eq 'foilorder');
4847: pop(@parts);
4848: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4849: if ($data eq 'type') {
4850: unless ($showsurv) {
4851: my $id = join(',',@parts);
4852: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4853: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4854: $lasthidden{$ign.'.'.$id} = 1;
4855: }
4856: }
4857: if ($identifier ne '') {
4858: my $id = join(',',@parts);
4859: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4860: $domain,$username,$usec,undef,$course) =~ /^no/) {
4861: $hidestatus{$ign.'.'.$id} = 1;
4862: }
4863: }
4864: } elsif ($data eq 'regrader') {
4865: if (($identifier ne '') && (@parts)) {
4866: my $id = join(',',@parts);
4867: $regraded{$ign.'.'.$id} = 1;
4868: }
4869: }
4870: } else {
4871: if ($#parts == 0) {
4872: $prevattempts.='<th>'.$parts[0].'</th>';
4873: } else {
4874: $prevattempts.='<th>'.$ign.'</th>';
4875: }
4876: }
4877: }
4878: $prevattempts.=&end_data_table_header_row();
4879: if ($getattempt eq '') {
4880: my (%solved,%resets,%probstatus);
4881: if (($identifier ne '') && (keys(%regraded) > 0)) {
4882: for ($version=1;$version<=$returnhash{'version'};$version++) {
4883: foreach my $id (keys(%regraded)) {
4884: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4885: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4886: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4887: push(@{$resets{$id}},$version);
4888: }
4889: }
4890: }
4891: }
4892: for ($version=1;$version<=$returnhash{'version'};$version++) {
4893: my (@hidden,@unsolved);
4894: if (%typeparts) {
4895: foreach my $id (keys(%typeparts)) {
4896: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4897: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4898: push(@hidden,$id);
4899: } elsif ($identifier ne '') {
4900: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4901: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4902: ($hidestatus{$id})) {
4903: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4904: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4905: push(@{$solved{$id}},$version);
4906: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4907: (ref($solved{$id}) eq 'ARRAY')) {
4908: my $skip;
4909: if (ref($resets{$id}) eq 'ARRAY') {
4910: foreach my $reset (@{$resets{$id}}) {
4911: if ($reset > $solved{$id}[-1]) {
4912: $skip=1;
4913: last;
4914: }
4915: }
4916: }
4917: unless ($skip) {
4918: my ($ign,$partslist) = split(/\./,$id,2);
4919: push(@unsolved,$partslist);
4920: }
4921: }
4922: }
4923: }
4924: }
4925: }
4926: $prevattempts.=&start_data_table_row().
4927: '<td>'.&mt('Transaction [_1]',$version);
4928: if (@unsolved) {
4929: $prevattempts .= '<span class="LC_nobreak"><label>'.
4930: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4931: &mt('Hide').'</label></span>';
4932: }
4933: $prevattempts .= '</td>';
4934: if (@hidden) {
4935: foreach my $key (sort(keys(%lasthash))) {
4936: next if ($key =~ /\.foilorder$/);
4937: my $hide;
4938: foreach my $id (@hidden) {
4939: if ($key =~ /^\Q$id\E/) {
4940: $hide = 1;
4941: last;
4942: }
4943: }
4944: if ($hide) {
4945: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4946: if (($data eq 'award') || ($data eq 'awarddetail')) {
4947: my $value = &format_previous_attempt_value($key,
4948: $returnhash{$version.':'.$key});
4949: $prevattempts.='<td>'.$value.' </td>';
4950: } else {
4951: $prevattempts.='<td> </td>';
4952: }
4953: } else {
4954: if ($key =~ /\./) {
4955: my $value = $returnhash{$version.':'.$key};
4956: if ($key =~ /\.rndseed$/) {
4957: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4958: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4959: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4960: }
4961: }
4962: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4963: ' </td>';
4964: } else {
4965: $prevattempts.='<td> </td>';
4966: }
4967: }
4968: }
4969: } else {
4970: foreach my $key (sort(keys(%lasthash))) {
4971: next if ($key =~ /\.foilorder$/);
4972: my $value = $returnhash{$version.':'.$key};
4973: if ($key =~ /\.rndseed$/) {
4974: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4975: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4976: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4977: }
4978: }
4979: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4980: ' </td>';
4981: }
4982: }
4983: $prevattempts.=&end_data_table_row();
4984: }
4985: }
4986: my @currhidden = keys(%lasthidden);
4987: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4988: foreach my $key (sort(keys(%lasthash))) {
4989: next if ($key =~ /\.foilorder$/);
4990: if (%typeparts) {
4991: my $hidden;
4992: foreach my $id (@currhidden) {
4993: if ($key =~ /^\Q$id\E/) {
4994: $hidden = 1;
4995: last;
4996: }
4997: }
4998: if ($hidden) {
4999: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
5000: if (($data eq 'award') || ($data eq 'awarddetail')) {
5001: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5002: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5003: $value = &$gradesub($value);
5004: }
5005: $prevattempts.='<td>'. $value.' </td>';
5006: } else {
5007: $prevattempts.='<td> </td>';
5008: }
5009: } else {
5010: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5011: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5012: $value = &$gradesub($value);
5013: }
5014: $prevattempts.='<td>'.$value.' </td>';
5015: }
5016: } else {
5017: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5018: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5019: $value = &$gradesub($value);
5020: }
5021: $prevattempts.='<td>'.$value.' </td>';
5022: }
5023: }
5024: $prevattempts.= &end_data_table_row().&end_data_table();
5025: } else {
5026: my $msg;
5027: if ($symb =~ /ext\.tool$/) {
5028: $msg = &mt('No grade passed back.');
5029: } else {
5030: $msg = &mt('Nothing submitted - no attempts.');
5031: }
5032: $prevattempts=
5033: &start_data_table().&start_data_table_row().
5034: '<td>'.$msg.'</td>'.
5035: &end_data_table_row().&end_data_table();
5036: }
5037: } else {
5038: $prevattempts=
5039: &start_data_table().&start_data_table_row().
5040: '<td>'.&mt('No data.').'</td>'.
5041: &end_data_table_row().&end_data_table();
5042: }
5043: }
5044:
5045: sub format_previous_attempt_value {
5046: my ($key,$value) = @_;
5047: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
5048: $value = &Apache::lonlocal::locallocaltime($value);
5049: } elsif (ref($value) eq 'ARRAY') {
5050: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
5051: } elsif ($key =~ /answerstring$/) {
5052: my %answers = &Apache::lonnet::str2hash($value);
5053: my @answer = %answers;
5054: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
5055: my @anskeys = sort(keys(%answers));
5056: if (@anskeys == 1) {
5057: my $answer = $answers{$anskeys[0]};
5058: if ($answer =~ m{\0}) {
5059: $answer =~ s{\0}{,}g;
5060: }
5061: my $tag_internal_answer_name = 'INTERNAL';
5062: if ($anskeys[0] eq $tag_internal_answer_name) {
5063: $value = $answer;
5064: } else {
5065: $value = $anskeys[0].'='.$answer;
5066: }
5067: } else {
5068: foreach my $ans (@anskeys) {
5069: my $answer = $answers{$ans};
5070: if ($answer =~ m{\0}) {
5071: $answer =~ s{\0}{,}g;
5072: }
5073: $value .= $ans.'='.$answer.'<br />';;
5074: }
5075: }
5076: } else {
5077: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
5078: }
5079: return $value;
5080: }
5081:
5082:
5083: sub relative_to_absolute {
5084: my ($url,$output)=@_;
5085: my $parser=HTML::TokeParser->new(\$output);
5086: my $token;
5087: my $thisdir=$url;
5088: my @rlinks=();
5089: while ($token=$parser->get_token) {
5090: if ($token->[0] eq 'S') {
5091: if ($token->[1] eq 'a') {
5092: if ($token->[2]->{'href'}) {
5093: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
5094: }
5095: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
5096: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
5097: } elsif ($token->[1] eq 'base') {
5098: $thisdir=$token->[2]->{'href'};
5099: }
5100: }
5101: }
5102: $thisdir=~s-/[^/]*$--;
5103: foreach my $link (@rlinks) {
5104: unless (($link=~/^https?\:\/\//i) ||
5105: ($link=~/^\//) ||
5106: ($link=~/^javascript:/i) ||
5107: ($link=~/^mailto:/i) ||
5108: ($link=~/^\#/)) {
5109: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
5110: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
5111: }
5112: }
5113: # -------------------------------------------------- Deal with Applet codebases
5114: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
5115: return $output;
5116: }
5117:
5118: =pod
5119:
5120: =item * &get_student_view()
5121:
5122: show a snapshot of what student was looking at
5123:
5124: =cut
5125:
5126: sub get_student_view {
5127: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
5128: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
5129: my (%form);
5130: my @elements=('symb','courseid','domain','username');
5131: foreach my $element (@elements) {
5132: $form{'grade_'.$element}=eval '$'.$element #'
5133: }
5134: if (defined($moreenv)) {
5135: %form=(%form,%{$moreenv});
5136: }
5137: if (defined($target)) { $form{'grade_target'} = $target; }
5138: $feedurl=&Apache::lonnet::clutter($feedurl);
5139: if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
5140: $feedurl =~ s{^/adm/wrapper}{};
5141: }
5142: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
5143: $userview=~s/\<body[^\>]*\>//gi;
5144: $userview=~s/\<\/body\>//gi;
5145: $userview=~s/\<html\>//gi;
5146: $userview=~s/\<\/html\>//gi;
5147: $userview=~s/\<head\>//gi;
5148: $userview=~s/\<\/head\>//gi;
5149: $userview=~s/action\s*\=/would_be_action\=/gi;
5150: $userview=&relative_to_absolute($feedurl,$userview);
5151: if (wantarray) {
5152: return ($userview,$response);
5153: } else {
5154: return $userview;
5155: }
5156: }
5157:
5158: sub get_student_view_with_retries {
5159: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
5160:
5161: my $ok = 0; # True if we got a good response.
5162: my $content;
5163: my $response;
5164:
5165: # Try to get the student_view done. within the retries count:
5166:
5167: do {
5168: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
5169: $ok = $response->is_success;
5170: if (!$ok) {
5171: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
5172: }
5173: $retries--;
5174: } while (!$ok && ($retries > 0));
5175:
5176: if (!$ok) {
5177: $content = ''; # On error return an empty content.
5178: }
5179: if (wantarray) {
5180: return ($content, $response);
5181: } else {
5182: return $content;
5183: }
5184: }
5185:
5186: sub css_links {
5187: my ($currsymb,$level) = @_;
5188: my ($links,@symbs,%cssrefs,%httpref);
5189: if ($level eq 'map') {
5190: my $navmap = Apache::lonnavmaps::navmap->new();
5191: if (ref($navmap)) {
5192: my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
5193: my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
5194: foreach my $res (@resources) {
5195: if (ref($res) && $res->symb()) {
5196: push(@symbs,$res->symb());
5197: }
5198: }
5199: }
5200: } else {
5201: @symbs = ($currsymb);
5202: }
5203: foreach my $symb (@symbs) {
5204: my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
5205: if ($css_href =~ /\S/) {
5206: unless ($css_href =~ m{https?://}) {
5207: my $url = (&Apache::lonnet::decode_symb($symb))[-1];
5208: my $proburl = &Apache::lonnet::clutter($url);
5209: my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
5210: unless ($css_href =~ m{^/}) {
5211: $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
5212: }
5213: if ($css_href =~ m{^/(res|uploaded)/}) {
5214: unless (($httpref{'httpref.'.$css_href}) ||
5215: (&Apache::lonnet::is_on_map($css_href))) {
5216: my $thisurl = $proburl;
5217: if ($env{'httpref.'.$proburl}) {
5218: $thisurl = $env{'httpref.'.$proburl};
5219: }
5220: $httpref{'httpref.'.$css_href} = $thisurl;
5221: }
5222: }
5223: }
5224: $cssrefs{$css_href} = 1;
5225: }
5226: }
5227: if (keys(%httpref)) {
5228: &Apache::lonnet::appenv(\%httpref);
5229: }
5230: if (keys(%cssrefs)) {
5231: foreach my $css_href (keys(%cssrefs)) {
5232: next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
5233: $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
5234: }
5235: }
5236: return $links;
5237: }
5238:
5239: =pod
5240:
5241: =item * &get_student_answers()
5242:
5243: show a snapshot of how student was answering problem
5244:
5245: =cut
5246:
5247: sub get_student_answers {
5248: my ($symb,$username,$domain,$courseid,%form) = @_;
5249: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
5250: my (%moreenv);
5251: my @elements=('symb','courseid','domain','username');
5252: foreach my $element (@elements) {
5253: $moreenv{'grade_'.$element}=eval '$'.$element #'
5254: }
5255: $moreenv{'grade_target'}='answer';
5256: %moreenv=(%form,%moreenv);
5257: $feedurl = &Apache::lonnet::clutter($feedurl);
5258: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
5259: return $userview;
5260: }
5261:
5262: =pod
5263:
5264: =item * &submlink()
5265:
5266: Inputs: $text $uname $udom $symb $target
5267:
5268: Returns: A link to grades.pm such as to see the SUBM view of a student
5269:
5270: =cut
5271:
5272: ###############################################
5273: sub submlink {
5274: my ($text,$uname,$udom,$symb,$target)=@_;
5275: if (!($uname && $udom)) {
5276: (my $cursymb, my $courseid,$udom,$uname)=
5277: &Apache::lonnet::whichuser($symb);
5278: if (!$symb) { $symb=$cursymb; }
5279: }
5280: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5281: $symb=&escape($symb);
5282: if ($target) { $target=" target=\"$target\""; }
5283: return
5284: '<a href="/adm/grades?command=submission'.
5285: '&symb='.$symb.
5286: '&student='.$uname.
5287: '&userdom='.$udom.'"'.
5288: $target.'>'.$text.'</a>';
5289: }
5290: ##############################################
5291:
5292: =pod
5293:
5294: =item * &pgrdlink()
5295:
5296: Inputs: $text $uname $udom $symb $target
5297:
5298: Returns: A link to grades.pm such as to see the PGRD view of a student
5299:
5300: =cut
5301:
5302: ###############################################
5303: sub pgrdlink {
5304: my $link=&submlink(@_);
5305: $link=~s/(&command=submission)/$1&showgrading=yes/;
5306: return $link;
5307: }
5308: ##############################################
5309:
5310: =pod
5311:
5312: =item * &pprmlink()
5313:
5314: Inputs: $text $uname $udom $symb $target
5315:
5316: Returns: A link to parmset.pm such as to see the PPRM view of a
5317: student and a specific resource
5318:
5319: =cut
5320:
5321: ###############################################
5322: sub pprmlink {
5323: my ($text,$uname,$udom,$symb,$target)=@_;
5324: if (!($uname && $udom)) {
5325: (my $cursymb, my $courseid,$udom,$uname)=
5326: &Apache::lonnet::whichuser($symb);
5327: if (!$symb) { $symb=$cursymb; }
5328: }
5329: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5330: $symb=&escape($symb);
5331: if ($target) { $target="target=\"$target\""; }
5332: return '<a href="/adm/parmset?command=set&'.
5333: 'symb='.$symb.'&uname='.$uname.
5334: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
5335: }
5336: ##############################################
5337:
5338: =pod
5339:
5340: =back
5341:
5342: =cut
5343:
5344: ###############################################
5345:
5346:
5347: sub timehash {
5348: my ($thistime) = @_;
5349: my $timezone = &Apache::lonlocal::gettimezone();
5350: my $dt = DateTime->from_epoch(epoch => $thistime)
5351: ->set_time_zone($timezone);
5352: my $wday = $dt->day_of_week();
5353: if ($wday == 7) { $wday = 0; }
5354: return ( 'second' => $dt->second(),
5355: 'minute' => $dt->minute(),
5356: 'hour' => $dt->hour(),
5357: 'day' => $dt->day_of_month(),
5358: 'month' => $dt->month(),
5359: 'year' => $dt->year(),
5360: 'weekday' => $wday,
5361: 'dayyear' => $dt->day_of_year(),
5362: 'dlsav' => $dt->is_dst() );
5363: }
5364:
5365: sub utc_string {
5366: my ($date)=@_;
5367: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
5368: }
5369:
5370: sub maketime {
5371: my %th=@_;
5372: my ($epoch_time,$timezone,$dt);
5373: $timezone = &Apache::lonlocal::gettimezone();
5374: eval {
5375: $dt = DateTime->new( year => $th{'year'},
5376: month => $th{'month'},
5377: day => $th{'day'},
5378: hour => $th{'hour'},
5379: minute => $th{'minute'},
5380: second => $th{'second'},
5381: time_zone => $timezone,
5382: );
5383: };
5384: if (!$@) {
5385: $epoch_time = $dt->epoch;
5386: if ($epoch_time) {
5387: return $epoch_time;
5388: }
5389: }
5390: return POSIX::mktime(
5391: ($th{'seconds'},$th{'minutes'},$th{'hours'},
5392: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
5393: }
5394:
5395: #########################################
5396:
5397: sub findallcourses {
5398: my ($roles,$uname,$udom) = @_;
5399: my %roles;
5400: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
5401: my %courses;
5402: my $now=time;
5403: if (!defined($uname)) {
5404: $uname = $env{'user.name'};
5405: }
5406: if (!defined($udom)) {
5407: $udom = $env{'user.domain'};
5408: }
5409: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
5410: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
5411: if (!%roles) {
5412: %roles = (
5413: cc => 1,
5414: co => 1,
5415: in => 1,
5416: ep => 1,
5417: ta => 1,
5418: cr => 1,
5419: st => 1,
5420: );
5421: }
5422: foreach my $entry (keys(%roleshash)) {
5423: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
5424: if ($trole =~ /^cr/) {
5425: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
5426: } else {
5427: next if (!exists($roles{$trole}));
5428: }
5429: if ($tend) {
5430: next if ($tend < $now);
5431: }
5432: if ($tstart) {
5433: next if ($tstart > $now);
5434: }
5435: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
5436: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
5437: my $value = $trole.'/'.$cdom.'/';
5438: if ($secpart eq '') {
5439: ($cnum,$role) = split(/_/,$cnumpart);
5440: $sec = 'none';
5441: $value .= $cnum.'/';
5442: } else {
5443: $cnum = $cnumpart;
5444: ($sec,$role) = split(/_/,$secpart);
5445: $value .= $cnum.'/'.$sec;
5446: }
5447: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5448: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5449: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5450: }
5451: } else {
5452: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5453: }
5454: }
5455: } else {
5456: foreach my $key (keys(%env)) {
5457: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
5458: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
5459: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
5460: next if ($role eq 'ca' || $role eq 'aa');
5461: next if (%roles && !exists($roles{$role}));
5462: my ($starttime,$endtime)=split(/\./,$env{$key});
5463: my $active=1;
5464: if ($starttime) {
5465: if ($now<$starttime) { $active=0; }
5466: }
5467: if ($endtime) {
5468: if ($now>$endtime) { $active=0; }
5469: }
5470: if ($active) {
5471: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
5472: if ($sec eq '') {
5473: $sec = 'none';
5474: } else {
5475: $value .= $sec;
5476: }
5477: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5478: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5479: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5480: }
5481: } else {
5482: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5483: }
5484: }
5485: }
5486: }
5487: }
5488: return %courses;
5489: }
5490:
5491: ###############################################
5492:
5493: sub blockcheck {
5494: my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5495: unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
5496: my ($has_evb,$check_ipaccess);
5497: my $dom = $env{'user.domain'};
5498: if ($env{'request.course.id'}) {
5499: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5500: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5501: my $checkrole = "cm./$cdom/$cnum";
5502: my $sec = $env{'request.course.sec'};
5503: if ($sec ne '') {
5504: $checkrole .= "/$sec";
5505: }
5506: if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
5507: ($env{'request.role'} !~ /^st/)) {
5508: $has_evb = 1;
5509: }
5510: unless ($has_evb) {
5511: if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
5512: ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
5513: if ($udom eq $cdom) {
5514: $check_ipaccess = 1;
5515: }
5516: }
5517: }
5518: } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
5519: ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
5520: my $checkrole;
5521: if ($env{'request.role.domain'} eq '') {
5522: $checkrole = "cm./$env{'user.domain'}/";
5523: } else {
5524: $checkrole = "cm./$env{'request.role.domain'}/";
5525: }
5526: if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
5527: $has_evb = 1;
5528: }
5529: }
5530: unless ($has_evb || $check_ipaccess) {
5531: my @machinedoms = &Apache::lonnet::current_machine_domains();
5532: if (($dom eq 'public') && ($activity eq 'port')) {
5533: $dom = $udom;
5534: }
5535: if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
5536: $check_ipaccess = 1;
5537: } else {
5538: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
5539: my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
5540: my $prim = &Apache::lonnet::domain($dom,'primary');
5541: my $intdom = &Apache::lonnet::internet_dom($prim);
5542: if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
5543: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
5544: $check_ipaccess = 1;
5545: }
5546: }
5547: }
5548: }
5549: if ($check_ipaccess) {
5550: my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
5551: unless (defined($cached)) {
5552: my %domconfig =
5553: &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
5554: $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
5555: }
5556: if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
5557: foreach my $id (keys(%{$ipaccessref})) {
5558: if (ref($ipaccessref->{$id}) eq 'HASH') {
5559: my $range = $ipaccessref->{$id}->{'ip'};
5560: if ($range) {
5561: if (&Apache::lonnet::ip_match($clientip,$range)) {
5562: if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
5563: if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
5564: return ('','','',$id,$dom);
5565: last;
5566: }
5567: }
5568: }
5569: }
5570: }
5571: }
5572: }
5573: }
5574: if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5575: return ();
5576: }
5577: }
5578: if (defined($udom) && defined($uname)) {
5579: # If uname and udom are for a course, check for blocks in the course.
5580: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
5581: my ($startblock,$endblock,$triggerblock) =
5582: &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
5583: return ($startblock,$endblock,$triggerblock);
5584: }
5585: } else {
5586: $udom = $env{'user.domain'};
5587: $uname = $env{'user.name'};
5588: }
5589:
5590: my $startblock = 0;
5591: my $endblock = 0;
5592: my $triggerblock = '';
5593: my %live_courses;
5594: unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5595: %live_courses = &findallcourses(undef,$uname,$udom);
5596: }
5597:
5598: # If uname is for a user, and activity is course-specific, i.e.,
5599: # boards, chat or groups, check for blocking in current course only.
5600:
5601: if (($activity eq 'boards' || $activity eq 'chat' ||
5602: $activity eq 'groups' || $activity eq 'printout' ||
5603: $activity eq 'search' || $activity eq 'reinit' ||
5604: $activity eq 'alert') &&
5605: ($env{'request.course.id'})) {
5606: foreach my $key (keys(%live_courses)) {
5607: if ($key ne $env{'request.course.id'}) {
5608: delete($live_courses{$key});
5609: }
5610: }
5611: }
5612:
5613: my $otheruser = 0;
5614: my %own_courses;
5615: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
5616: # Resource belongs to user other than current user.
5617: $otheruser = 1;
5618: # Gather courses for current user
5619: %own_courses =
5620: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
5621: }
5622:
5623: # Gather active course roles - course coordinator, instructor,
5624: # exam proctor, ta, student, or custom role.
5625:
5626: foreach my $course (keys(%live_courses)) {
5627: my ($cdom,$cnum);
5628: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5629: $cdom = $env{'course.'.$course.'.domain'};
5630: $cnum = $env{'course.'.$course.'.num'};
5631: } else {
5632: ($cdom,$cnum) = split(/_/,$course);
5633: }
5634: my $no_ownblock = 0;
5635: my $no_userblock = 0;
5636: if ($otheruser && $activity ne 'com') {
5637: # Check if current user has 'evb' priv for this
5638: if (defined($own_courses{$course})) {
5639: foreach my $sec (keys(%{$own_courses{$course}})) {
5640: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5641: if ($sec ne 'none') {
5642: $checkrole .= '/'.$sec;
5643: }
5644: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5645: $no_ownblock = 1;
5646: last;
5647: }
5648: }
5649: }
5650: # if they have 'evb' priv and are currently not playing student
5651: next if (($no_ownblock) &&
5652: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5653: }
5654: foreach my $sec (keys(%{$live_courses{$course}})) {
5655: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5656: if ($sec ne 'none') {
5657: $checkrole .= '/'.$sec;
5658: }
5659: if ($otheruser) {
5660: # Resource belongs to user other than current user.
5661: # Assemble privs for that user, and check for 'evb' priv.
5662: my (%allroles,%userroles);
5663: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5664: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5665: my ($trole,$tdom,$tnum,$tsec);
5666: if ($entry =~ /^cr/) {
5667: ($trole,$tdom,$tnum,$tsec) =
5668: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5669: } else {
5670: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5671: }
5672: my ($spec,$area,$trest);
5673: $area = '/'.$tdom.'/'.$tnum;
5674: $trest = $tnum;
5675: if ($tsec ne '') {
5676: $area .= '/'.$tsec;
5677: $trest .= '/'.$tsec;
5678: }
5679: $spec = $trole.'.'.$area;
5680: if ($trole =~ /^cr/) {
5681: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5682: $tdom,$spec,$trest,$area);
5683: } else {
5684: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5685: $tdom,$spec,$trest,$area);
5686: }
5687: }
5688: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5689: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5690: if ($1) {
5691: $no_userblock = 1;
5692: last;
5693: }
5694: }
5695: }
5696: } else {
5697: # Resource belongs to current user
5698: # Check for 'evb' priv via lonnet::allowed().
5699: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5700: $no_ownblock = 1;
5701: last;
5702: }
5703: }
5704: }
5705: # if they have the evb priv and are currently not playing student
5706: next if (($no_ownblock) &&
5707: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5708: next if ($no_userblock);
5709:
5710: # Retrieve blocking times and identity of blocker for course
5711: # of specified user, unless user has 'evb' privilege.
5712:
5713: my ($start,$end,$trigger) =
5714: &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
5715: if (($start != 0) &&
5716: (($startblock == 0) || ($startblock > $start))) {
5717: $startblock = $start;
5718: if ($trigger ne '') {
5719: $triggerblock = $trigger;
5720: }
5721: }
5722: if (($end != 0) &&
5723: (($endblock == 0) || ($endblock < $end))) {
5724: $endblock = $end;
5725: if ($trigger ne '') {
5726: $triggerblock = $trigger;
5727: }
5728: }
5729: }
5730: return ($startblock,$endblock,$triggerblock);
5731: }
5732:
5733: sub get_blocks {
5734: my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
5735: my $startblock = 0;
5736: my $endblock = 0;
5737: my $triggerblock = '';
5738: my $course = $cdom.'_'.$cnum;
5739: $setters->{$course} = {};
5740: $setters->{$course}{'staff'} = [];
5741: $setters->{$course}{'times'} = [];
5742: $setters->{$course}{'triggers'} = [];
5743: my (@blockers,%triggered);
5744: my $now = time;
5745: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5746: if ($activity eq 'docs') {
5747: my ($blocked,$nosymbcache,$noenccheck);
5748: if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
5749: $blocked = 1;
5750: $nosymbcache = 1;
5751: $noenccheck = 1;
5752: }
5753: @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
5754: foreach my $block (@blockers) {
5755: if ($block =~ /^firstaccess____(.+)$/) {
5756: my $item = $1;
5757: my $type = 'map';
5758: my $timersymb = $item;
5759: if ($item eq 'course') {
5760: $type = 'course';
5761: } elsif ($item =~ /___\d+___/) {
5762: $type = 'resource';
5763: } else {
5764: $timersymb = &Apache::lonnet::symbread($item);
5765: }
5766: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5767: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5768: $triggered{$block} = {
5769: start => $start,
5770: end => $end,
5771: type => $type,
5772: };
5773: }
5774: }
5775: } else {
5776: foreach my $block (keys(%commblocks)) {
5777: if ($block =~ m/^(\d+)____(\d+)$/) {
5778: my ($start,$end) = ($1,$2);
5779: if ($start <= time && $end >= time) {
5780: if (ref($commblocks{$block}) eq 'HASH') {
5781: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5782: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5783: unless(grep(/^\Q$block\E$/,@blockers)) {
5784: push(@blockers,$block);
5785: }
5786: }
5787: }
5788: }
5789: }
5790: } elsif ($block =~ /^firstaccess____(.+)$/) {
5791: my $item = $1;
5792: my $timersymb = $item;
5793: my $type = 'map';
5794: if ($item eq 'course') {
5795: $type = 'course';
5796: } elsif ($item =~ /___\d+___/) {
5797: $type = 'resource';
5798: } else {
5799: $timersymb = &Apache::lonnet::symbread($item);
5800: }
5801: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5802: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5803: if ($start && $end) {
5804: if (($start <= time) && ($end >= time)) {
5805: if (ref($commblocks{$block}) eq 'HASH') {
5806: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5807: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5808: unless(grep(/^\Q$block\E$/,@blockers)) {
5809: push(@blockers,$block);
5810: $triggered{$block} = {
5811: start => $start,
5812: end => $end,
5813: type => $type,
5814: };
5815: }
5816: }
5817: }
5818: }
5819: }
5820: }
5821: }
5822: }
5823: }
5824: foreach my $blocker (@blockers) {
5825: my ($staff_name,$staff_dom,$title,$blocks) =
5826: &parse_block_record($commblocks{$blocker});
5827: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5828: my ($start,$end,$triggertype);
5829: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5830: ($start,$end) = ($1,$2);
5831: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5832: $start = $triggered{$blocker}{'start'};
5833: $end = $triggered{$blocker}{'end'};
5834: $triggertype = $triggered{$blocker}{'type'};
5835: }
5836: if ($start) {
5837: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5838: if ($triggertype) {
5839: push(@{$$setters{$course}{'triggers'}},$triggertype);
5840: } else {
5841: push(@{$$setters{$course}{'triggers'}},0);
5842: }
5843: if ( ($startblock == 0) || ($startblock > $start) ) {
5844: $startblock = $start;
5845: if ($triggertype) {
5846: $triggerblock = $blocker;
5847: }
5848: }
5849: if ( ($endblock == 0) || ($endblock < $end) ) {
5850: $endblock = $end;
5851: if ($triggertype) {
5852: $triggerblock = $blocker;
5853: }
5854: }
5855: }
5856: }
5857: return ($startblock,$endblock,$triggerblock);
5858: }
5859:
5860: sub parse_block_record {
5861: my ($record) = @_;
5862: my ($setuname,$setudom,$title,$blocks);
5863: if (ref($record) eq 'HASH') {
5864: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5865: $title = &unescape($record->{'event'});
5866: $blocks = $record->{'blocks'};
5867: } else {
5868: my @data = split(/:/,$record,3);
5869: if (scalar(@data) eq 2) {
5870: $title = $data[1];
5871: ($setuname,$setudom) = split(/@/,$data[0]);
5872: } else {
5873: ($setuname,$setudom,$title) = @data;
5874: }
5875: $blocks = { 'com' => 'on' };
5876: }
5877: return ($setuname,$setudom,$title,$blocks);
5878: }
5879:
5880: sub blocking_status {
5881: my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5882: my %setters;
5883:
5884: # check for active blocking
5885: if ($clientip eq '') {
5886: $clientip = &Apache::lonnet::get_requestor_ip();
5887: }
5888: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
5889: &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
5890: my $blocked = 0;
5891: if (($startblock && $endblock) || ($by_ip)) {
5892: $blocked = 1;
5893: }
5894:
5895: # caller just wants to know whether a block is active
5896: if (!wantarray) { return $blocked; }
5897:
5898: # build a link to a popup window containing the details
5899: my $querystring = "?activity=$activity";
5900: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
5901: if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
5902: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5903: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5904: } elsif ($activity eq 'docs') {
5905: my $showurl = &Apache::lonenc::check_encrypt($url);
5906: $querystring .= '&url='.&HTML::Entities::encode($showurl,'\'&"<>');
5907: if ($symb) {
5908: my $showsymb = &Apache::lonenc::check_encrypt($symb);
5909: $querystring .= '&symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
5910: }
5911: }
5912:
5913: my $output .= <<'END_MYBLOCK';
5914: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5915: var options = "width=" + w + ",height=" + h + ",";
5916: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5917: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5918: var newWin = window.open(url, wdwName, options);
5919: newWin.focus();
5920: }
5921: END_MYBLOCK
5922:
5923: $output = Apache::lonhtmlcommon::scripttag($output);
5924:
5925: my $popupUrl = "/adm/blockingstatus/$querystring";
5926: my $text = &mt('Communication Blocked');
5927: my $class = 'LC_comblock';
5928: if ($activity eq 'docs') {
5929: $text = &mt('Content Access Blocked');
5930: $class = '';
5931: } elsif ($activity eq 'printout') {
5932: $text = &mt('Printing Blocked');
5933: } elsif ($activity eq 'passwd') {
5934: $text = &mt('Password Changing Blocked');
5935: } elsif ($activity eq 'grades') {
5936: $text = &mt('Gradebook Blocked');
5937: } elsif ($activity eq 'search') {
5938: $text = &mt('Search Blocked');
5939: } elsif ($activity eq 'alert') {
5940: $text = &mt('Checking Critical Messages Blocked');
5941: } elsif ($activity eq 'reinit') {
5942: $text = &mt('Checking Course Update Blocked');
5943: } elsif ($activity eq 'about') {
5944: $text = &mt('Access to User Information Pages Blocked');
5945: } elsif ($activity eq 'wishlist') {
5946: $text = &mt('Access to Stored Links Blocked');
5947: } elsif ($activity eq 'annotate') {
5948: $text = &mt('Access to Annotations Blocked');
5949: }
5950: $output .= <<"END_BLOCK";
5951: <div class='$class'>
5952: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5953: title='$text'>
5954: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5955: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5956: title='$text'>$text</a>
5957: </div>
5958:
5959: END_BLOCK
5960:
5961: return ($blocked, $output);
5962: }
5963:
5964: ###############################################
5965:
5966: sub check_ip_acc {
5967: my ($acc,$clientip)=@_;
5968: &Apache::lonxml::debug("acc is $acc");
5969: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5970: return 1;
5971: }
5972: my ($ip,$allowed);
5973: if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
5974: ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
5975: $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
5976: } else {
5977: my $remote_ip = &Apache::lonnet::get_requestor_ip();
5978: $ip = $remote_ip || $env{'request.host'} || $clientip;
5979: }
5980:
5981: my $name;
5982: my %access = (
5983: allowfrom => 1,
5984: denyfrom => 0,
5985: );
5986: my @allows;
5987: my @denies;
5988: foreach my $item (split(',',$acc)) {
5989: $item =~ s/^\s*//;
5990: $item =~ s/\s*$//;
5991: my $pattern;
5992: if ($item =~ /^\!(.+)$/) {
5993: push(@denies,$1);
5994: } else {
5995: push(@allows,$item);
5996: }
5997: }
5998: my $numdenies = scalar(@denies);
5999: my $numallows = scalar(@allows);
6000: my $count = 0;
6001: foreach my $pattern (@denies,@allows) {
6002: $count ++;
6003: my $acctype = 'allowfrom';
6004: if ($count <= $numdenies) {
6005: $acctype = 'denyfrom';
6006: }
6007: if ($pattern =~ /\*$/) {
6008: #35.8.*
6009: $pattern=~s/\*//;
6010: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
6011: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
6012: #35.8.3.[34-56]
6013: my $low=$2;
6014: my $high=$3;
6015: $pattern=$1;
6016: if ($ip =~ /^\Q$pattern\E/) {
6017: my $last=(split(/\./,$ip))[3];
6018: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
6019: }
6020: } elsif ($pattern =~ /^\*/) {
6021: #*.msu.edu
6022: $pattern=~s/\*//;
6023: if (!defined($name)) {
6024: use Socket;
6025: my $netaddr=inet_aton($ip);
6026: ($name)=gethostbyaddr($netaddr,AF_INET);
6027: }
6028: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
6029: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
6030: #127.0.0.1
6031: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
6032: } else {
6033: #some.name.com
6034: if (!defined($name)) {
6035: use Socket;
6036: my $netaddr=inet_aton($ip);
6037: ($name)=gethostbyaddr($netaddr,AF_INET);
6038: }
6039: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
6040: }
6041: if ($allowed =~ /^(0|1)$/) { last; }
6042: }
6043: if ($allowed eq '') {
6044: if ($numdenies && !$numallows) {
6045: $allowed = 1;
6046: } else {
6047: $allowed = 0;
6048: }
6049: }
6050: return $allowed;
6051: }
6052:
6053: ###############################################
6054:
6055: =pod
6056:
6057: =head1 Domain Template Functions
6058:
6059: =over 4
6060:
6061: =item * &determinedomain()
6062:
6063: Inputs: $domain (usually will be undef)
6064:
6065: Returns: Determines which domain should be used for designs
6066:
6067: =cut
6068:
6069: ###############################################
6070: sub determinedomain {
6071: my $domain=shift;
6072: if (! $domain) {
6073: # Determine domain if we have not been given one
6074: $domain = &Apache::lonnet::default_login_domain();
6075: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
6076: if ($env{'request.role.domain'}) {
6077: $domain=$env{'request.role.domain'};
6078: }
6079: }
6080: return $domain;
6081: }
6082: ###############################################
6083:
6084: sub devalidate_domconfig_cache {
6085: my ($udom)=@_;
6086: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
6087: }
6088:
6089: # ---------------------- Get domain configuration for a domain
6090: sub get_domainconf {
6091: my ($udom) = @_;
6092: my $cachetime=1800;
6093: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
6094: if (defined($cached)) { return %{$result}; }
6095:
6096: my %domconfig = &Apache::lonnet::get_dom('configuration',
6097: ['login','rolecolors','autoenroll'],$udom);
6098: my (%designhash,%legacy);
6099: if (keys(%domconfig) > 0) {
6100: if (ref($domconfig{'login'}) eq 'HASH') {
6101: if (keys(%{$domconfig{'login'}})) {
6102: foreach my $key (keys(%{$domconfig{'login'}})) {
6103: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6104: if (($key eq 'loginvia') || ($key eq 'headtag')) {
6105: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6106: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
6107: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
6108: if ($key eq 'loginvia') {
6109: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
6110: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
6111: $designhash{$udom.'.login.loginvia'} = $server;
6112: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
6113:
6114: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
6115: } else {
6116: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
6117: }
6118: }
6119: } elsif ($key eq 'headtag') {
6120: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
6121: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
6122: }
6123: }
6124: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
6125: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
6126: }
6127: }
6128: }
6129: }
6130: } elsif ($key eq 'saml') {
6131: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6132: foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
6133: if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
6134: $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
6135: foreach my $item ('text','img','alt','url','title','window','notsso') {
6136: $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
6137: }
6138: }
6139: }
6140: }
6141: } else {
6142: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
6143: $designhash{$udom.'.login.'.$key.'_'.$img} =
6144: $domconfig{'login'}{$key}{$img};
6145: }
6146: }
6147: } else {
6148: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
6149: }
6150: }
6151: } else {
6152: $legacy{'login'} = 1;
6153: }
6154: } else {
6155: $legacy{'login'} = 1;
6156: }
6157: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
6158: if (keys(%{$domconfig{'rolecolors'}})) {
6159: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
6160: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
6161: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
6162: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
6163: }
6164: }
6165: }
6166: } else {
6167: $legacy{'rolecolors'} = 1;
6168: }
6169: } else {
6170: $legacy{'rolecolors'} = 1;
6171: }
6172: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6173: if ($domconfig{'autoenroll'}{'co-owners'}) {
6174: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
6175: }
6176: }
6177: if (keys(%legacy) > 0) {
6178: my %legacyhash = &get_legacy_domconf($udom);
6179: foreach my $item (keys(%legacyhash)) {
6180: if ($item =~ /^\Q$udom\E\.login/) {
6181: if ($legacy{'login'}) {
6182: $designhash{$item} = $legacyhash{$item};
6183: }
6184: } else {
6185: if ($legacy{'rolecolors'}) {
6186: $designhash{$item} = $legacyhash{$item};
6187: }
6188: }
6189: }
6190: }
6191: } else {
6192: %designhash = &get_legacy_domconf($udom);
6193: }
6194: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
6195: $cachetime);
6196: return %designhash;
6197: }
6198:
6199: sub get_legacy_domconf {
6200: my ($udom) = @_;
6201: my %legacyhash;
6202: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
6203: my $designfile = $designdir.'/'.$udom.'.tab';
6204: if (-e $designfile) {
6205: if ( open (my $fh,'<',$designfile) ) {
6206: while (my $line = <$fh>) {
6207: next if ($line =~ /^\#/);
6208: chomp($line);
6209: my ($key,$val)=(split(/\=/,$line));
6210: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
6211: }
6212: close($fh);
6213: }
6214: }
6215: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
6216: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
6217: }
6218: return %legacyhash;
6219: }
6220:
6221: =pod
6222:
6223: =item * &domainlogo()
6224:
6225: Inputs: $domain (usually will be undef)
6226:
6227: Returns: A link to a domain logo, if the domain logo exists.
6228: If the domain logo does not exist, a description of the domain.
6229:
6230: =cut
6231:
6232: ###############################################
6233: sub domainlogo {
6234: my $domain = &determinedomain(shift);
6235: my %designhash = &get_domainconf($domain);
6236: # See if there is a logo
6237: if ($designhash{$domain.'.login.domlogo'} ne '') {
6238: my $imgsrc = $designhash{$domain.'.login.domlogo'};
6239: if ($imgsrc =~ m{^/(adm|res)/}) {
6240: if ($imgsrc =~ m{^/res/}) {
6241: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
6242: &Apache::lonnet::repcopy($local_name);
6243: }
6244: $imgsrc = &lonhttpdurl($imgsrc);
6245: }
6246: my $alttext = $domain;
6247: if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
6248: $alttext = $designhash{$domain.'.login.alttext_domlogo'};
6249: }
6250: return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
6251: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
6252: return &Apache::lonnet::domain($domain,'description');
6253: } else {
6254: return '';
6255: }
6256: }
6257: ##############################################
6258:
6259: =pod
6260:
6261: =item * &designparm()
6262:
6263: Inputs: $which parameter; $domain (usually will be undef)
6264:
6265: Returns: value of designparamter $which
6266:
6267: =cut
6268:
6269:
6270: ##############################################
6271: sub designparm {
6272: my ($which,$domain)=@_;
6273: if (exists($env{'environment.color.'.$which})) {
6274: return $env{'environment.color.'.$which};
6275: }
6276: $domain=&determinedomain($domain);
6277: my %domdesign;
6278: unless ($domain eq 'public') {
6279: %domdesign = &get_domainconf($domain);
6280: }
6281: my $output;
6282: if ($domdesign{$domain.'.'.$which} ne '') {
6283: $output = $domdesign{$domain.'.'.$which};
6284: } else {
6285: $output = $defaultdesign{$which};
6286: }
6287: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
6288: ($which =~ /login\.(img|logo|domlogo|login)/)) {
6289: if ($output =~ m{^/(adm|res)/}) {
6290: if ($output =~ m{^/res/}) {
6291: my $local_name = &Apache::lonnet::filelocation('',$output);
6292: &Apache::lonnet::repcopy($local_name);
6293: }
6294: $output = &lonhttpdurl($output);
6295: }
6296: }
6297: return $output;
6298: }
6299:
6300: ##############################################
6301: =pod
6302:
6303: =item * &authorspace()
6304:
6305: Inputs: $url (usually will be undef).
6306:
6307: Returns: Path to Authoring Space containing the resource or
6308: directory being viewed (or for which action is being taken).
6309: If $url is provided, and begins /priv/<domain>/<uname>
6310: the path will be that portion of the $context argument.
6311: Otherwise the path will be for the author space of the current
6312: user when the current role is author, or for that of the
6313: co-author/assistant co-author space when the current role
6314: is co-author or assistant co-author.
6315:
6316: =cut
6317:
6318: sub authorspace {
6319: my ($url) = @_;
6320: if ($url ne '') {
6321: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
6322: return $1;
6323: }
6324: }
6325: my $caname = '';
6326: my $cadom = '';
6327: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
6328: ($cadom,$caname) =
6329: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
6330: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
6331: $caname = $env{'user.name'};
6332: $cadom = $env{'user.domain'};
6333: }
6334: if (($caname ne '') && ($cadom ne '')) {
6335: return "/priv/$cadom/$caname/";
6336: }
6337: return;
6338: }
6339:
6340: ##############################################
6341: =pod
6342:
6343: =item * &head_subbox()
6344:
6345: Inputs: $content (contains HTML code with page functions, etc.)
6346:
6347: Returns: HTML div with $content
6348: To be included in page header
6349:
6350: =cut
6351:
6352: sub head_subbox {
6353: my ($content)=@_;
6354: my $output =
6355: '<div class="LC_head_subbox">'
6356: .$content
6357: .'</div>'
6358: }
6359:
6360: ##############################################
6361: =pod
6362:
6363: =item * &CSTR_pageheader()
6364:
6365: Input: (optional) filename from which breadcrumb trail is built.
6366: In most cases no input as needed, as $env{'request.filename'}
6367: is appropriate for use in building the breadcrumb trail.
6368: frameset flag
6369: If page header is being requested for use in a frameset, then
6370: the second (option) argument -- frameset will be true, and
6371: the target attribute set for links should be target="_parent".
6372:
6373: Returns: HTML div with CSTR path and recent box
6374: To be included on Authoring Space pages
6375:
6376: =cut
6377:
6378: sub CSTR_pageheader {
6379: my ($trailfile,$frameset,$title,$diraction) = @_;
6380: if ($trailfile eq '') {
6381: $trailfile = $env{'request.filename'};
6382: }
6383:
6384: # this is for resources; directories have customtitle, and crumbs
6385: # and select recent are created in lonpubdir.pm
6386:
6387: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
6388: my ($udom,$uname,$thisdisfn)=
6389: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
6390: my $formaction = "/priv/$udom/$uname/$thisdisfn";
6391: $formaction =~ s{/+}{/}g;
6392:
6393: my $parentpath = '';
6394: my $lastitem = '';
6395: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
6396: $parentpath = $1;
6397: $lastitem = $2;
6398: } else {
6399: $lastitem = $thisdisfn;
6400: }
6401:
6402: my $crsauthor;
6403: if (($env{'request.course.id'}) &&
6404: ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
6405: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
6406: $crsauthor = 1;
6407: if ($title eq '') {
6408: $title = &mt('Course Authoring Space');
6409: }
6410: } elsif ($title eq '') {
6411: $title = &mt('Authoring Space');
6412: }
6413:
6414: my ($target,$crumbtarget) = (' target="_top"','_top');
6415: if ($frameset) {
6416: $target = ' target="_parent"';
6417: $crumbtarget = '_parent';
6418: } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
6419: $target = '';
6420: $crumbtarget = '';
6421: } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
6422: $target = ' target="'.$env{'request.deeplink.target'}.'"';
6423: $crumbtarget = $env{'request.deeplink.target'};
6424: }
6425:
6426: my $output =
6427: '<div style="display:inline-block">'
6428: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
6429: .'<b>'.$title.'</b> '
6430: .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
6431: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
6432:
6433: if ($lastitem) {
6434: $output .=
6435: '<span class="LC_filename">'
6436: .$lastitem
6437: .'</span>';
6438: }
6439:
6440: if ($crsauthor) {
6441: $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
6442: } else {
6443: $output .=
6444: '<br />'
6445: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
6446: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
6447: .'</form>'
6448: .&Apache::lonmenu::constspaceform($frameset);
6449: }
6450: $output .= '</div>'.$diraction;
6451:
6452: return $output;
6453: }
6454:
6455: ###############################################
6456: ###############################################
6457:
6458: =pod
6459:
6460: =back
6461:
6462: =head1 HTML Helpers
6463:
6464: =over 4
6465:
6466: =item * &bodytag()
6467:
6468: Returns a uniform header for LON-CAPA web pages.
6469:
6470: Inputs:
6471:
6472: =over 4
6473:
6474: =item * $title, A title to be displayed on the page.
6475:
6476: =item * $function, the current role (can be undef).
6477:
6478: =item * $addentries, extra parameters for the <body> tag.
6479:
6480: =item * $bodyonly, if defined, only return the <body> tag.
6481:
6482: =item * $domain, if defined, force a given domain.
6483:
6484: =item * $forcereg, if page should register as content page (relevant for
6485: text interface only)
6486:
6487: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
6488: navigational links
6489:
6490: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
6491:
6492: =item * $args, optional argument valid values are
6493: no_auto_mt_title -> prevents &mt()ing the title arg
6494: use_absolute -> for external resource or syllabus, this will
6495: contain https://<hostname> if server uses
6496: https (as per hosts.tab), but request is for http
6497: hostname -> hostname, from $r->hostname().
6498:
6499: =item * $advtoolsref, optional argument, ref to an array containing
6500: inlineremote items to be added in "Functions" menu below
6501: breadcrumbs.
6502:
6503: =item * $ltiscope, optional argument, will be one of: resource, map or
6504: course, if LON-CAPA is in LTI Provider context. Value is
6505: the scope of use, i.e., launch was for access to a single, a map
6506: or the entire course.
6507:
6508: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
6509: context, this will contain the URL for the landing item in
6510: the course, after launch from an LTI Consumer
6511:
6512: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
6513: context, this will contain a reference to hash of items
6514: to be included in the page header and/or inline menu.
6515:
6516: =item * $menucoll, optional argument, if specific menu collection is in
6517: effect, either set as the default for the course, or set for
6518: the deeplink paramater for $env{'request.deeplink.login'}
6519: then $menucoll will be the number of that collection.
6520:
6521: =item * $menuref, optional argument, reference to a hash, containing the
6522: menu options included for the menu in effect, based on the
6523: configuration for the numbered menu collection in use.
6524:
6525: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
6526: within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
6527: if so, $showncrumbsref is set there to 1, and will propagate back
6528: via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
6529: being called a second time.
6530:
6531: =back
6532:
6533: Returns: A uniform header for LON-CAPA web pages.
6534: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
6535: If $bodyonly is undef or zero, an html string containing a <body> tag and
6536: other decorations will be returned.
6537:
6538: =cut
6539:
6540: sub bodytag {
6541: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
6542: $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
6543: $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
6544:
6545: my $public;
6546: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
6547: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
6548: $public = 1;
6549: }
6550: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6551: my $httphost = $args->{'use_absolute'};
6552: my $hostname = $args->{'hostname'};
6553:
6554: $function = &get_users_function() if (!$function);
6555: my $img = &designparm($function.'.img',$domain);
6556: my $font = &designparm($function.'.font',$domain);
6557: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
6558:
6559: my %design = ( 'style' => 'margin-top: 0',
6560: 'bgcolor' => $pgbg,
6561: 'text' => $font,
6562: 'alink' => &designparm($function.'.alink',$domain),
6563: 'vlink' => &designparm($function.'.vlink',$domain),
6564: 'link' => &designparm($function.'.link',$domain),);
6565: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
6566:
6567: # role and realm
6568: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
6569: if ($realm) {
6570: $realm = '/'.$realm;
6571: }
6572: if ($role eq 'ca') {
6573: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
6574: $realm = &plainname($rname,$rdom);
6575: }
6576: # realm
6577: my ($cid,$sec);
6578: if ($env{'request.course.id'}) {
6579: $cid = $env{'request.course.id'};
6580: if ($env{'request.course.sec'}) {
6581: $sec = $env{'request.course.sec'};
6582: }
6583: } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
6584: if (&Apache::lonnet::is_course($1,$2)) {
6585: $cid = $1.'_'.$2;
6586: $sec = $3;
6587: }
6588: }
6589: if ($cid) {
6590: if ($env{'request.role'} !~ /^cr/) {
6591: $role = &Apache::lonnet::plaintext($role,&course_type());
6592: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
6593: if ($env{'request.role.desc'}) {
6594: $role = $env{'request.role.desc'};
6595: } else {
6596: $role = &mt('Helpdesk[_1]',' '.$2);
6597: }
6598: } else {
6599: $role = (split(/\//,$role,4))[-1];
6600: }
6601: if ($sec) {
6602: $role .= (' 'x2).'- '.&mt('section:').' '.$sec;
6603: }
6604: $realm = $env{'course.'.$cid.'.description'};
6605: } else {
6606: $role = &Apache::lonnet::plaintext($role);
6607: }
6608:
6609: if (!$realm) { $realm=' '; }
6610:
6611: my $extra_body_attr = &make_attr_string($forcereg,\%design);
6612:
6613: # construct main body tag
6614: my $bodytag = "<body $extra_body_attr>".
6615: &Apache::lontexconvert::init_math_support();
6616:
6617: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6618:
6619: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
6620: return $bodytag;
6621: }
6622:
6623: if ($public) {
6624: undef($role);
6625: }
6626:
6627: my $showcrstitle = 1;
6628: if (($cid) && ($env{'request.lti.login'})) {
6629: if (ref($ltimenu) eq 'HASH') {
6630: unless ($ltimenu->{'role'}) {
6631: undef($role);
6632: }
6633: unless ($ltimenu->{'coursetitle'}) {
6634: $realm=' ';
6635: $showcrstitle = 0;
6636: }
6637: }
6638: } elsif (($cid) && ($menucoll)) {
6639: if (ref($menuref) eq 'HASH') {
6640: unless ($menuref->{'role'}) {
6641: undef($role);
6642: }
6643: unless ($menuref->{'crs'}) {
6644: $realm=' ';
6645: $showcrstitle = 0;
6646: }
6647: }
6648: }
6649:
6650: my $titleinfo = '<h1>'.$title.'</h1>';
6651: #
6652: # Extra info if you are the DC
6653: my $dc_info = '';
6654: if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
6655: (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
6656: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
6657: $dc_info =~ s/\s+$//;
6658: }
6659:
6660: my $crstype;
6661: if ($cid) {
6662: $crstype = $env{'course.'.$cid.'.type'};
6663: } elsif ($args->{'crstype'}) {
6664: $crstype = $args->{'crstype'};
6665: }
6666: if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
6667: undef($role);
6668: } else {
6669: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
6670: }
6671:
6672: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
6673:
6674: # if ($env{'request.state'} eq 'construct') {
6675: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
6676: # }
6677:
6678: $bodytag .= Apache::lonhtmlcommon::scripttag(
6679: Apache::lonmenu::utilityfunctions($httphost), 'start');
6680:
6681: unless ($args->{'no_primary_menu'}) {
6682: my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
6683: $args->{'links_disabled'},
6684: $args->{'links_target'});
6685:
6686: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
6687: if ($dc_info) {
6688: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
6689: }
6690: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
6691: <em>$realm</em> $dc_info</div>|;
6692: return $bodytag;
6693: }
6694:
6695: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
6696: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
6697: }
6698:
6699: $bodytag .= $right;
6700:
6701: if ($dc_info) {
6702: $dc_info = &dc_courseid_toggle($dc_info);
6703: }
6704: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
6705: }
6706:
6707: #if directed to not display the secondary menu, don't.
6708: if ($args->{'no_secondary_menu'}) {
6709: return $bodytag;
6710: }
6711: #don't show menus for public users
6712: if (!$public){
6713: unless ($args->{'no_inline_menu'}) {
6714: $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
6715: $args->{'no_primary_menu'},
6716: $menucoll,$menuref,
6717: $args->{'links_disabled'},
6718: $args->{'links_target'});
6719: }
6720: $bodytag .= Apache::lonmenu::serverform();
6721: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6722: if ($env{'request.state'} eq 'construct') {
6723: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
6724: $args->{'bread_crumbs'},'','',$hostname,
6725: $ltiscope,$ltiuri,$showncrumbsref);
6726: } elsif ($forcereg) {
6727: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
6728: $args->{'group'},$args->{'hide_buttons'},
6729: $hostname,$ltiscope,$ltiuri,$showncrumbsref);
6730: } else {
6731: $bodytag .=
6732: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6733: $forcereg,$args->{'group'},
6734: $args->{'bread_crumbs'},
6735: $advtoolsref,'',$hostname);
6736: }
6737: }else{
6738: # this is to seperate menu from content when there's no secondary
6739: # menu. Especially needed for public accessible ressources.
6740: $bodytag .= '<hr style="clear:both" />';
6741: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6742: }
6743:
6744: return $bodytag;
6745: }
6746:
6747: sub dc_courseid_toggle {
6748: my ($dc_info) = @_;
6749: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
6750: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
6751: &mt('(More ...)').'</a></span>'.
6752: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
6753: }
6754:
6755: sub make_attr_string {
6756: my ($register,$attr_ref) = @_;
6757:
6758: if ($attr_ref && !ref($attr_ref)) {
6759: die("addentries Must be a hash ref ".
6760: join(':',caller(1))." ".
6761: join(':',caller(0))." ");
6762: }
6763:
6764: if ($register) {
6765: my ($on_load,$on_unload);
6766: foreach my $key (keys(%{$attr_ref})) {
6767: if (lc($key) eq 'onload') {
6768: $on_load.=$attr_ref->{$key}.';';
6769: delete($attr_ref->{$key});
6770:
6771: } elsif (lc($key) eq 'onunload') {
6772: $on_unload.=$attr_ref->{$key}.';';
6773: delete($attr_ref->{$key});
6774: }
6775: }
6776: $attr_ref->{'onload'} = $on_load;
6777: $attr_ref->{'onunload'}= $on_unload;
6778: }
6779:
6780: my $attr_string;
6781: foreach my $attr (sort(keys(%$attr_ref))) {
6782: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6783: }
6784: return $attr_string;
6785: }
6786:
6787:
6788: ###############################################
6789: ###############################################
6790:
6791: =pod
6792:
6793: =item * &endbodytag()
6794:
6795: Returns a uniform footer for LON-CAPA web pages.
6796:
6797: Inputs: 1 - optional reference to an args hash
6798: If in the hash, key for noredirectlink has a value which evaluates to true,
6799: a 'Continue' link is not displayed if the page contains an
6800: internal redirect in the <head></head> section,
6801: i.e., $env{'internal.head.redirect'} exists
6802:
6803: =cut
6804:
6805: sub endbodytag {
6806: my ($args) = @_;
6807: my $endbodytag;
6808: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6809: $endbodytag='</body>';
6810: }
6811: if ( exists( $env{'internal.head.redirect'} ) ) {
6812: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6813: my ($endbodyjs,$idattr);
6814: if ($env{'internal.head.to_opener'}) {
6815: my $linkid = 'LC_continue_link';
6816: $idattr = ' id="'.$linkid.'"';
6817: my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
6818: $endbodyjs=<<ENDJS;
6819: <script type="text/javascript">
6820: // <![CDATA[
6821: function ebFunction(evt) {
6822: evt.preventDefault();
6823: var dest = '$redirect_for_js';
6824: if (window.opener != null && !window.opener.closed) {
6825: window.opener.location.href=dest;
6826: window.close();
6827: } else {
6828: window.location.href=dest;
6829: }
6830: return false;
6831: }
6832:
6833: \$(document).ready(function () {
6834: if (document.getElementById('$linkid')) {
6835: var clickelem = document.getElementById('$linkid');
6836: clickelem.addEventListener('click',ebFunction,false);
6837: }
6838: });
6839: // ]]>
6840: </script>
6841: ENDJS
6842: }
6843: $endbodytag=
6844: "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
6845: &mt('Continue').'</a>'.
6846: $endbodytag;
6847: }
6848: }
6849: return $endbodytag;
6850: }
6851:
6852: =pod
6853:
6854: =item * &standard_css()
6855:
6856: Returns a style sheet
6857:
6858: Inputs: (all optional)
6859: domain -> force to color decorate a page for a specific
6860: domain
6861: function -> force usage of a specific rolish color scheme
6862: bgcolor -> override the default page bgcolor
6863:
6864: =cut
6865:
6866: sub standard_css {
6867: my ($function,$domain,$bgcolor) = @_;
6868: $function = &get_users_function() if (!$function);
6869: my $img = &designparm($function.'.img', $domain);
6870: my $tabbg = &designparm($function.'.tabbg', $domain);
6871: my $font = &designparm($function.'.font', $domain);
6872: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6873: #second colour for later usage
6874: my $sidebg = &designparm($function.'.sidebg',$domain);
6875: my $pgbg_or_bgcolor =
6876: $bgcolor ||
6877: &designparm($function.'.pgbg', $domain);
6878: my $pgbg = &designparm($function.'.pgbg', $domain);
6879: my $alink = &designparm($function.'.alink', $domain);
6880: my $vlink = &designparm($function.'.vlink', $domain);
6881: my $link = &designparm($function.'.link', $domain);
6882:
6883: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6884: my $mono = 'monospace';
6885: my $data_table_head = $sidebg;
6886: my $data_table_light = '#FAFAFA';
6887: my $data_table_dark = '#E0E0E0';
6888: my $data_table_darker = '#CCCCCC';
6889: my $data_table_highlight = '#FFFF00';
6890: my $mail_new = '#FFBB77';
6891: my $mail_new_hover = '#DD9955';
6892: my $mail_read = '#BBBB77';
6893: my $mail_read_hover = '#999944';
6894: my $mail_replied = '#AAAA88';
6895: my $mail_replied_hover = '#888855';
6896: my $mail_other = '#99BBBB';
6897: my $mail_other_hover = '#669999';
6898: my $table_header = '#DDDDDD';
6899: my $feedback_link_bg = '#BBBBBB';
6900: my $lg_border_color = '#C8C8C8';
6901: my $button_hover = '#BF2317';
6902:
6903: my $border = ($env{'browser.type'} eq 'explorer' ||
6904: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6905: : '0 3px 0 4px';
6906:
6907:
6908: return <<END;
6909:
6910: /* needed for iframe to allow 100% height in FF */
6911: body, html {
6912: margin: 0;
6913: padding: 0 0.5%;
6914: height: 99%; /* to avoid scrollbars */
6915: }
6916:
6917: body {
6918: font-family: $sans;
6919: line-height:130%;
6920: font-size:0.83em;
6921: color:$font;
6922: }
6923:
6924: a:focus,
6925: a:focus img {
6926: color: red;
6927: }
6928:
6929: form, .inline {
6930: display: inline;
6931: }
6932:
6933: .LC_right {
6934: text-align:right;
6935: }
6936:
6937: .LC_middle {
6938: vertical-align:middle;
6939: }
6940:
6941: .LC_floatleft {
6942: float: left;
6943: }
6944:
6945: .LC_floatright {
6946: float: right;
6947: }
6948:
6949: .LC_400Box {
6950: width:400px;
6951: }
6952:
6953: .LC_iframecontainer {
6954: width: 98%;
6955: margin: 0;
6956: position: fixed;
6957: top: 8.5em;
6958: bottom: 0;
6959: }
6960:
6961: .LC_iframecontainer iframe{
6962: border: none;
6963: width: 100%;
6964: height: 100%;
6965: }
6966:
6967: .LC_filename {
6968: font-family: $mono;
6969: white-space:pre;
6970: font-size: 120%;
6971: }
6972:
6973: .LC_fileicon {
6974: border: none;
6975: height: 1.3em;
6976: vertical-align: text-bottom;
6977: margin-right: 0.3em;
6978: text-decoration:none;
6979: }
6980:
6981: .LC_setting {
6982: text-decoration:underline;
6983: }
6984:
6985: .LC_error {
6986: color: red;
6987: }
6988:
6989: .LC_warning {
6990: color: darkorange;
6991: }
6992:
6993: .LC_diff_removed {
6994: color: red;
6995: }
6996:
6997: .LC_info,
6998: .LC_success,
6999: .LC_diff_added {
7000: color: green;
7001: }
7002:
7003: div.LC_confirm_box {
7004: background-color: #FAFAFA;
7005: border: 1px solid $lg_border_color;
7006: margin-right: 0;
7007: padding: 5px;
7008: }
7009:
7010: div.LC_confirm_box .LC_error img,
7011: div.LC_confirm_box .LC_success img {
7012: vertical-align: middle;
7013: }
7014:
7015: .LC_maxwidth {
7016: max-width: 100%;
7017: height: auto;
7018: }
7019:
7020: .LC_textsize_mobile {
7021: \@media only screen and (max-device-width: 480px) {
7022: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
7023: }
7024: }
7025:
7026: .LC_icon {
7027: border: none;
7028: vertical-align: middle;
7029: }
7030:
7031: .LC_docs_spacer {
7032: width: 25px;
7033: height: 1px;
7034: border: none;
7035: }
7036:
7037: .LC_internal_info {
7038: color: #999999;
7039: }
7040:
7041: .LC_discussion {
7042: background: $data_table_dark;
7043: border: 1px solid black;
7044: margin: 2px;
7045: }
7046:
7047: .LC_disc_action_left {
7048: background: $sidebg;
7049: text-align: left;
7050: padding: 4px;
7051: margin: 2px;
7052: }
7053:
7054: .LC_disc_action_right {
7055: background: $sidebg;
7056: text-align: right;
7057: padding: 4px;
7058: margin: 2px;
7059: }
7060:
7061: .LC_disc_new_item {
7062: background: white;
7063: border: 2px solid red;
7064: margin: 4px;
7065: padding: 4px;
7066: }
7067:
7068: .LC_disc_old_item {
7069: background: white;
7070: margin: 4px;
7071: padding: 4px;
7072: }
7073:
7074: table.LC_pastsubmission {
7075: border: 1px solid black;
7076: margin: 2px;
7077: }
7078:
7079: table#LC_menubuttons {
7080: width: 100%;
7081: background: $pgbg;
7082: border: 2px;
7083: border-collapse: separate;
7084: padding: 0;
7085: }
7086:
7087: table#LC_title_bar a {
7088: color: $fontmenu;
7089: }
7090:
7091: table#LC_title_bar {
7092: clear: both;
7093: display: none;
7094: }
7095:
7096: table#LC_title_bar,
7097: table.LC_breadcrumbs, /* obsolete? */
7098: table#LC_title_bar.LC_with_remote {
7099: width: 100%;
7100: border-color: $pgbg;
7101: border-style: solid;
7102: border-width: $border;
7103: background: $pgbg;
7104: color: $fontmenu;
7105: border-collapse: collapse;
7106: padding: 0;
7107: margin: 0;
7108: }
7109:
7110: ul.LC_breadcrumb_tools_outerlist {
7111: margin: 0;
7112: padding: 0;
7113: position: relative;
7114: list-style: none;
7115: }
7116: ul.LC_breadcrumb_tools_outerlist li {
7117: display: inline;
7118: }
7119:
7120: .LC_breadcrumb_tools_navigation {
7121: padding: 0;
7122: margin: 0;
7123: float: left;
7124: }
7125: .LC_breadcrumb_tools_tools {
7126: padding: 0;
7127: margin: 0;
7128: float: right;
7129: }
7130:
7131: .LC_placement_prog {
7132: padding-right: 20px;
7133: font-weight: bold;
7134: font-size: 90%;
7135: }
7136:
7137: table#LC_title_bar td {
7138: background: $tabbg;
7139: }
7140:
7141: table#LC_menubuttons img {
7142: border: none;
7143: }
7144:
7145: .LC_breadcrumbs_component {
7146: float: right;
7147: margin: 0 1em;
7148: }
7149: .LC_breadcrumbs_component img {
7150: vertical-align: middle;
7151: }
7152:
7153: .LC_breadcrumbs_hoverable {
7154: background: $sidebg;
7155: }
7156:
7157: td.LC_table_cell_checkbox {
7158: text-align: center;
7159: }
7160:
7161: .LC_fontsize_small {
7162: font-size: 70%;
7163: }
7164:
7165: #LC_breadcrumbs {
7166: clear:both;
7167: background: $sidebg;
7168: border-bottom: 1px solid $lg_border_color;
7169: line-height: 2.5em;
7170: overflow: hidden;
7171: margin: 0;
7172: padding: 0;
7173: text-align: left;
7174: }
7175:
7176: .LC_head_subbox, .LC_actionbox {
7177: clear:both;
7178: background: #F8F8F8; /* $sidebg; */
7179: border: 1px solid $sidebg;
7180: margin: 0 0 10px 0;
7181: padding: 3px;
7182: text-align: left;
7183: }
7184:
7185: .LC_fontsize_medium {
7186: font-size: 85%;
7187: }
7188:
7189: .LC_fontsize_large {
7190: font-size: 120%;
7191: }
7192:
7193: .LC_menubuttons_inline_text {
7194: color: $font;
7195: font-size: 90%;
7196: padding-left:3px;
7197: }
7198:
7199: .LC_menubuttons_inline_text img{
7200: vertical-align: middle;
7201: }
7202:
7203: li.LC_menubuttons_inline_text img {
7204: cursor:pointer;
7205: text-decoration: none;
7206: }
7207:
7208: .LC_menubuttons_link {
7209: text-decoration: none;
7210: }
7211:
7212: .LC_menubuttons_category {
7213: color: $font;
7214: background: $pgbg;
7215: font-size: larger;
7216: font-weight: bold;
7217: }
7218:
7219: td.LC_menubuttons_text {
7220: color: $font;
7221: }
7222:
7223: .LC_current_location {
7224: background: $tabbg;
7225: }
7226:
7227: td.LC_zero_height {
7228: line-height: 0;
7229: cellpadding: 0;
7230: }
7231:
7232: table.LC_data_table {
7233: border: 1px solid #000000;
7234: border-collapse: separate;
7235: border-spacing: 1px;
7236: background: $pgbg;
7237: }
7238:
7239: .LC_data_table_dense {
7240: font-size: small;
7241: }
7242:
7243: table.LC_nested_outer {
7244: border: 1px solid #000000;
7245: border-collapse: collapse;
7246: border-spacing: 0;
7247: width: 100%;
7248: }
7249:
7250: table.LC_innerpickbox,
7251: table.LC_nested {
7252: border: none;
7253: border-collapse: collapse;
7254: border-spacing: 0;
7255: width: 100%;
7256: }
7257:
7258: table.LC_data_table tr th,
7259: table.LC_calendar tr th,
7260: table.LC_prior_tries tr th,
7261: table.LC_innerpickbox tr th {
7262: font-weight: bold;
7263: background-color: $data_table_head;
7264: color:$fontmenu;
7265: font-size:90%;
7266: }
7267:
7268: table.LC_innerpickbox tr th,
7269: table.LC_innerpickbox tr td {
7270: vertical-align: top;
7271: }
7272:
7273: table.LC_data_table tr.LC_info_row > td {
7274: background-color: #CCCCCC;
7275: font-weight: bold;
7276: text-align: left;
7277: }
7278:
7279: table.LC_data_table tr.LC_odd_row > td {
7280: background-color: $data_table_light;
7281: padding: 2px;
7282: vertical-align: top;
7283: }
7284:
7285: table.LC_pick_box tr > td.LC_odd_row {
7286: background-color: $data_table_light;
7287: vertical-align: top;
7288: }
7289:
7290: table.LC_data_table tr.LC_even_row > td {
7291: background-color: $data_table_dark;
7292: padding: 2px;
7293: vertical-align: top;
7294: }
7295:
7296: table.LC_pick_box tr > td.LC_even_row {
7297: background-color: $data_table_dark;
7298: vertical-align: top;
7299: }
7300:
7301: table.LC_data_table tr.LC_data_table_highlight td {
7302: background-color: $data_table_darker;
7303: }
7304:
7305: table.LC_data_table tr td.LC_leftcol_header {
7306: background-color: $data_table_head;
7307: font-weight: bold;
7308: }
7309:
7310: table.LC_data_table tr.LC_empty_row td,
7311: table.LC_nested tr.LC_empty_row td {
7312: font-weight: bold;
7313: font-style: italic;
7314: text-align: center;
7315: padding: 8px;
7316: }
7317:
7318: table.LC_data_table tr.LC_empty_row td,
7319: table.LC_data_table tr.LC_footer_row td {
7320: background-color: $sidebg;
7321: }
7322:
7323: table.LC_nested tr.LC_empty_row td {
7324: background-color: #FFFFFF;
7325: }
7326:
7327: table.LC_caption {
7328: }
7329:
7330: table.LC_nested tr.LC_empty_row td {
7331: padding: 4ex
7332: }
7333:
7334: table.LC_nested_outer tr th {
7335: font-weight: bold;
7336: color:$fontmenu;
7337: background-color: $data_table_head;
7338: font-size: small;
7339: border-bottom: 1px solid #000000;
7340: }
7341:
7342: table.LC_nested_outer tr td.LC_subheader {
7343: background-color: $data_table_head;
7344: font-weight: bold;
7345: font-size: small;
7346: border-bottom: 1px solid #000000;
7347: text-align: right;
7348: }
7349:
7350: table.LC_nested tr.LC_info_row td {
7351: background-color: #CCCCCC;
7352: font-weight: bold;
7353: font-size: small;
7354: text-align: center;
7355: }
7356:
7357: table.LC_nested tr.LC_info_row td.LC_left_item,
7358: table.LC_nested_outer tr th.LC_left_item {
7359: text-align: left;
7360: }
7361:
7362: table.LC_nested td {
7363: background-color: #FFFFFF;
7364: font-size: small;
7365: }
7366:
7367: table.LC_nested_outer tr th.LC_right_item,
7368: table.LC_nested tr.LC_info_row td.LC_right_item,
7369: table.LC_nested tr.LC_odd_row td.LC_right_item,
7370: table.LC_nested tr td.LC_right_item {
7371: text-align: right;
7372: }
7373:
7374: table.LC_nested tr.LC_odd_row td {
7375: background-color: #EEEEEE;
7376: }
7377:
7378: table.LC_createuser {
7379: }
7380:
7381: table.LC_createuser tr.LC_section_row td {
7382: font-size: small;
7383: }
7384:
7385: table.LC_createuser tr.LC_info_row td {
7386: background-color: #CCCCCC;
7387: font-weight: bold;
7388: text-align: center;
7389: }
7390:
7391: table.LC_calendar {
7392: border: 1px solid #000000;
7393: border-collapse: collapse;
7394: width: 98%;
7395: }
7396:
7397: table.LC_calendar_pickdate {
7398: font-size: xx-small;
7399: }
7400:
7401: table.LC_calendar tr td {
7402: border: 1px solid #000000;
7403: vertical-align: top;
7404: width: 14%;
7405: }
7406:
7407: table.LC_calendar tr td.LC_calendar_day_empty {
7408: background-color: $data_table_dark;
7409: }
7410:
7411: table.LC_calendar tr td.LC_calendar_day_current {
7412: background-color: $data_table_highlight;
7413: }
7414:
7415: table.LC_data_table tr td.LC_mail_new {
7416: background-color: $mail_new;
7417: }
7418:
7419: table.LC_data_table tr.LC_mail_new:hover {
7420: background-color: $mail_new_hover;
7421: }
7422:
7423: table.LC_data_table tr td.LC_mail_read {
7424: background-color: $mail_read;
7425: }
7426:
7427: /*
7428: table.LC_data_table tr.LC_mail_read:hover {
7429: background-color: $mail_read_hover;
7430: }
7431: */
7432:
7433: table.LC_data_table tr td.LC_mail_replied {
7434: background-color: $mail_replied;
7435: }
7436:
7437: /*
7438: table.LC_data_table tr.LC_mail_replied:hover {
7439: background-color: $mail_replied_hover;
7440: }
7441: */
7442:
7443: table.LC_data_table tr td.LC_mail_other {
7444: background-color: $mail_other;
7445: }
7446:
7447: /*
7448: table.LC_data_table tr.LC_mail_other:hover {
7449: background-color: $mail_other_hover;
7450: }
7451: */
7452:
7453: table.LC_data_table tr > td.LC_browser_file,
7454: table.LC_data_table tr > td.LC_browser_file_published {
7455: background: #AAEE77;
7456: }
7457:
7458: table.LC_data_table tr > td.LC_browser_file_locked,
7459: table.LC_data_table tr > td.LC_browser_file_unpublished {
7460: background: #FFAA99;
7461: }
7462:
7463: table.LC_data_table tr > td.LC_browser_file_obsolete {
7464: background: #888888;
7465: }
7466:
7467: table.LC_data_table tr > td.LC_browser_file_modified,
7468: table.LC_data_table tr > td.LC_browser_file_metamodified {
7469: background: #F8F866;
7470: }
7471:
7472: table.LC_data_table tr.LC_browser_folder > td {
7473: background: #E0E8FF;
7474: }
7475:
7476: table.LC_data_table tr > td.LC_roles_is {
7477: /* background: #77FF77; */
7478: }
7479:
7480: table.LC_data_table tr > td.LC_roles_future {
7481: border-right: 8px solid #FFFF77;
7482: }
7483:
7484: table.LC_data_table tr > td.LC_roles_will {
7485: border-right: 8px solid #FFAA77;
7486: }
7487:
7488: table.LC_data_table tr > td.LC_roles_expired {
7489: border-right: 8px solid #FF7777;
7490: }
7491:
7492: table.LC_data_table tr > td.LC_roles_will_not {
7493: border-right: 8px solid #AAFF77;
7494: }
7495:
7496: table.LC_data_table tr > td.LC_roles_selected {
7497: border-right: 8px solid #11CC55;
7498: }
7499:
7500: span.LC_current_location {
7501: font-size:larger;
7502: background: $pgbg;
7503: }
7504:
7505: span.LC_current_nav_location {
7506: font-weight:bold;
7507: background: $sidebg;
7508: }
7509:
7510: span.LC_parm_menu_item {
7511: font-size: larger;
7512: }
7513:
7514: span.LC_parm_scope_all {
7515: color: red;
7516: }
7517:
7518: span.LC_parm_scope_folder {
7519: color: green;
7520: }
7521:
7522: span.LC_parm_scope_resource {
7523: color: orange;
7524: }
7525:
7526: span.LC_parm_part {
7527: color: blue;
7528: }
7529:
7530: span.LC_parm_folder,
7531: span.LC_parm_symb {
7532: font-size: x-small;
7533: font-family: $mono;
7534: color: #AAAAAA;
7535: }
7536:
7537: ul.LC_parm_parmlist li {
7538: display: inline-block;
7539: padding: 0.3em 0.8em;
7540: vertical-align: top;
7541: width: 150px;
7542: border-top:1px solid $lg_border_color;
7543: }
7544:
7545: td.LC_parm_overview_level_menu,
7546: td.LC_parm_overview_map_menu,
7547: td.LC_parm_overview_parm_selectors,
7548: td.LC_parm_overview_restrictions {
7549: border: 1px solid black;
7550: border-collapse: collapse;
7551: }
7552:
7553: span.LC_parm_recursive,
7554: td.LC_parm_recursive {
7555: font-weight: bold;
7556: font-size: smaller;
7557: }
7558:
7559: table.LC_parm_overview_restrictions td {
7560: border-width: 1px 4px 1px 4px;
7561: border-style: solid;
7562: border-color: $pgbg;
7563: text-align: center;
7564: }
7565:
7566: table.LC_parm_overview_restrictions th {
7567: background: $tabbg;
7568: border-width: 1px 4px 1px 4px;
7569: border-style: solid;
7570: border-color: $pgbg;
7571: }
7572:
7573: table#LC_helpmenu {
7574: border: none;
7575: height: 55px;
7576: border-spacing: 0;
7577: }
7578:
7579: table#LC_helpmenu fieldset legend {
7580: font-size: larger;
7581: }
7582:
7583: table#LC_helpmenu_links {
7584: width: 100%;
7585: border: 1px solid black;
7586: background: $pgbg;
7587: padding: 0;
7588: border-spacing: 1px;
7589: }
7590:
7591: table#LC_helpmenu_links tr td {
7592: padding: 1px;
7593: background: $tabbg;
7594: text-align: center;
7595: font-weight: bold;
7596: }
7597:
7598: table#LC_helpmenu_links a:link,
7599: table#LC_helpmenu_links a:visited,
7600: table#LC_helpmenu_links a:active {
7601: text-decoration: none;
7602: color: $font;
7603: }
7604:
7605: table#LC_helpmenu_links a:hover {
7606: text-decoration: underline;
7607: color: $vlink;
7608: }
7609:
7610: .LC_chrt_popup_exists {
7611: border: 1px solid #339933;
7612: margin: -1px;
7613: }
7614:
7615: .LC_chrt_popup_up {
7616: border: 1px solid yellow;
7617: margin: -1px;
7618: }
7619:
7620: .LC_chrt_popup {
7621: border: 1px solid #8888FF;
7622: background: #CCCCFF;
7623: }
7624:
7625: table.LC_pick_box {
7626: border-collapse: separate;
7627: background: white;
7628: border: 1px solid black;
7629: border-spacing: 1px;
7630: }
7631:
7632: table.LC_pick_box td.LC_pick_box_title {
7633: background: $sidebg;
7634: font-weight: bold;
7635: text-align: left;
7636: vertical-align: top;
7637: width: 184px;
7638: padding: 8px;
7639: }
7640:
7641: table.LC_pick_box td.LC_pick_box_value {
7642: text-align: left;
7643: padding: 8px;
7644: }
7645:
7646: table.LC_pick_box td.LC_pick_box_select {
7647: text-align: left;
7648: padding: 8px;
7649: }
7650:
7651: table.LC_pick_box td.LC_pick_box_separator {
7652: padding: 0;
7653: height: 1px;
7654: background: black;
7655: }
7656:
7657: table.LC_pick_box td.LC_pick_box_submit {
7658: text-align: right;
7659: }
7660:
7661: table.LC_pick_box td.LC_evenrow_value {
7662: text-align: left;
7663: padding: 8px;
7664: background-color: $data_table_light;
7665: }
7666:
7667: table.LC_pick_box td.LC_oddrow_value {
7668: text-align: left;
7669: padding: 8px;
7670: background-color: $data_table_light;
7671: }
7672:
7673: span.LC_helpform_receipt_cat {
7674: font-weight: bold;
7675: }
7676:
7677: table.LC_group_priv_box {
7678: background: white;
7679: border: 1px solid black;
7680: border-spacing: 1px;
7681: }
7682:
7683: table.LC_group_priv_box td.LC_pick_box_title {
7684: background: $tabbg;
7685: font-weight: bold;
7686: text-align: right;
7687: width: 184px;
7688: }
7689:
7690: table.LC_group_priv_box td.LC_groups_fixed {
7691: background: $data_table_light;
7692: text-align: center;
7693: }
7694:
7695: table.LC_group_priv_box td.LC_groups_optional {
7696: background: $data_table_dark;
7697: text-align: center;
7698: }
7699:
7700: table.LC_group_priv_box td.LC_groups_functionality {
7701: background: $data_table_darker;
7702: text-align: center;
7703: font-weight: bold;
7704: }
7705:
7706: table.LC_group_priv td {
7707: text-align: left;
7708: padding: 0;
7709: }
7710:
7711: .LC_navbuttons {
7712: margin: 2ex 0ex 2ex 0ex;
7713: }
7714:
7715: .LC_topic_bar {
7716: font-weight: bold;
7717: background: $tabbg;
7718: margin: 1em 0em 1em 2em;
7719: padding: 3px;
7720: font-size: 1.2em;
7721: }
7722:
7723: .LC_topic_bar span {
7724: left: 0.5em;
7725: position: absolute;
7726: vertical-align: middle;
7727: font-size: 1.2em;
7728: }
7729:
7730: table.LC_course_group_status {
7731: margin: 20px;
7732: }
7733:
7734: table.LC_status_selector td {
7735: vertical-align: top;
7736: text-align: center;
7737: padding: 4px;
7738: }
7739:
7740: div.LC_feedback_link {
7741: clear: both;
7742: background: $sidebg;
7743: width: 100%;
7744: padding-bottom: 10px;
7745: border: 1px $tabbg solid;
7746: height: 22px;
7747: line-height: 22px;
7748: padding-top: 5px;
7749: }
7750:
7751: div.LC_feedback_link img {
7752: height: 22px;
7753: vertical-align:middle;
7754: }
7755:
7756: div.LC_feedback_link a {
7757: text-decoration: none;
7758: }
7759:
7760: div.LC_comblock {
7761: display:inline;
7762: color:$font;
7763: font-size:90%;
7764: }
7765:
7766: div.LC_feedback_link div.LC_comblock {
7767: padding-left:5px;
7768: }
7769:
7770: div.LC_feedback_link div.LC_comblock a {
7771: color:$font;
7772: }
7773:
7774: span.LC_feedback_link {
7775: /* background: $feedback_link_bg; */
7776: font-size: larger;
7777: }
7778:
7779: span.LC_message_link {
7780: /* background: $feedback_link_bg; */
7781: font-size: larger;
7782: position: absolute;
7783: right: 1em;
7784: }
7785:
7786: table.LC_prior_tries {
7787: border: 1px solid #000000;
7788: border-collapse: separate;
7789: border-spacing: 1px;
7790: }
7791:
7792: table.LC_prior_tries td {
7793: padding: 2px;
7794: }
7795:
7796: .LC_answer_correct {
7797: background: lightgreen;
7798: color: darkgreen;
7799: padding: 6px;
7800: }
7801:
7802: .LC_answer_charged_try {
7803: background: #FFAAAA;
7804: color: darkred;
7805: padding: 6px;
7806: }
7807:
7808: .LC_answer_not_charged_try,
7809: .LC_answer_no_grade,
7810: .LC_answer_late {
7811: background: lightyellow;
7812: color: black;
7813: padding: 6px;
7814: }
7815:
7816: .LC_answer_previous {
7817: background: lightblue;
7818: color: darkblue;
7819: padding: 6px;
7820: }
7821:
7822: .LC_answer_no_message {
7823: background: #FFFFFF;
7824: color: black;
7825: padding: 6px;
7826: }
7827:
7828: .LC_answer_unknown,
7829: .LC_answer_warning {
7830: background: orange;
7831: color: black;
7832: padding: 6px;
7833: }
7834:
7835: span.LC_prior_numerical,
7836: span.LC_prior_string,
7837: span.LC_prior_custom,
7838: span.LC_prior_reaction,
7839: span.LC_prior_math {
7840: font-family: $mono;
7841: white-space: pre;
7842: }
7843:
7844: span.LC_prior_string {
7845: font-family: $mono;
7846: white-space: pre;
7847: }
7848:
7849: table.LC_prior_option {
7850: width: 100%;
7851: border-collapse: collapse;
7852: }
7853:
7854: table.LC_prior_rank,
7855: table.LC_prior_match {
7856: border-collapse: collapse;
7857: }
7858:
7859: table.LC_prior_option tr td,
7860: table.LC_prior_rank tr td,
7861: table.LC_prior_match tr td {
7862: border: 1px solid #000000;
7863: }
7864:
7865: .LC_nobreak {
7866: white-space: nowrap;
7867: }
7868:
7869: span.LC_cusr_emph {
7870: font-style: italic;
7871: }
7872:
7873: span.LC_cusr_subheading {
7874: font-weight: normal;
7875: font-size: 85%;
7876: }
7877:
7878: div.LC_docs_entry_move {
7879: border: 1px solid #BBBBBB;
7880: background: #DDDDDD;
7881: width: 22px;
7882: padding: 1px;
7883: margin: 0;
7884: }
7885:
7886: table.LC_data_table tr > td.LC_docs_entry_commands,
7887: table.LC_data_table tr > td.LC_docs_entry_parameter {
7888: font-size: x-small;
7889: }
7890:
7891: .LC_docs_entry_parameter {
7892: white-space: nowrap;
7893: }
7894:
7895: .LC_docs_copy {
7896: color: #000099;
7897: }
7898:
7899: .LC_docs_cut {
7900: color: #550044;
7901: }
7902:
7903: .LC_docs_rename {
7904: color: #009900;
7905: }
7906:
7907: .LC_docs_remove {
7908: color: #990000;
7909: }
7910:
7911: .LC_docs_alias {
7912: color: #440055;
7913: }
7914:
7915: .LC_domprefs_email,
7916: .LC_docs_alias_name,
7917: .LC_docs_reinit_warn,
7918: .LC_docs_ext_edit {
7919: font-size: x-small;
7920: }
7921:
7922: table.LC_docs_adddocs td,
7923: table.LC_docs_adddocs th {
7924: border: 1px solid #BBBBBB;
7925: padding: 4px;
7926: background: #DDDDDD;
7927: }
7928:
7929: table.LC_sty_begin {
7930: background: #BBFFBB;
7931: }
7932:
7933: table.LC_sty_end {
7934: background: #FFBBBB;
7935: }
7936:
7937: table.LC_double_column {
7938: border-width: 0;
7939: border-collapse: collapse;
7940: width: 100%;
7941: padding: 2px;
7942: }
7943:
7944: table.LC_double_column tr td.LC_left_col {
7945: top: 2px;
7946: left: 2px;
7947: width: 47%;
7948: vertical-align: top;
7949: }
7950:
7951: table.LC_double_column tr td.LC_right_col {
7952: top: 2px;
7953: right: 2px;
7954: width: 47%;
7955: vertical-align: top;
7956: }
7957:
7958: div.LC_left_float {
7959: float: left;
7960: padding-right: 5%;
7961: padding-bottom: 4px;
7962: }
7963:
7964: div.LC_clear_float_header {
7965: padding-bottom: 2px;
7966: }
7967:
7968: div.LC_clear_float_footer {
7969: padding-top: 10px;
7970: clear: both;
7971: }
7972:
7973: div.LC_grade_show_user {
7974: /* border-left: 5px solid $sidebg; */
7975: border-top: 5px solid #000000;
7976: margin: 50px 0 0 0;
7977: padding: 15px 0 5px 10px;
7978: }
7979:
7980: div.LC_grade_show_user_odd_row {
7981: /* border-left: 5px solid #000000; */
7982: }
7983:
7984: div.LC_grade_show_user div.LC_Box {
7985: margin-right: 50px;
7986: }
7987:
7988: div.LC_grade_submissions,
7989: div.LC_grade_message_center,
7990: div.LC_grade_info_links {
7991: margin: 5px;
7992: width: 99%;
7993: background: #FFFFFF;
7994: }
7995:
7996: div.LC_grade_submissions_header,
7997: div.LC_grade_message_center_header {
7998: font-weight: bold;
7999: font-size: large;
8000: }
8001:
8002: div.LC_grade_submissions_body,
8003: div.LC_grade_message_center_body {
8004: border: 1px solid black;
8005: width: 99%;
8006: background: #FFFFFF;
8007: }
8008:
8009: table.LC_scantron_action {
8010: width: 100%;
8011: }
8012:
8013: table.LC_scantron_action tr th {
8014: font-weight:bold;
8015: font-style:normal;
8016: }
8017:
8018: .LC_edit_problem_header,
8019: div.LC_edit_problem_footer {
8020: font-weight: normal;
8021: font-size: medium;
8022: margin: 2px;
8023: background-color: $sidebg;
8024: }
8025:
8026: div.LC_edit_problem_header,
8027: div.LC_edit_problem_header div,
8028: div.LC_edit_problem_footer,
8029: div.LC_edit_problem_footer div,
8030: div.LC_edit_problem_editxml_header,
8031: div.LC_edit_problem_editxml_header div {
8032: z-index: 100;
8033: }
8034:
8035: div.LC_edit_problem_header_title {
8036: font-weight: bold;
8037: font-size: larger;
8038: background: $tabbg;
8039: padding: 3px;
8040: margin: 0 0 5px 0;
8041: }
8042:
8043: table.LC_edit_problem_header_title {
8044: width: 100%;
8045: background: $tabbg;
8046: }
8047:
8048: div.LC_edit_actionbar {
8049: background-color: $sidebg;
8050: margin: 0;
8051: padding: 0;
8052: line-height: 200%;
8053: }
8054:
8055: div.LC_edit_actionbar div{
8056: padding: 0;
8057: margin: 0;
8058: display: inline-block;
8059: }
8060:
8061: .LC_edit_opt {
8062: padding-left: 1em;
8063: white-space: nowrap;
8064: }
8065:
8066: .LC_edit_problem_latexhelper{
8067: text-align: right;
8068: }
8069:
8070: #LC_edit_problem_colorful div{
8071: margin-left: 40px;
8072: }
8073:
8074: #LC_edit_problem_codemirror div{
8075: margin-left: 0px;
8076: }
8077:
8078: img.stift {
8079: border-width: 0;
8080: vertical-align: middle;
8081: }
8082:
8083: table td.LC_mainmenu_col_fieldset {
8084: vertical-align: top;
8085: }
8086:
8087: div.LC_createcourse {
8088: margin: 10px 10px 10px 10px;
8089: }
8090:
8091: .LC_dccid {
8092: float: right;
8093: margin: 0.2em 0 0 0;
8094: padding: 0;
8095: font-size: 90%;
8096: display:none;
8097: }
8098:
8099: ol.LC_primary_menu a:hover,
8100: ol#LC_MenuBreadcrumbs a:hover,
8101: ol#LC_PathBreadcrumbs a:hover,
8102: ul#LC_secondary_menu a:hover,
8103: .LC_FormSectionClearButton input:hover
8104: ul.LC_TabContent li:hover a {
8105: color:$button_hover;
8106: text-decoration:none;
8107: }
8108:
8109: h1 {
8110: padding: 0;
8111: line-height:130%;
8112: }
8113:
8114: h2,
8115: h3,
8116: h4,
8117: h5,
8118: h6 {
8119: margin: 5px 0 5px 0;
8120: padding: 0;
8121: line-height:130%;
8122: }
8123:
8124: .LC_hcell {
8125: padding:3px 15px 3px 15px;
8126: margin: 0;
8127: background-color:$tabbg;
8128: color:$fontmenu;
8129: border-bottom:solid 1px $lg_border_color;
8130: }
8131:
8132: .LC_Box > .LC_hcell {
8133: margin: 0 -10px 10px -10px;
8134: }
8135:
8136: .LC_noBorder {
8137: border: 0;
8138: }
8139:
8140: .LC_FormSectionClearButton input {
8141: background-color:transparent;
8142: border: none;
8143: cursor:pointer;
8144: text-decoration:underline;
8145: }
8146:
8147: .LC_help_open_topic {
8148: color: #FFFFFF;
8149: background-color: #EEEEFF;
8150: margin: 1px;
8151: padding: 4px;
8152: border: 1px solid #000033;
8153: white-space: nowrap;
8154: /* vertical-align: middle; */
8155: }
8156:
8157: dl,
8158: ul,
8159: div,
8160: fieldset {
8161: margin: 10px 10px 10px 0;
8162: /* overflow: hidden; */
8163: }
8164:
8165: fieldset#LC_selectuser {
8166: margin: 0;
8167: padding: 0;
8168: }
8169:
8170: article.geogebraweb div {
8171: margin: 0;
8172: }
8173:
8174: fieldset > legend {
8175: font-weight: bold;
8176: padding: 0 5px 0 5px;
8177: }
8178:
8179: #LC_nav_bar {
8180: float: left;
8181: background-color: $pgbg_or_bgcolor;
8182: margin: 0 0 2px 0;
8183: }
8184:
8185: #LC_realm {
8186: margin: 0.2em 0 0 0;
8187: padding: 0;
8188: font-weight: bold;
8189: text-align: center;
8190: background-color: $pgbg_or_bgcolor;
8191: }
8192:
8193: #LC_nav_bar em {
8194: font-weight: bold;
8195: font-style: normal;
8196: }
8197:
8198: ol.LC_primary_menu {
8199: margin: 0;
8200: padding: 0;
8201: }
8202:
8203: ol#LC_PathBreadcrumbs {
8204: margin: 0;
8205: }
8206:
8207: ol.LC_primary_menu li {
8208: color: RGB(80, 80, 80);
8209: vertical-align: middle;
8210: text-align: left;
8211: list-style: none;
8212: position: relative;
8213: float: left;
8214: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
8215: line-height: 1.5em;
8216: }
8217:
8218: ol.LC_primary_menu li a,
8219: ol.LC_primary_menu li p {
8220: display: block;
8221: margin: 0;
8222: padding: 0 5px 0 10px;
8223: text-decoration: none;
8224: }
8225:
8226: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
8227: display: inline-block;
8228: width: 95%;
8229: text-align: left;
8230: }
8231:
8232: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
8233: display: inline-block;
8234: width: 5%;
8235: float: right;
8236: text-align: right;
8237: font-size: 70%;
8238: }
8239:
8240: ol.LC_primary_menu ul {
8241: display: none;
8242: width: 15em;
8243: background-color: $data_table_light;
8244: position: absolute;
8245: top: 100%;
8246: }
8247:
8248: ol.LC_primary_menu ul ul {
8249: left: 100%;
8250: top: 0;
8251: }
8252:
8253: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
8254: display: block;
8255: position: absolute;
8256: margin: 0;
8257: padding: 0;
8258: z-index: 2;
8259: }
8260:
8261: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
8262: /* First Submenu -> size should be smaller than the menu title of the whole menu */
8263: font-size: 90%;
8264: vertical-align: top;
8265: float: none;
8266: border-left: 1px solid black;
8267: border-right: 1px solid black;
8268: /* A dark bottom border to visualize different menu options;
8269: overwritten in the create_submenu routine for the last border-bottom of the menu */
8270: border-bottom: 1px solid $data_table_dark;
8271: }
8272:
8273: ol.LC_primary_menu li li p:hover {
8274: color:$button_hover;
8275: text-decoration:none;
8276: background-color:$data_table_dark;
8277: }
8278:
8279: ol.LC_primary_menu li li a:hover {
8280: color:$button_hover;
8281: background-color:$data_table_dark;
8282: }
8283:
8284: /* Font-size equal to the size of the predecessors*/
8285: ol.LC_primary_menu li:hover li li {
8286: font-size: 100%;
8287: }
8288:
8289: ol.LC_primary_menu li img {
8290: vertical-align: bottom;
8291: height: 1.1em;
8292: margin: 0.2em 0 0 0;
8293: }
8294:
8295: ol.LC_primary_menu a {
8296: color: RGB(80, 80, 80);
8297: text-decoration: none;
8298: }
8299:
8300: ol.LC_primary_menu a.LC_new_message {
8301: font-weight:bold;
8302: color: darkred;
8303: }
8304:
8305: ol.LC_docs_parameters {
8306: margin-left: 0;
8307: padding: 0;
8308: list-style: none;
8309: }
8310:
8311: ol.LC_docs_parameters li {
8312: margin: 0;
8313: padding-right: 20px;
8314: display: inline;
8315: }
8316:
8317: ol.LC_docs_parameters li:before {
8318: content: "\\002022 \\0020";
8319: }
8320:
8321: li.LC_docs_parameters_title {
8322: font-weight: bold;
8323: }
8324:
8325: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
8326: content: "";
8327: }
8328:
8329: ul#LC_secondary_menu {
8330: clear: right;
8331: color: $fontmenu;
8332: background: $tabbg;
8333: list-style: none;
8334: padding: 0;
8335: margin: 0;
8336: width: 100%;
8337: text-align: left;
8338: float: left;
8339: }
8340:
8341: ul#LC_secondary_menu li {
8342: font-weight: bold;
8343: line-height: 1.8em;
8344: border-right: 1px solid black;
8345: float: left;
8346: }
8347:
8348: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
8349: background-color: $data_table_light;
8350: }
8351:
8352: ul#LC_secondary_menu li a {
8353: padding: 0 0.8em;
8354: }
8355:
8356: ul#LC_secondary_menu li ul {
8357: display: none;
8358: }
8359:
8360: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
8361: display: block;
8362: position: absolute;
8363: margin: 0;
8364: padding: 0;
8365: list-style:none;
8366: float: none;
8367: background-color: $data_table_light;
8368: z-index: 2;
8369: margin-left: -1px;
8370: }
8371:
8372: ul#LC_secondary_menu li ul li {
8373: font-size: 90%;
8374: vertical-align: top;
8375: border-left: 1px solid black;
8376: border-right: 1px solid black;
8377: background-color: $data_table_light;
8378: list-style:none;
8379: float: none;
8380: }
8381:
8382: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
8383: background-color: $data_table_dark;
8384: }
8385:
8386: ul.LC_TabContent {
8387: display:block;
8388: background: $sidebg;
8389: border-bottom: solid 1px $lg_border_color;
8390: list-style:none;
8391: margin: -1px -10px 0 -10px;
8392: padding: 0;
8393: }
8394:
8395: ul.LC_TabContent li,
8396: ul.LC_TabContentBigger li {
8397: float:left;
8398: }
8399:
8400: ul#LC_secondary_menu li a {
8401: color: $fontmenu;
8402: text-decoration: none;
8403: }
8404:
8405: ul.LC_TabContent {
8406: min-height:20px;
8407: }
8408:
8409: ul.LC_TabContent li {
8410: vertical-align:middle;
8411: padding: 0 16px 0 10px;
8412: background-color:$tabbg;
8413: border-bottom:solid 1px $lg_border_color;
8414: border-left: solid 1px $font;
8415: }
8416:
8417: ul.LC_TabContent .right {
8418: float:right;
8419: }
8420:
8421: ul.LC_TabContent li a,
8422: ul.LC_TabContent li {
8423: color:rgb(47,47,47);
8424: text-decoration:none;
8425: font-size:95%;
8426: font-weight:bold;
8427: min-height:20px;
8428: }
8429:
8430: ul.LC_TabContent li a:hover,
8431: ul.LC_TabContent li a:focus {
8432: color: $button_hover;
8433: background:none;
8434: outline:none;
8435: }
8436:
8437: ul.LC_TabContent li:hover {
8438: color: $button_hover;
8439: cursor:pointer;
8440: }
8441:
8442: ul.LC_TabContent li.active {
8443: color: $font;
8444: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
8445: border-bottom:solid 1px #FFFFFF;
8446: cursor: default;
8447: }
8448:
8449: ul.LC_TabContent li.active a {
8450: color:$font;
8451: background:#FFFFFF;
8452: outline: none;
8453: }
8454:
8455: ul.LC_TabContent li.goback {
8456: float: left;
8457: border-left: none;
8458: }
8459:
8460: #maincoursedoc {
8461: clear:both;
8462: }
8463:
8464: ul.LC_TabContentBigger {
8465: display:block;
8466: list-style:none;
8467: padding: 0;
8468: }
8469:
8470: ul.LC_TabContentBigger li {
8471: vertical-align:bottom;
8472: height: 30px;
8473: font-size:110%;
8474: font-weight:bold;
8475: color: #737373;
8476: }
8477:
8478: ul.LC_TabContentBigger li.active {
8479: position: relative;
8480: top: 1px;
8481: }
8482:
8483: ul.LC_TabContentBigger li a {
8484: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
8485: height: 30px;
8486: line-height: 30px;
8487: text-align: center;
8488: display: block;
8489: text-decoration: none;
8490: outline: none;
8491: }
8492:
8493: ul.LC_TabContentBigger li.active a {
8494: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
8495: color:$font;
8496: }
8497:
8498: ul.LC_TabContentBigger li b {
8499: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
8500: display: block;
8501: float: left;
8502: padding: 0 30px;
8503: border-bottom: 1px solid $lg_border_color;
8504: }
8505:
8506: ul.LC_TabContentBigger li:hover b {
8507: color:$button_hover;
8508: }
8509:
8510: ul.LC_TabContentBigger li.active b {
8511: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
8512: color:$font;
8513: border: 0;
8514: }
8515:
8516:
8517: ul.LC_CourseBreadcrumbs {
8518: background: $sidebg;
8519: height: 2em;
8520: padding-left: 10px;
8521: margin: 0;
8522: list-style-position: inside;
8523: }
8524:
8525: ol#LC_MenuBreadcrumbs,
8526: ol#LC_PathBreadcrumbs {
8527: padding-left: 10px;
8528: margin: 0;
8529: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
8530: }
8531:
8532: ol#LC_MenuBreadcrumbs li,
8533: ol#LC_PathBreadcrumbs li,
8534: ul.LC_CourseBreadcrumbs li {
8535: display: inline;
8536: white-space: normal;
8537: }
8538:
8539: ol#LC_MenuBreadcrumbs li a,
8540: ul.LC_CourseBreadcrumbs li a {
8541: text-decoration: none;
8542: font-size:90%;
8543: }
8544:
8545: ol#LC_MenuBreadcrumbs h1 {
8546: display: inline;
8547: font-size: 90%;
8548: line-height: 2.5em;
8549: margin: 0;
8550: padding: 0;
8551: }
8552:
8553: ol#LC_PathBreadcrumbs li a {
8554: text-decoration:none;
8555: font-size:100%;
8556: font-weight:bold;
8557: }
8558:
8559: .LC_Box {
8560: border: solid 1px $lg_border_color;
8561: padding: 0 10px 10px 10px;
8562: }
8563:
8564: .LC_DocsBox {
8565: border: solid 1px $lg_border_color;
8566: padding: 0 0 10px 10px;
8567: }
8568:
8569: .LC_AboutMe_Image {
8570: float:left;
8571: margin-right:10px;
8572: }
8573:
8574: .LC_Clear_AboutMe_Image {
8575: clear:left;
8576: }
8577:
8578: dl.LC_ListStyleClean dt {
8579: padding-right: 5px;
8580: display: table-header-group;
8581: }
8582:
8583: dl.LC_ListStyleClean dd {
8584: display: table-row;
8585: }
8586:
8587: .LC_ListStyleClean,
8588: .LC_ListStyleSimple,
8589: .LC_ListStyleNormal,
8590: .LC_ListStyleSpecial {
8591: /* display:block; */
8592: list-style-position: inside;
8593: list-style-type: none;
8594: overflow: hidden;
8595: padding: 0;
8596: }
8597:
8598: .LC_ListStyleSimple li,
8599: .LC_ListStyleSimple dd,
8600: .LC_ListStyleNormal li,
8601: .LC_ListStyleNormal dd,
8602: .LC_ListStyleSpecial li,
8603: .LC_ListStyleSpecial dd {
8604: margin: 0;
8605: padding: 5px 5px 5px 10px;
8606: clear: both;
8607: }
8608:
8609: .LC_ListStyleClean li,
8610: .LC_ListStyleClean dd {
8611: padding-top: 0;
8612: padding-bottom: 0;
8613: }
8614:
8615: .LC_ListStyleSimple dd,
8616: .LC_ListStyleSimple li {
8617: border-bottom: solid 1px $lg_border_color;
8618: }
8619:
8620: .LC_ListStyleSpecial li,
8621: .LC_ListStyleSpecial dd {
8622: list-style-type: none;
8623: background-color: RGB(220, 220, 220);
8624: margin-bottom: 4px;
8625: }
8626:
8627: table.LC_SimpleTable {
8628: margin:5px;
8629: border:solid 1px $lg_border_color;
8630: }
8631:
8632: table.LC_SimpleTable tr {
8633: padding: 0;
8634: border:solid 1px $lg_border_color;
8635: }
8636:
8637: table.LC_SimpleTable thead {
8638: background:rgb(220,220,220);
8639: }
8640:
8641: div.LC_columnSection {
8642: display: block;
8643: clear: both;
8644: overflow: hidden;
8645: margin: 0;
8646: }
8647:
8648: div.LC_columnSection>* {
8649: float: left;
8650: margin: 10px 20px 10px 0;
8651: overflow:hidden;
8652: }
8653:
8654: table em {
8655: font-weight: bold;
8656: font-style: normal;
8657: }
8658:
8659: table.LC_tableBrowseRes,
8660: table.LC_tableOfContent {
8661: border:none;
8662: border-spacing: 1px;
8663: padding: 3px;
8664: background-color: #FFFFFF;
8665: font-size: 90%;
8666: }
8667:
8668: table.LC_tableOfContent {
8669: border-collapse: collapse;
8670: }
8671:
8672: table.LC_tableBrowseRes a,
8673: table.LC_tableOfContent a {
8674: background-color: transparent;
8675: text-decoration: none;
8676: }
8677:
8678: table.LC_tableOfContent img {
8679: border: none;
8680: height: 1.3em;
8681: vertical-align: text-bottom;
8682: margin-right: 0.3em;
8683: }
8684:
8685: a#LC_content_toolbar_firsthomework {
8686: background-image:url(/res/adm/pages/open-first-problem.gif);
8687: }
8688:
8689: a#LC_content_toolbar_everything {
8690: background-image:url(/res/adm/pages/show-all.gif);
8691: }
8692:
8693: a#LC_content_toolbar_uncompleted {
8694: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
8695: }
8696:
8697: #LC_content_toolbar_clearbubbles {
8698: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
8699: }
8700:
8701: a#LC_content_toolbar_changefolder {
8702: background : url(/res/adm/pages/close-all-folders.gif) top center ;
8703: }
8704:
8705: a#LC_content_toolbar_changefolder_toggled {
8706: background-image:url(/res/adm/pages/open-all-folders.gif);
8707: }
8708:
8709: a#LC_content_toolbar_edittoplevel {
8710: background-image:url(/res/adm/pages/edittoplevel.gif);
8711: }
8712:
8713: a#LC_content_toolbar_printout {
8714: background-image:url(/res/adm/pages/printout.gif);
8715: }
8716:
8717: ul#LC_toolbar li a:hover {
8718: background-position: bottom center;
8719: }
8720:
8721: ul#LC_toolbar {
8722: padding: 0;
8723: margin: 2px;
8724: list-style:none;
8725: position:relative;
8726: background-color:white;
8727: overflow: auto;
8728: }
8729:
8730: ul#LC_toolbar li {
8731: border:1px solid white;
8732: padding: 0;
8733: margin: 0;
8734: float: left;
8735: display:inline;
8736: vertical-align:middle;
8737: white-space: nowrap;
8738: }
8739:
8740:
8741: a.LC_toolbarItem {
8742: display:block;
8743: padding: 0;
8744: margin: 0;
8745: height: 32px;
8746: width: 32px;
8747: color:white;
8748: border: none;
8749: background-repeat:no-repeat;
8750: background-color:transparent;
8751: }
8752:
8753: ul.LC_funclist {
8754: margin: 0;
8755: padding: 0.5em 1em 0.5em 0;
8756: }
8757:
8758: ul.LC_funclist > li:first-child {
8759: font-weight:bold;
8760: margin-left:0.8em;
8761: }
8762:
8763: ul.LC_funclist + ul.LC_funclist {
8764: /*
8765: left border as a seperator if we have more than
8766: one list
8767: */
8768: border-left: 1px solid $sidebg;
8769: /*
8770: this hides the left border behind the border of the
8771: outer box if element is wrapped to the next 'line'
8772: */
8773: margin-left: -1px;
8774: }
8775:
8776: ul.LC_funclist li {
8777: display: inline;
8778: white-space: nowrap;
8779: margin: 0 0 0 25px;
8780: line-height: 150%;
8781: }
8782:
8783: .LC_hidden {
8784: display: none;
8785: }
8786:
8787: .LCmodal-overlay {
8788: position:fixed;
8789: top:0;
8790: right:0;
8791: bottom:0;
8792: left:0;
8793: height:100%;
8794: width:100%;
8795: margin:0;
8796: padding:0;
8797: background:#999;
8798: opacity:.75;
8799: filter: alpha(opacity=75);
8800: -moz-opacity: 0.75;
8801: z-index:101;
8802: }
8803:
8804: * html .LCmodal-overlay {
8805: position: absolute;
8806: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
8807: }
8808:
8809: .LCmodal-window {
8810: position:fixed;
8811: top:50%;
8812: left:50%;
8813: margin:0;
8814: padding:0;
8815: z-index:102;
8816: }
8817:
8818: * html .LCmodal-window {
8819: position:absolute;
8820: }
8821:
8822: .LCclose-window {
8823: position:absolute;
8824: width:32px;
8825: height:32px;
8826: right:8px;
8827: top:8px;
8828: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
8829: text-indent:-99999px;
8830: overflow:hidden;
8831: cursor:pointer;
8832: }
8833:
8834: .LCisDisabled {
8835: cursor: not-allowed;
8836: opacity: 0.5;
8837: }
8838:
8839: a[aria-disabled="true"] {
8840: color: currentColor;
8841: display: inline-block; /* For IE11/ MS Edge bug */
8842: pointer-events: none;
8843: text-decoration: none;
8844: }
8845:
8846: pre.LC_wordwrap {
8847: white-space: pre-wrap;
8848: white-space: -moz-pre-wrap;
8849: white-space: -pre-wrap;
8850: white-space: -o-pre-wrap;
8851: word-wrap: break-word;
8852: }
8853:
8854: /*
8855: styles used for response display
8856: */
8857: div.LC_radiofoil, div.LC_rankfoil {
8858: margin: .5em 0em .5em 0em;
8859: }
8860: table.LC_itemgroup {
8861: margin-top: 1em;
8862: }
8863:
8864: /*
8865: styles used by TTH when "Default set of options to pass to tth/m
8866: when converting TeX" in course settings has been set
8867:
8868: option passed: -t
8869:
8870: */
8871:
8872: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8873: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8874: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8875: td div.norm {line-height:normal;}
8876:
8877: /*
8878: option passed -y3
8879: */
8880:
8881: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8882: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8883: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8884:
8885: /*
8886: sections with roles, for content only
8887: */
8888: section[class^="role-"] {
8889: padding-left: 10px;
8890: padding-right: 5px;
8891: margin-top: 8px;
8892: margin-bottom: 8px;
8893: border: 1px solid #2A4;
8894: border-radius: 5px;
8895: box-shadow: 0px 1px 1px #BBB;
8896: }
8897: section[class^="role-"]>h1 {
8898: position: relative;
8899: margin: 0px;
8900: padding-top: 10px;
8901: padding-left: 40px;
8902: }
8903: section[class^="role-"]>h1:before {
8904: position: absolute;
8905: left: -5px;
8906: top: 5px;
8907: }
8908: section.role-activity>h1:before {
8909: content:url('/adm/daxe/images/section_icons/activity.png');
8910: }
8911: section.role-advice>h1:before {
8912: content:url('/adm/daxe/images/section_icons/advice.png');
8913: }
8914: section.role-bibliography>h1:before {
8915: content:url('/adm/daxe/images/section_icons/bibliography.png');
8916: }
8917: section.role-citation>h1:before {
8918: content:url('/adm/daxe/images/section_icons/citation.png');
8919: }
8920: section.role-conclusion>h1:before {
8921: content:url('/adm/daxe/images/section_icons/conclusion.png');
8922: }
8923: section.role-definition>h1:before {
8924: content:url('/adm/daxe/images/section_icons/definition.png');
8925: }
8926: section.role-demonstration>h1:before {
8927: content:url('/adm/daxe/images/section_icons/demonstration.png');
8928: }
8929: section.role-example>h1:before {
8930: content:url('/adm/daxe/images/section_icons/example.png');
8931: }
8932: section.role-explanation>h1:before {
8933: content:url('/adm/daxe/images/section_icons/explanation.png');
8934: }
8935: section.role-introduction>h1:before {
8936: content:url('/adm/daxe/images/section_icons/introduction.png');
8937: }
8938: section.role-method>h1:before {
8939: content:url('/adm/daxe/images/section_icons/method.png');
8940: }
8941: section.role-more_information>h1:before {
8942: content:url('/adm/daxe/images/section_icons/more_information.png');
8943: }
8944: section.role-objectives>h1:before {
8945: content:url('/adm/daxe/images/section_icons/objectives.png');
8946: }
8947: section.role-prerequisites>h1:before {
8948: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8949: }
8950: section.role-remark>h1:before {
8951: content:url('/adm/daxe/images/section_icons/remark.png');
8952: }
8953: section.role-reminder>h1:before {
8954: content:url('/adm/daxe/images/section_icons/reminder.png');
8955: }
8956: section.role-summary>h1:before {
8957: content:url('/adm/daxe/images/section_icons/summary.png');
8958: }
8959: section.role-syntax>h1:before {
8960: content:url('/adm/daxe/images/section_icons/syntax.png');
8961: }
8962: section.role-warning>h1:before {
8963: content:url('/adm/daxe/images/section_icons/warning.png');
8964: }
8965:
8966: #LC_minitab_header {
8967: float:left;
8968: width:100%;
8969: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
8970: font-size:93%;
8971: line-height:normal;
8972: margin: 0.5em 0 0.5em 0;
8973: }
8974: #LC_minitab_header ul {
8975: margin:0;
8976: padding:10px 10px 0;
8977: list-style:none;
8978: }
8979: #LC_minitab_header li {
8980: float:left;
8981: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
8982: margin:0;
8983: padding:0 0 0 9px;
8984: }
8985: #LC_minitab_header a {
8986: display:block;
8987: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
8988: padding:5px 15px 4px 6px;
8989: }
8990: #LC_minitab_header #LC_current_minitab {
8991: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
8992: }
8993: #LC_minitab_header #LC_current_minitab a {
8994: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
8995: padding-bottom:5px;
8996: }
8997:
8998:
8999: END
9000: }
9001:
9002: =pod
9003:
9004: =item * &headtag()
9005:
9006: Returns a uniform footer for LON-CAPA web pages.
9007:
9008: Inputs: $title - optional title for the head
9009: $head_extra - optional extra HTML to put inside the <head>
9010: $args - optional arguments
9011: force_register - if is true call registerurl so the remote is
9012: informed
9013: redirect -> array ref of
9014: 1- seconds before redirect occurs
9015: 2- url to redirect to
9016: 3- whether the side effect should occur
9017: (side effect of setting
9018: $env{'internal.head.redirect'} to the url
9019: redirected to)
9020: 4- whether the redirect target should be
9021: the opener of the current (pop-up)
9022: window (side effect of setting
9023: $env{'internal.head.to_opener'} to
9024: 1, if true.
9025: 5- whether encrypt check should be skipped
9026: domain -> force to color decorate a page for a specific
9027: domain
9028: function -> force usage of a specific rolish color scheme
9029: bgcolor -> override the default page bgcolor
9030: no_auto_mt_title
9031: -> prevent &mt()ing the title arg
9032:
9033: =cut
9034:
9035: sub headtag {
9036: my ($title,$head_extra,$args) = @_;
9037:
9038: my $function = $args->{'function'} || &get_users_function();
9039: my $domain = $args->{'domain'} || &determinedomain();
9040: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
9041: my $httphost = $args->{'use_absolute'};
9042: my $url = join(':',$env{'user.name'},$env{'user.domain'},
9043: $Apache::lonnet::perlvar{'lonVersion'},
9044: #time(),
9045: $env{'environment.color.timestamp'},
9046: $function,$domain,$bgcolor);
9047:
9048: $url = '/adm/css/'.&escape($url).'.css';
9049:
9050: my $result =
9051: '<head>'.
9052: &font_settings($args);
9053:
9054: my $inhibitprint;
9055: if ($args->{'print_suppress'}) {
9056: $inhibitprint = &print_suppression();
9057: }
9058:
9059: if (!$args->{'frameset'}) {
9060: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
9061: }
9062: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
9063: $result .= Apache::lonxml::display_title();
9064: }
9065: if (!$args->{'no_nav_bar'}
9066: && !$args->{'only_body'}
9067: && !$args->{'frameset'}) {
9068: $result .= &help_menu_js($httphost);
9069: $result.=&modal_window();
9070: $result.=&togglebox_script();
9071: $result.=&wishlist_window();
9072: $result.=&LCprogressbarUpdate_script();
9073: } else {
9074: if ($args->{'add_modal'}) {
9075: $result.=&modal_window();
9076: }
9077: if ($args->{'add_wishlist'}) {
9078: $result.=&wishlist_window();
9079: }
9080: if ($args->{'add_togglebox'}) {
9081: $result.=&togglebox_script();
9082: }
9083: if ($args->{'add_progressbar'}) {
9084: $result.=&LCprogressbarUpdate_script();
9085: }
9086: }
9087: if (ref($args->{'redirect'})) {
9088: my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
9089: if (!$skip_enc_check) {
9090: $url = &Apache::lonenc::check_encrypt($url);
9091: }
9092: if (!$inhibit_continue) {
9093: $env{'internal.head.redirect'} = $url;
9094: }
9095: $result.=<<"ADDMETA";
9096: <meta http-equiv="pragma" content="no-cache" />
9097: ADDMETA
9098: if ($to_opener) {
9099: $env{'internal.head.to_opener'} = 1;
9100: my $dest = &js_escape($url);
9101: my $timeout = int($time * 1000);
9102: $result .=<<"ENDJS";
9103: <script type="text/javascript">
9104: // <![CDATA[
9105: function LC_To_Opener() {
9106: var dest = '$dest';
9107: if (dest != '') {
9108: if (window.opener != null && !window.opener.closed) {
9109: window.opener.location.href=dest;
9110: window.close();
9111: } else {
9112: window.location.href=dest;
9113: }
9114: }
9115: }
9116: \$(document).ready(function () {
9117: setTimeout('LC_To_Opener()',$timeout);
9118: });
9119: // ]]>
9120: </script>
9121: ENDJS
9122: } else {
9123: $result.=<<"ADDMETA";
9124: <meta http-equiv="Refresh" content="$time; url=$url" />
9125: ADDMETA
9126: }
9127: } else {
9128: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
9129: my $requrl = $env{'request.uri'};
9130: if ($requrl eq '') {
9131: $requrl = $ENV{'REQUEST_URI'};
9132: $requrl =~ s/\?.+$//;
9133: }
9134: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
9135: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
9136: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
9137: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
9138: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
9139: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
9140: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
9141: my ($offload,$offloadoth);
9142: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
9143: if ($domdefs{'offloadnow'}{$lonhost}) {
9144: $offload = 1;
9145: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
9146: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
9147: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
9148: $offloadoth = 1;
9149: $dom_in_use = $env{'user.domain'};
9150: }
9151: }
9152: }
9153: }
9154: unless ($offload) {
9155: if (ref($domdefs{'offloadoth'}) eq 'HASH') {
9156: if ($domdefs{'offloadoth'}{$lonhost}) {
9157: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
9158: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
9159: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
9160: $offload = 1;
9161: $offloadoth = 1;
9162: $dom_in_use = $env{'user.domain'};
9163: }
9164: }
9165: }
9166: }
9167: }
9168: if ($offload) {
9169: my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
9170: if (($newserver eq '') && ($offloadoth)) {
9171: my @domains = &Apache::lonnet::current_machine_domains();
9172: if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
9173: ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
9174: }
9175: }
9176: if (($newserver) && ($newserver ne $lonhost)) {
9177: my $numsec = 5;
9178: my $timeout = $numsec * 1000;
9179: my ($newurl,$locknum,%locks,$msg);
9180: if ($env{'request.role.adv'}) {
9181: ($locknum,%locks) = &Apache::lonnet::get_locks();
9182: }
9183: my $disable_submit = 0;
9184: if ($requrl =~ /$LONCAPA::assess_re/) {
9185: $disable_submit = 1;
9186: }
9187: if ($locknum) {
9188: my @lockinfo = sort(values(%locks));
9189: $msg = &mt('Once the following tasks are complete:')." \n".
9190: join(", ",sort(values(%locks)))."\n";
9191: if (&show_course()) {
9192: $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
9193: } else {
9194: $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
9195: }
9196: } else {
9197: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
9198: $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
9199: }
9200: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
9201: $newurl = '/adm/switchserver?otherserver='.$newserver;
9202: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
9203: $newurl .= '&role='.$env{'request.role'};
9204: }
9205: if ($env{'request.symb'}) {
9206: my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
9207: if ($shownsymb =~ m{^/enc/}) {
9208: my $reqdmajor = 2;
9209: my $reqdminor = 11;
9210: my $reqdsubminor = 3;
9211: my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
9212: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
9213: my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
9214: if (($major eq '' && $minor eq '') ||
9215: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
9216: (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
9217: ($reqdsubminor > $subminor))))) {
9218: undef($shownsymb);
9219: }
9220: }
9221: if ($shownsymb) {
9222: &js_escape(\$shownsymb);
9223: $newurl .= '&symb='.$shownsymb;
9224: }
9225: } else {
9226: my $shownurl = &Apache::lonenc::check_encrypt($requrl);
9227: &js_escape(\$shownurl);
9228: $newurl .= '&origurl='.$shownurl;
9229: }
9230: }
9231: &js_escape(\$msg);
9232: $result.=<<OFFLOAD
9233: <meta http-equiv="pragma" content="no-cache" />
9234: <script type="text/javascript">
9235: // <![CDATA[
9236: function LC_Offload_Now() {
9237: var dest = "$newurl";
9238: if (dest != '') {
9239: window.location.href="$newurl";
9240: }
9241: }
9242: \$(document).ready(function () {
9243: window.alert('$msg');
9244: if ($disable_submit) {
9245: \$(".LC_hwk_submit").prop("disabled", true);
9246: \$( ".LC_textline" ).prop( "readonly", "readonly");
9247: }
9248: setTimeout('LC_Offload_Now()', $timeout);
9249: });
9250: // ]]>
9251: </script>
9252: OFFLOAD
9253: }
9254: }
9255: }
9256: }
9257: }
9258: }
9259: if (!defined($title)) {
9260: $title = 'The LearningOnline Network with CAPA';
9261: }
9262: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
9263: $result .= '<title> LON-CAPA '.$title.'</title>'
9264: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
9265: if (!$args->{'frameset'}) {
9266: $result .= ' /';
9267: }
9268: $result .= '>'
9269: .$inhibitprint
9270: .$head_extra;
9271: my $clientmobile;
9272: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
9273: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
9274: } else {
9275: $clientmobile = $env{'browser.mobile'};
9276: }
9277: if ($clientmobile) {
9278: $result .= '
9279: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
9280: <meta name="apple-mobile-web-app-capable" content="yes" />';
9281: }
9282: $result .= '<meta name="google" content="notranslate" />'."\n";
9283: return $result.'</head>';
9284: }
9285:
9286: =pod
9287:
9288: =item * &font_settings()
9289:
9290: Returns neccessary <meta> to set the proper encoding
9291:
9292: Inputs: optional reference to HASH -- $args passed to &headtag()
9293:
9294: =cut
9295:
9296: sub font_settings {
9297: my ($args) = @_;
9298: my $headerstring='';
9299: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
9300: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
9301: $headerstring.=
9302: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
9303: if (!$args->{'frameset'}) {
9304: $headerstring.= ' /';
9305: }
9306: $headerstring .= '>'."\n";
9307: }
9308: return $headerstring;
9309: }
9310:
9311: =pod
9312:
9313: =item * &print_suppression()
9314:
9315: In course context returns css which causes the body to be blank when media="print",
9316: if printout generation is unavailable for the current resource.
9317:
9318: This could be because:
9319:
9320: (a) printstartdate is in the future
9321:
9322: (b) printenddate is in the past
9323:
9324: (c) there is an active exam block with "printout"
9325: functionality blocked
9326:
9327: Users with pav, pfo or evb privileges are exempt.
9328:
9329: Inputs: none
9330:
9331: =cut
9332:
9333:
9334: sub print_suppression {
9335: my $noprint;
9336: if ($env{'request.course.id'}) {
9337: my $scope = $env{'request.course.id'};
9338: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9339: (&Apache::lonnet::allowed('pfo',$scope))) {
9340: return;
9341: }
9342: if ($env{'request.course.sec'} ne '') {
9343: $scope .= "/$env{'request.course.sec'}";
9344: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9345: (&Apache::lonnet::allowed('pfo',$scope))) {
9346: return;
9347: }
9348: }
9349: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9350: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9351: my $clientip = &Apache::lonnet::get_requestor_ip();
9352: my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
9353: if ($blocked) {
9354: my $checkrole = "cm./$cdom/$cnum";
9355: if ($env{'request.course.sec'} ne '') {
9356: $checkrole .= "/$env{'request.course.sec'}";
9357: }
9358: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
9359: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
9360: $noprint = 1;
9361: }
9362: }
9363: unless ($noprint) {
9364: my $symb = &Apache::lonnet::symbread();
9365: if ($symb ne '') {
9366: my $navmap = Apache::lonnavmaps::navmap->new();
9367: if (ref($navmap)) {
9368: my $res = $navmap->getBySymb($symb);
9369: if (ref($res)) {
9370: if (!$res->resprintable()) {
9371: $noprint = 1;
9372: }
9373: }
9374: }
9375: }
9376: }
9377: if ($noprint) {
9378: return <<"ENDSTYLE";
9379: <style type="text/css" media="print">
9380: body { display:none }
9381: </style>
9382: ENDSTYLE
9383: }
9384: }
9385: return;
9386: }
9387:
9388: =pod
9389:
9390: =item * &xml_begin()
9391:
9392: Returns the needed doctype and <html>
9393:
9394: Inputs: none
9395:
9396: =cut
9397:
9398: sub xml_begin {
9399: my ($is_frameset) = @_;
9400: my $output='';
9401:
9402: if ($env{'browser.mathml'}) {
9403: $output='<?xml version="1.0"?>'
9404: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
9405: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
9406:
9407: # .'<!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">] >'
9408: .'<!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">'
9409: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
9410: .'xmlns="http://www.w3.org/1999/xhtml">';
9411: } elsif ($is_frameset) {
9412: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
9413: '<html>'."\n";
9414: } else {
9415: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
9416: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
9417: }
9418: return $output;
9419: }
9420:
9421: =pod
9422:
9423: =item * &start_page()
9424:
9425: Returns a complete <html> .. <body> section for LON-CAPA web pages.
9426:
9427: Inputs:
9428:
9429: =over 4
9430:
9431: $title - optional title for the page
9432:
9433: $head_extra - optional extra HTML to incude inside the <head>
9434:
9435: $args - additional optional args supported are:
9436:
9437: =over 8
9438:
9439: only_body -> is true will set &bodytag() onlybodytag
9440: arg on
9441: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
9442: add_entries -> additional attributes to add to the <body>
9443: domain -> force to color decorate a page for a
9444: specific domain
9445: function -> force usage of a specific rolish color
9446: scheme
9447: redirect -> see &headtag()
9448: bgcolor -> override the default page bg color
9449: js_ready -> return a string ready for being used in
9450: a javascript writeln
9451: html_encode -> return a string ready for being used in
9452: a html attribute
9453: force_register -> if is true will turn on the &bodytag()
9454: $forcereg arg
9455: frameset -> if true will start with a <frameset>
9456: rather than <body>
9457: skip_phases -> hash ref of
9458: head -> skip the <html><head> generation
9459: body -> skip all <body> generation
9460: no_auto_mt_title -> prevent &mt()ing the title arg
9461: bread_crumbs -> Array containing breadcrumbs
9462: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
9463: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
9464: to lonhtmlcommon::breadcrumbs
9465: group -> includes the current group, if page is for a
9466: specific group
9467: use_absolute -> for request for external resource or syllabus, this
9468: will contain https://<hostname> if server uses
9469: https (as per hosts.tab), but request is for http
9470: hostname -> hostname, originally from $r->hostname(), (optional).
9471: links_disabled -> Links in primary and secondary menus are disabled
9472: (Can enable them once page has loaded - see lonroles.pm
9473: for an example).
9474: links_target -> Target for links, e.g., _parent (optional).
9475:
9476: =back
9477:
9478: =back
9479:
9480: =cut
9481:
9482: sub start_page {
9483: my ($title,$head_extra,$args) = @_;
9484: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
9485:
9486: $env{'internal.start_page'}++;
9487: my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
9488:
9489: if (! exists($args->{'skip_phases'}{'head'}) ) {
9490: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
9491: }
9492:
9493: if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
9494: if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
9495: unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
9496: $args->{'no_primary_menu'} = 1;
9497: }
9498: unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
9499: $args->{'no_inline_menu'} = 1;
9500: }
9501: if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
9502: map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
9503: }
9504: } else {
9505: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9506: my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
9507: if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
9508: unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
9509: $args->{'no_primary_menu'} = 1;
9510: }
9511: unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
9512: $args->{'no_inline_menu'} = 1;
9513: }
9514: if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
9515: map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
9516: }
9517: }
9518: }
9519: ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
9520: $env{'course.'.$env{'request.course.id'}.'.domain'},
9521: $env{'course.'.$env{'request.course.id'}.'.num'});
9522: } elsif ($env{'request.course.id'}) {
9523: my $expiretime=600;
9524: if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
9525: &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
9526: }
9527: my ($deeplinkmenu,$menuref);
9528: ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
9529: if ($menucoll) {
9530: if (ref($menuref) eq 'HASH') {
9531: %menu = %{$menuref};
9532: }
9533: if ($menu{'top'} eq 'n') {
9534: $args->{'no_primary_menu'} = 1;
9535: }
9536: if ($menu{'inline'} eq 'n') {
9537: unless (&Apache::lonnet::allowed('opa')) {
9538: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9539: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9540: my $crstype = &course_type();
9541: my $now = time;
9542: my $ccrole;
9543: if ($crstype eq 'Community') {
9544: $ccrole = 'co';
9545: } else {
9546: $ccrole = 'cc';
9547: }
9548: if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
9549: my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
9550: if ((($start) && ($start<0)) ||
9551: (($end) && ($end<$now)) ||
9552: (($start) && ($now<$start))) {
9553: $args->{'no_inline_menu'} = 1;
9554: }
9555: } else {
9556: $args->{'no_inline_menu'} = 1;
9557: }
9558: }
9559: }
9560: }
9561: }
9562:
9563: my $showncrumbs;
9564: if (! exists($args->{'skip_phases'}{'body'}) ) {
9565: if ($args->{'frameset'}) {
9566: my $attr_string = &make_attr_string($args->{'force_register'},
9567: $args->{'add_entries'});
9568: $result .= "\n<frameset $attr_string>\n";
9569: } else {
9570: $result .=
9571: &bodytag($title,
9572: $args->{'function'}, $args->{'add_entries'},
9573: $args->{'only_body'}, $args->{'domain'},
9574: $args->{'force_register'}, $args->{'no_nav_bar'},
9575: $args->{'bgcolor'}, $args,
9576: \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
9577: \%menu,\$showncrumbs);
9578: }
9579: }
9580:
9581: if ($args->{'js_ready'}) {
9582: $result = &js_ready($result);
9583: }
9584: if ($args->{'html_encode'}) {
9585: $result = &html_encode($result);
9586: }
9587:
9588: # Preparation for new and consistent functionlist at top of screen
9589: # if ($args->{'functionlist'}) {
9590: # $result .= &build_functionlist();
9591: #}
9592:
9593: # Don't add anything more if only_body wanted or in const space
9594: return $result if $args->{'only_body'}
9595: || $env{'request.state'} eq 'construct';
9596:
9597: #Breadcrumbs
9598: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
9599: unless ($showncrumbs) {
9600: &Apache::lonhtmlcommon::clear_breadcrumbs();
9601: #if any br links exists, add them to the breadcrumbs
9602: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
9603: foreach my $crumb (@{$args->{'bread_crumbs'}}){
9604: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
9605: }
9606: }
9607: # if @advtools array contains items add then to the breadcrumbs
9608: if (@advtools > 0) {
9609: &Apache::lonmenu::advtools_crumbs(@advtools);
9610: }
9611: my $menulink;
9612: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
9613: if ((exists($args->{'bread_crumbs_nomenu'})) ||
9614: ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
9615: ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
9616: ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
9617: (!$env{'request.role.adv'}))) {
9618: $menulink = 0;
9619: } else {
9620: undef($menulink);
9621: }
9622: my $linkprotout;
9623: if ($env{'request.deeplink.login'}) {
9624: my $linkprotout = &Apache::lonmenu::linkprot_exit();
9625: if ($linkprotout) {
9626: &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
9627: }
9628: }
9629: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
9630: if(exists($args->{'bread_crumbs_component'})){
9631: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
9632: } else {
9633: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
9634: }
9635: }
9636: }
9637: return $result;
9638: }
9639:
9640: sub end_page {
9641: my ($args) = @_;
9642: $env{'internal.end_page'}++;
9643: my $result;
9644: if ($args->{'discussion'}) {
9645: my ($target,$parser);
9646: if (ref($args->{'discussion'})) {
9647: ($target,$parser) =($args->{'discussion'}{'target'},
9648: $args->{'discussion'}{'parser'});
9649: }
9650: $result .= &Apache::lonxml::xmlend($target,$parser);
9651: }
9652: if ($args->{'frameset'}) {
9653: $result .= '</frameset>';
9654: } else {
9655: $result .= &endbodytag($args);
9656: }
9657: unless ($args->{'notbody'}) {
9658: $result .= "\n</html>";
9659: }
9660:
9661: if ($args->{'js_ready'}) {
9662: $result = &js_ready($result);
9663: }
9664:
9665: if ($args->{'html_encode'}) {
9666: $result = &html_encode($result);
9667: }
9668:
9669: return $result;
9670: }
9671:
9672: sub menucoll_in_effect {
9673: my ($menucoll,$deeplinkmenu,%menu);
9674: if ($env{'request.course.id'}) {
9675: $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
9676: if ($env{'request.deeplink.login'}) {
9677: my ($deeplink_symb,$deeplink,$check_login_symb);
9678: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9679: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9680: if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
9681: if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
9682: my $navmap = Apache::lonnavmaps::navmap->new();
9683: if (ref($navmap)) {
9684: $deeplink = $navmap->get_mapparam(undef,
9685: &Apache::lonnet::declutter($env{'request.noversionuri'}),
9686: '0.deeplink');
9687: } else {
9688: $check_login_symb = 1;
9689: }
9690: } else {
9691: my $symb = &Apache::lonnet::symbread();
9692: if ($symb) {
9693: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
9694: } else {
9695: $check_login_symb = 1;
9696: }
9697: }
9698: } else {
9699: $check_login_symb = 1;
9700: }
9701: if ($check_login_symb) {
9702: $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
9703: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9704: my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
9705: my $navmap = Apache::lonnavmaps::navmap->new();
9706: if (ref($navmap)) {
9707: $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
9708: }
9709: } else {
9710: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
9711: }
9712: }
9713: if ($deeplink ne '') {
9714: my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
9715: if ($display =~ /^\d+$/) {
9716: $deeplinkmenu = 1;
9717: $menucoll = $display;
9718: }
9719: }
9720: }
9721: if ($menucoll) {
9722: %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
9723: }
9724: }
9725: return ($menucoll,$deeplinkmenu,\%menu);
9726: }
9727:
9728: sub deeplink_login_symb {
9729: my ($cnum,$cdom) = @_;
9730: my $login_symb;
9731: if ($env{'request.deeplink.login'}) {
9732: $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
9733: }
9734: return $login_symb;
9735: }
9736:
9737: sub symb_from_tinyurl {
9738: my ($url,$cnum,$cdom) = @_;
9739: if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
9740: my $key = $1;
9741: my ($tinyurl,$login);
9742: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
9743: if (defined($cached)) {
9744: $tinyurl = $result;
9745: } else {
9746: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
9747: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
9748: if ($currtiny{$key} ne '') {
9749: $tinyurl = $currtiny{$key};
9750: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
9751: }
9752: }
9753: if ($tinyurl ne '') {
9754: my ($cnumreq,$symb) = split(/\&/,$tinyurl);
9755: if (wantarray) {
9756: return ($cnumreq,$symb);
9757: } elsif ($cnumreq eq $cnum) {
9758: return $symb;
9759: }
9760: }
9761: }
9762: if (wantarray) {
9763: return ();
9764: } else {
9765: return;
9766: }
9767: }
9768:
9769: sub usable_exttools {
9770: my %tooltypes;
9771: if ($env{'request.course.id'}) {
9772: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
9773: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
9774: %tooltypes = (
9775: crs => 1,
9776: dom => 1,
9777: );
9778: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
9779: $tooltypes{'crs'} = 1;
9780: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
9781: $tooltypes{'dom'} = 1;
9782: }
9783: } else {
9784: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9785: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9786: my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
9787: if ($crstype eq '') {
9788: $crstype = 'course';
9789: }
9790: if ($crstype eq 'course') {
9791: if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
9792: $crstype = 'official';
9793: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
9794: $crstype = 'textbook';
9795: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
9796: $crstype = 'lti';
9797: } else {
9798: $crstype = 'unofficial';
9799: }
9800: }
9801: my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
9802: if ($domdefaults{$crstype.'domexttool'}) {
9803: $tooltypes{'dom'} = 1;
9804: }
9805: if ($domdefaults{$crstype.'exttool'}) {
9806: $tooltypes{'crs'} = 1;
9807: }
9808: }
9809: }
9810: return %tooltypes;
9811: }
9812:
9813: sub wishlist_window {
9814: return(<<'ENDWISHLIST');
9815: <script type="text/javascript">
9816: // <![CDATA[
9817: // <!-- BEGIN LON-CAPA Internal
9818: function set_wishlistlink(title, path) {
9819: if (!title) {
9820: title = document.title;
9821: title = title.replace(/^LON-CAPA /,'');
9822: }
9823: title = encodeURIComponent(title);
9824: title = title.replace("'","\\\'");
9825: if (!path) {
9826: path = location.pathname;
9827: }
9828: path = encodeURIComponent(path);
9829: path = path.replace("'","\\\'");
9830: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
9831: 'wishlistNewLink','width=560,height=350,scrollbars=0');
9832: }
9833: // END LON-CAPA Internal -->
9834: // ]]>
9835: </script>
9836: ENDWISHLIST
9837: }
9838:
9839: sub modal_window {
9840: return(<<'ENDMODAL');
9841: <script type="text/javascript">
9842: // <![CDATA[
9843: // <!-- BEGIN LON-CAPA Internal
9844: var modalWindow = {
9845: parent:"body",
9846: windowId:null,
9847: content:null,
9848: width:null,
9849: height:null,
9850: close:function()
9851: {
9852: $(".LCmodal-window").remove();
9853: $(".LCmodal-overlay").remove();
9854: },
9855: open:function()
9856: {
9857: var modal = "";
9858: modal += "<div class=\"LCmodal-overlay\"></div>";
9859: 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;\">";
9860: modal += this.content;
9861: modal += "</div>";
9862:
9863: $(this.parent).append(modal);
9864:
9865: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
9866: $(".LCclose-window").click(function(){modalWindow.close();});
9867: $(".LCmodal-overlay").click(function(){modalWindow.close();});
9868: }
9869: };
9870: var openMyModal = function(source,width,height,scrolling,transparency,style)
9871: {
9872: source = source.replace(/'/g,"'");
9873: modalWindow.windowId = "myModal";
9874: modalWindow.width = width;
9875: modalWindow.height = height;
9876: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
9877: modalWindow.open();
9878: };
9879: // END LON-CAPA Internal -->
9880: // ]]>
9881: </script>
9882: ENDMODAL
9883: }
9884:
9885: sub modal_link {
9886: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
9887: unless ($width) { $width=480; }
9888: unless ($height) { $height=400; }
9889: unless ($scrolling) { $scrolling='yes'; }
9890: unless ($transparency) { $transparency='true'; }
9891:
9892: my $target_attr;
9893: if (defined($target)) {
9894: $target_attr = 'target="'.$target.'"';
9895: }
9896: return <<"ENDLINK";
9897: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
9898: ENDLINK
9899: }
9900:
9901: sub modal_adhoc_script {
9902: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9903: my $mathjax;
9904: if ($possmathjax) {
9905: $mathjax = <<'ENDJAX';
9906: if (typeof MathJax == 'object') {
9907: MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
9908: }
9909: ENDJAX
9910: }
9911: return (<<ENDADHOC);
9912: <script type="text/javascript">
9913: // <![CDATA[
9914: var $funcname = function()
9915: {
9916: modalWindow.windowId = "myModal";
9917: modalWindow.width = $width;
9918: modalWindow.height = $height;
9919: modalWindow.content = '$content';
9920: modalWindow.open();
9921: $mathjax
9922: };
9923: // ]]>
9924: </script>
9925: ENDADHOC
9926: }
9927:
9928: sub modal_adhoc_inner {
9929: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9930: my $innerwidth=$width-20;
9931: $content=&js_ready(
9932: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
9933: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
9934: $content.
9935: &end_scrollbox().
9936: &end_page()
9937: );
9938: return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
9939: }
9940:
9941: sub modal_adhoc_window {
9942: my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
9943: return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
9944: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
9945: }
9946:
9947: sub modal_adhoc_launch {
9948: my ($funcname,$width,$height,$content)=@_;
9949: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
9950: <script type="text/javascript">
9951: // <![CDATA[
9952: $funcname();
9953: // ]]>
9954: </script>
9955: ENDLAUNCH
9956: }
9957:
9958: sub modal_adhoc_close {
9959: return (<<ENDCLOSE);
9960: <script type="text/javascript">
9961: // <![CDATA[
9962: modalWindow.close();
9963: // ]]>
9964: </script>
9965: ENDCLOSE
9966: }
9967:
9968: sub togglebox_script {
9969: return(<<ENDTOGGLE);
9970: <script type="text/javascript">
9971: // <![CDATA[
9972: function LCtoggleDisplay(id,hidetext,showtext) {
9973: link = document.getElementById(id + "link").childNodes[0];
9974: with (document.getElementById(id).style) {
9975: if (display == "none" ) {
9976: display = "inline";
9977: link.nodeValue = hidetext;
9978: } else {
9979: display = "none";
9980: link.nodeValue = showtext;
9981: }
9982: }
9983: }
9984: // ]]>
9985: </script>
9986: ENDTOGGLE
9987: }
9988:
9989: sub start_togglebox {
9990: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
9991: unless ($heading) { $heading=''; } else { $heading.=' '; }
9992: unless ($showtext) { $showtext=&mt('show'); }
9993: unless ($hidetext) { $hidetext=&mt('hide'); }
9994: unless ($headerbg) { $headerbg='#FFFFFF'; }
9995: return &start_data_table().
9996: &start_data_table_header_row().
9997: '<td bgcolor="'.$headerbg.'">'.$heading.
9998: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
9999: $showtext.'\')">'.$showtext.'</a>]</td>'.
10000: &end_data_table_header_row().
10001: '<tr id="'.$id.'" style="display:none""><td>';
10002: }
10003:
10004: sub end_togglebox {
10005: return '</td></tr>'.&end_data_table();
10006: }
10007:
10008: sub LCprogressbar_script {
10009: my ($id,$number_to_do)=@_;
10010: if ($number_to_do) {
10011: return(<<ENDPROGRESS);
10012: <script type="text/javascript">
10013: // <![CDATA[
10014: \$('#progressbar$id').progressbar({
10015: value: 0,
10016: change: function(event, ui) {
10017: var newVal = \$(this).progressbar('option', 'value');
10018: \$('.pblabel', this).text(LCprogressTxt);
10019: }
10020: });
10021: // ]]>
10022: </script>
10023: ENDPROGRESS
10024: } else {
10025: return(<<ENDPROGRESS);
10026: <script type="text/javascript">
10027: // <![CDATA[
10028: \$('#progressbar$id').progressbar({
10029: value: false,
10030: create: function(event, ui) {
10031: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10032: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10033: }
10034: });
10035: // ]]>
10036: </script>
10037: ENDPROGRESS
10038: }
10039: }
10040:
10041: sub LCprogressbarUpdate_script {
10042: return(<<ENDPROGRESSUPDATE);
10043: <style type="text/css">
10044: .ui-progressbar { position:relative; }
10045: .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%; }
10046: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10047: </style>
10048: <script type="text/javascript">
10049: // <![CDATA[
10050: var LCprogressTxt='---';
10051:
10052: function LCupdateProgress(percent,progresstext,id,maxnum) {
10053: LCprogressTxt=progresstext;
10054: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10055: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10056: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10057: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10058: } else {
10059: \$('#progressbar'+id).progressbar('value',percent);
10060: }
10061: }
10062: // ]]>
10063: </script>
10064: ENDPROGRESSUPDATE
10065: }
10066:
10067: my $LClastpercent;
10068: my $LCidcnt;
10069: my $LCcurrentid;
10070:
10071: sub LCprogressbar {
10072: my ($r,$number_to_do,$preamble)=@_;
10073: $LClastpercent=0;
10074: $LCidcnt++;
10075: $LCcurrentid=$$.'_'.$LCidcnt;
10076: my ($starting,$content);
10077: if ($number_to_do) {
10078: $starting=&mt('Starting');
10079: $content=(<<ENDPROGBAR);
10080: $preamble
10081: <div id="progressbar$LCcurrentid">
10082: <span class="pblabel">$starting</span>
10083: </div>
10084: ENDPROGBAR
10085: } else {
10086: $starting=&mt('Loading...');
10087: $LClastpercent='false';
10088: $content=(<<ENDPROGBAR);
10089: $preamble
10090: <div id="progressbar$LCcurrentid">
10091: <div class="progress-label">$starting</div>
10092: </div>
10093: ENDPROGBAR
10094: }
10095: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10096: }
10097:
10098: sub LCprogressbarUpdate {
10099: my ($r,$val,$text,$number_to_do)=@_;
10100: if ($number_to_do) {
10101: unless ($val) {
10102: if ($LClastpercent) {
10103: $val=$LClastpercent;
10104: } else {
10105: $val=0;
10106: }
10107: }
10108: if ($val<0) { $val=0; }
10109: if ($val>100) { $val=0; }
10110: $LClastpercent=$val;
10111: unless ($text) { $text=$val.'%'; }
10112: } else {
10113: $val = 'false';
10114: }
10115: $text=&js_ready($text);
10116: &r_print($r,<<ENDUPDATE);
10117: <script type="text/javascript">
10118: // <![CDATA[
10119: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10120: // ]]>
10121: </script>
10122: ENDUPDATE
10123: }
10124:
10125: sub LCprogressbarClose {
10126: my ($r)=@_;
10127: $LClastpercent=0;
10128: &r_print($r,<<ENDCLOSE);
10129: <script type="text/javascript">
10130: // <![CDATA[
10131: \$("#progressbar$LCcurrentid").hide('slow');
10132: // ]]>
10133: </script>
10134: ENDCLOSE
10135: }
10136:
10137: sub r_print {
10138: my ($r,$to_print)=@_;
10139: if ($r) {
10140: $r->print($to_print);
10141: $r->rflush();
10142: } else {
10143: print($to_print);
10144: }
10145: }
10146:
10147: sub html_encode {
10148: my ($result) = @_;
10149:
10150: $result = &HTML::Entities::encode($result,'<>&"');
10151:
10152: return $result;
10153: }
10154:
10155: sub js_ready {
10156: my ($result) = @_;
10157:
10158: $result =~ s/[\n\r]/ /xmsg;
10159: $result =~ s/\\/\\\\/xmsg;
10160: $result =~ s/'/\\'/xmsg;
10161: $result =~ s{</}{<\\/}xmsg;
10162:
10163: return $result;
10164: }
10165:
10166: sub validate_page {
10167: if ( exists($env{'internal.start_page'})
10168: && $env{'internal.start_page'} > 1) {
10169: &Apache::lonnet::logthis('start_page called multiple times '.
10170: $env{'internal.start_page'}.' '.
10171: $ENV{'request.filename'});
10172: }
10173: if ( exists($env{'internal.end_page'})
10174: && $env{'internal.end_page'} > 1) {
10175: &Apache::lonnet::logthis('end_page called multiple times '.
10176: $env{'internal.end_page'}.' '.
10177: $env{'request.filename'});
10178: }
10179: if ( exists($env{'internal.start_page'})
10180: && ! exists($env{'internal.end_page'})) {
10181: &Apache::lonnet::logthis('start_page called without end_page '.
10182: $env{'request.filename'});
10183: }
10184: if ( ! exists($env{'internal.start_page'})
10185: && exists($env{'internal.end_page'})) {
10186: &Apache::lonnet::logthis('end_page called without start_page'.
10187: $env{'request.filename'});
10188: }
10189: }
10190:
10191:
10192: sub start_scrollbox {
10193: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10194: unless ($outerwidth) { $outerwidth='520px'; }
10195: unless ($width) { $width='500px'; }
10196: unless ($height) { $height='200px'; }
10197: my ($table_id,$div_id,$tdcol);
10198: if ($id ne '') {
10199: $table_id = ' id="table_'.$id.'"';
10200: $div_id = ' id="div_'.$id.'"';
10201: }
10202: if ($bgcolor ne '') {
10203: $tdcol = "background-color: $bgcolor;";
10204: }
10205: my $nicescroll_js;
10206: if ($env{'browser.mobile'}) {
10207: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10208: }
10209: return <<"END";
10210: $nicescroll_js
10211:
10212: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10213: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10214: END
10215: }
10216:
10217: sub end_scrollbox {
10218: return '</div></td></tr></table>';
10219: }
10220:
10221: sub nicescroll_javascript {
10222: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10223: my %options;
10224: if (ref($cursor) eq 'HASH') {
10225: %options = %{$cursor};
10226: }
10227: unless ($options{'railalign'} =~ /^left|right$/) {
10228: $options{'railalign'} = 'left';
10229: }
10230: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10231: my $function = &get_users_function();
10232: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10233: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10234: $options{'cursorcolor'} = '#00F';
10235: }
10236: }
10237: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10238: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10239: $options{'cursoropacity'}='1.0';
10240: }
10241: } else {
10242: $options{'cursoropacity'}='1.0';
10243: }
10244: if ($options{'cursorfixedheight'} eq 'none') {
10245: delete($options{'cursorfixedheight'});
10246: } else {
10247: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10248: }
10249: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10250: delete($options{'railoffset'});
10251: }
10252: my @niceoptions;
10253: while (my($key,$value) = each(%options)) {
10254: if ($value =~ /^\{.+\}$/) {
10255: push(@niceoptions,$key.':'.$value);
10256: } else {
10257: push(@niceoptions,$key.':"'.$value.'"');
10258: }
10259: }
10260: my $nicescroll_js = '
10261: $(document).ready(
10262: function() {
10263: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10264: }
10265: );
10266: ';
10267: if ($framecheck) {
10268: $nicescroll_js .= '
10269: function expand_div(caller) {
10270: if (top === self) {
10271: document.getElementById("'.$id.'").style.width = "auto";
10272: document.getElementById("'.$id.'").style.height = "auto";
10273: } else {
10274: try {
10275: if (parent.frames) {
10276: if (parent.frames.length > 1) {
10277: var framesrc = parent.frames[1].location.href;
10278: var currsrc = framesrc.replace(/\#.*$/,"");
10279: if ((caller == "search") || (currsrc == "'.$location.'")) {
10280: document.getElementById("'.$id.'").style.width = "auto";
10281: document.getElementById("'.$id.'").style.height = "auto";
10282: }
10283: }
10284: }
10285: } catch (e) {
10286: return;
10287: }
10288: }
10289: return;
10290: }
10291: ';
10292: }
10293: if ($needjsready) {
10294: $nicescroll_js = '
10295: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10296: } else {
10297: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10298: }
10299: return $nicescroll_js;
10300: }
10301:
10302: sub simple_error_page {
10303: my ($r,$title,$msg,$args) = @_;
10304: my %displayargs;
10305: if (ref($args) eq 'HASH') {
10306: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10307: if ($args->{'only_body'}) {
10308: $displayargs{'only_body'} = 1;
10309: }
10310: if ($args->{'no_nav_bar'}) {
10311: $displayargs{'no_nav_bar'} = 1;
10312: }
10313: } else {
10314: $msg = &mt($msg);
10315: }
10316:
10317: my $page =
10318: &Apache::loncommon::start_page($title,'',\%displayargs).
10319: '<p class="LC_error">'.$msg.'</p>'.
10320: &Apache::loncommon::end_page();
10321: if (ref($r)) {
10322: $r->print($page);
10323: return;
10324: }
10325: return $page;
10326: }
10327:
10328: {
10329: my @row_count;
10330:
10331: sub start_data_table_count {
10332: unshift(@row_count, 0);
10333: return;
10334: }
10335:
10336: sub end_data_table_count {
10337: shift(@row_count);
10338: return;
10339: }
10340:
10341: sub start_data_table {
10342: my ($add_class,$id) = @_;
10343: my $css_class = (join(' ','LC_data_table',$add_class));
10344: my $table_id;
10345: if (defined($id)) {
10346: $table_id = ' id="'.$id.'"';
10347: }
10348: &start_data_table_count();
10349: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10350: }
10351:
10352: sub end_data_table {
10353: &end_data_table_count();
10354: return '</table>'."\n";;
10355: }
10356:
10357: sub start_data_table_row {
10358: my ($add_class, $id) = @_;
10359: $row_count[0]++;
10360: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10361: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10362: $id = (' id="'.$id.'"') unless ($id eq '');
10363: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10364: }
10365:
10366: sub continue_data_table_row {
10367: my ($add_class, $id) = @_;
10368: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10369: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10370: $id = (' id="'.$id.'"') unless ($id eq '');
10371: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10372: }
10373:
10374: sub end_data_table_row {
10375: return '</tr>'."\n";;
10376: }
10377:
10378: sub start_data_table_empty_row {
10379: # $row_count[0]++;
10380: return '<tr class="LC_empty_row" >'."\n";;
10381: }
10382:
10383: sub end_data_table_empty_row {
10384: return '</tr>'."\n";;
10385: }
10386:
10387: sub start_data_table_header_row {
10388: return '<tr class="LC_header_row">'."\n";;
10389: }
10390:
10391: sub end_data_table_header_row {
10392: return '</tr>'."\n";;
10393: }
10394:
10395: sub data_table_caption {
10396: my $caption = shift;
10397: return "<caption class=\"LC_caption\">$caption</caption>";
10398: }
10399: }
10400:
10401: =pod
10402:
10403: =item * &inhibit_menu_check($arg)
10404:
10405: Checks for a inhibitmenu state and generates output to preserve it
10406:
10407: Inputs: $arg - can be any of
10408: - undef - in which case the return value is a string
10409: to add into arguments list of a uri
10410: - 'input' - in which case the return value is a HTML
10411: <form> <input> field of type hidden to
10412: preserve the value
10413: - a url - in which case the return value is the url with
10414: the neccesary cgi args added to preserve the
10415: inhibitmenu state
10416: - a ref to a url - no return value, but the string is
10417: updated to include the neccessary cgi
10418: args to preserve the inhibitmenu state
10419:
10420: =cut
10421:
10422: sub inhibit_menu_check {
10423: my ($arg) = @_;
10424: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10425: if ($arg eq 'input') {
10426: if ($env{'form.inhibitmenu'}) {
10427: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10428: } else {
10429: return
10430: }
10431: }
10432: if ($env{'form.inhibitmenu'}) {
10433: if (ref($arg)) {
10434: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10435: } elsif ($arg eq '') {
10436: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10437: } else {
10438: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10439: }
10440: }
10441: if (!ref($arg)) {
10442: return $arg;
10443: }
10444: }
10445:
10446: ###############################################
10447:
10448: =pod
10449:
10450: =back
10451:
10452: =head1 User Information Routines
10453:
10454: =over 4
10455:
10456: =item * &get_users_function()
10457:
10458: Used by &bodytag to determine the current users primary role.
10459: Returns either 'student','coordinator','admin', or 'author'.
10460:
10461: =cut
10462:
10463: ###############################################
10464: sub get_users_function {
10465: my $function = 'norole';
10466: if ($env{'request.role'}=~/^(st)/) {
10467: $function='student';
10468: }
10469: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10470: $function='coordinator';
10471: }
10472: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10473: $function='admin';
10474: }
10475: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10476: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10477: $function='author';
10478: }
10479: return $function;
10480: }
10481:
10482: ###############################################
10483:
10484: =pod
10485:
10486: =item * &show_course()
10487:
10488: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10489: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10490:
10491: Inputs:
10492: None
10493:
10494: Outputs:
10495: Scalar: 1 if 'Course' to be used, 0 otherwise.
10496:
10497: =cut
10498:
10499: ###############################################
10500: sub show_course {
10501: my $course = !$env{'user.adv'};
10502: if (!$env{'user.adv'}) {
10503: foreach my $env (keys(%env)) {
10504: next if ($env !~ m/^user\.priv\./);
10505: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10506: $course = 0;
10507: last;
10508: }
10509: }
10510: }
10511: return $course;
10512: }
10513:
10514: ###############################################
10515:
10516: =pod
10517:
10518: =item * &check_user_status()
10519:
10520: Determines current status of supplied role for a
10521: specific user. Roles can be active, previous or future.
10522:
10523: Inputs:
10524: user's domain, user's username, course's domain,
10525: course's number, optional section ID.
10526:
10527: Outputs:
10528: role status: active, previous or future.
10529:
10530: =cut
10531:
10532: sub check_user_status {
10533: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10534: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10535: my @uroles = keys(%userinfo);
10536: my $srchstr;
10537: my $active_chk = 'none';
10538: my $now = time;
10539: if (@uroles > 0) {
10540: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10541: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10542: } else {
10543: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10544: }
10545: if (grep/^\Q$srchstr\E$/,@uroles) {
10546: my $role_end = 0;
10547: my $role_start = 0;
10548: $active_chk = 'active';
10549: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10550: $role_end = $1;
10551: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10552: $role_start = $1;
10553: }
10554: }
10555: if ($role_start > 0) {
10556: if ($now < $role_start) {
10557: $active_chk = 'future';
10558: }
10559: }
10560: if ($role_end > 0) {
10561: if ($now > $role_end) {
10562: $active_chk = 'previous';
10563: }
10564: }
10565: }
10566: }
10567: return $active_chk;
10568: }
10569:
10570: ###############################################
10571:
10572: =pod
10573:
10574: =item * &get_sections()
10575:
10576: Determines all the sections for a course including
10577: sections with students and sections containing other roles.
10578: Incoming parameters:
10579:
10580: 1. domain
10581: 2. course number
10582: 3. reference to array containing roles for which sections should
10583: be gathered (optional).
10584: 4. reference to array containing status types for which sections
10585: should be gathered (optional).
10586:
10587: If the third argument is undefined, sections are gathered for any role.
10588: If the fourth argument is undefined, sections are gathered for any status.
10589: Permissible values are 'active' or 'future' or 'previous'.
10590:
10591: Returns section hash (keys are section IDs, values are
10592: number of users in each section), subject to the
10593: optional roles filter, optional status filter
10594:
10595: =cut
10596:
10597: ###############################################
10598: sub get_sections {
10599: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10600: if (!defined($cdom) || !defined($cnum)) {
10601: my $cid = $env{'request.course.id'};
10602:
10603: return if (!defined($cid));
10604:
10605: $cdom = $env{'course.'.$cid.'.domain'};
10606: $cnum = $env{'course.'.$cid.'.num'};
10607: }
10608:
10609: my %sectioncount;
10610: my $now = time;
10611:
10612: my $check_students = 1;
10613: my $only_students = 0;
10614: if (ref($possible_roles) eq 'ARRAY') {
10615: if (grep(/^st$/,@{$possible_roles})) {
10616: if (@{$possible_roles} == 1) {
10617: $only_students = 1;
10618: }
10619: } else {
10620: $check_students = 0;
10621: }
10622: }
10623:
10624: if ($check_students) {
10625: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10626: my $sec_index = &Apache::loncoursedata::CL_SECTION();
10627: my $status_index = &Apache::loncoursedata::CL_STATUS();
10628: my $start_index = &Apache::loncoursedata::CL_START();
10629: my $end_index = &Apache::loncoursedata::CL_END();
10630: my $status;
10631: while (my ($student,$data) = each(%$classlist)) {
10632: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10633: $data->[$status_index],
10634: $data->[$start_index],
10635: $data->[$end_index]);
10636: if ($stu_status eq 'Active') {
10637: $status = 'active';
10638: } elsif ($end < $now) {
10639: $status = 'previous';
10640: } elsif ($start > $now) {
10641: $status = 'future';
10642: }
10643: if ($section ne '-1' && $section !~ /^\s*$/) {
10644: if ((!defined($possible_status)) || (($status ne '') &&
10645: (grep/^\Q$status\E$/,@{$possible_status}))) {
10646: $sectioncount{$section}++;
10647: }
10648: }
10649: }
10650: }
10651: if ($only_students) {
10652: return %sectioncount;
10653: }
10654: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10655: foreach my $user (sort(keys(%courseroles))) {
10656: if ($user !~ /^(\w{2})/) { next; }
10657: my ($role) = ($user =~ /^(\w{2})/);
10658: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10659: my ($section,$status);
10660: if ($role eq 'cr' &&
10661: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10662: $section=$1;
10663: }
10664: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10665: if (!defined($section) || $section eq '-1') { next; }
10666: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10667: if ($end == -1 && $start == -1) {
10668: next; #deleted role
10669: }
10670: if (!defined($possible_status)) {
10671: $sectioncount{$section}++;
10672: } else {
10673: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10674: $status = 'active';
10675: } elsif ($end < $now) {
10676: $status = 'future';
10677: } elsif ($start > $now) {
10678: $status = 'previous';
10679: }
10680: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10681: $sectioncount{$section}++;
10682: }
10683: }
10684: }
10685: return %sectioncount;
10686: }
10687:
10688: ###############################################
10689:
10690: =pod
10691:
10692: =item * &get_course_users()
10693:
10694: Retrieves usernames:domains for users in the specified course
10695: with specific role(s), and access status.
10696:
10697: Incoming parameters:
10698: 1. course domain
10699: 2. course number
10700: 3. access status: users must have - either active,
10701: previous, future, or all.
10702: 4. reference to array of permissible roles
10703: 5. reference to array of section restrictions (optional)
10704: 6. reference to results object (hash of hashes).
10705: 7. reference to optional userdata hash
10706: 8. reference to optional statushash
10707: 9. flag if privileged users (except those set to unhide in
10708: course settings) should be excluded
10709: Keys of top level results hash are roles.
10710: Keys of inner hashes are username:domain, with
10711: values set to access type.
10712: Optional userdata hash returns an array with arguments in the
10713: same order as loncoursedata::get_classlist() for student data.
10714:
10715: Optional statushash returns
10716:
10717: Entries for end, start, section and status are blank because
10718: of the possibility of multiple values for non-student roles.
10719:
10720: =cut
10721:
10722: ###############################################
10723:
10724: sub get_course_users {
10725: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10726: my %idx = ();
10727: my %seclists;
10728:
10729: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10730: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
10731: $idx{end} = &Apache::loncoursedata::CL_END();
10732: $idx{start} = &Apache::loncoursedata::CL_START();
10733: $idx{id} = &Apache::loncoursedata::CL_ID();
10734: $idx{section} = &Apache::loncoursedata::CL_SECTION();
10735: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10736: $idx{status} = &Apache::loncoursedata::CL_STATUS();
10737:
10738: if (grep(/^st$/,@{$roles})) {
10739: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10740: my $now = time;
10741: foreach my $student (keys(%{$classlist})) {
10742: my $match = 0;
10743: my $secmatch = 0;
10744: my $section = $$classlist{$student}[$idx{section}];
10745: my $status = $$classlist{$student}[$idx{status}];
10746: if ($section eq '') {
10747: $section = 'none';
10748: }
10749: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10750: if (grep(/^all$/,@{$sections})) {
10751: $secmatch = 1;
10752: } elsif ($$classlist{$student}[$idx{section}] eq '') {
10753: if (grep(/^none$/,@{$sections})) {
10754: $secmatch = 1;
10755: }
10756: } else {
10757: if (grep(/^\Q$section\E$/,@{$sections})) {
10758: $secmatch = 1;
10759: }
10760: }
10761: if (!$secmatch) {
10762: next;
10763: }
10764: }
10765: if (defined($$types{'active'})) {
10766: if ($$classlist{$student}[$idx{status}] eq 'Active') {
10767: push(@{$$users{st}{$student}},'active');
10768: $match = 1;
10769: }
10770: }
10771: if (defined($$types{'previous'})) {
10772: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10773: push(@{$$users{st}{$student}},'previous');
10774: $match = 1;
10775: }
10776: }
10777: if (defined($$types{'future'})) {
10778: if ($$classlist{$student}[$idx{status}] eq 'Future') {
10779: push(@{$$users{st}{$student}},'future');
10780: $match = 1;
10781: }
10782: }
10783: if ($match) {
10784: push(@{$seclists{$student}},$section);
10785: if (ref($userdata) eq 'HASH') {
10786: $$userdata{$student} = $$classlist{$student};
10787: }
10788: if (ref($statushash) eq 'HASH') {
10789: $statushash->{$student}{'st'}{$section} = $status;
10790: }
10791: }
10792: }
10793: }
10794: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10795: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10796: my $now = time;
10797: my %displaystatus = ( previous => 'Expired',
10798: active => 'Active',
10799: future => 'Future',
10800: );
10801: my (%nothide,@possdoms);
10802: if ($hidepriv) {
10803: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10804: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10805: if ($user !~ /:/) {
10806: $nothide{join(':',split(/[\@]/,$user))}=1;
10807: } else {
10808: $nothide{$user} = 1;
10809: }
10810: }
10811: my @possdoms = ($cdom);
10812: if ($coursehash{'checkforpriv'}) {
10813: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10814: }
10815: }
10816: foreach my $person (sort(keys(%coursepersonnel))) {
10817: my $match = 0;
10818: my $secmatch = 0;
10819: my $status;
10820: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10821: $user =~ s/:$//;
10822: my ($end,$start) = split(/:/,$coursepersonnel{$person});
10823: if ($end == -1 || $start == -1) {
10824: next;
10825: }
10826: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10827: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10828: my ($uname,$udom) = split(/:/,$user);
10829: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10830: if (grep(/^all$/,@{$sections})) {
10831: $secmatch = 1;
10832: } elsif ($usec eq '') {
10833: if (grep(/^none$/,@{$sections})) {
10834: $secmatch = 1;
10835: }
10836: } else {
10837: if (grep(/^\Q$usec\E$/,@{$sections})) {
10838: $secmatch = 1;
10839: }
10840: }
10841: if (!$secmatch) {
10842: next;
10843: }
10844: }
10845: if ($usec eq '') {
10846: $usec = 'none';
10847: }
10848: if ($uname ne '' && $udom ne '') {
10849: if ($hidepriv) {
10850: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10851: (!$nothide{$uname.':'.$udom})) {
10852: next;
10853: }
10854: }
10855: if ($end > 0 && $end < $now) {
10856: $status = 'previous';
10857: } elsif ($start > $now) {
10858: $status = 'future';
10859: } else {
10860: $status = 'active';
10861: }
10862: foreach my $type (keys(%{$types})) {
10863: if ($status eq $type) {
10864: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10865: push(@{$$users{$role}{$user}},$type);
10866: }
10867: $match = 1;
10868: }
10869: }
10870: if (($match) && (ref($userdata) eq 'HASH')) {
10871: if (!exists($$userdata{$uname.':'.$udom})) {
10872: &get_user_info($udom,$uname,\%idx,$userdata);
10873: }
10874: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10875: push(@{$seclists{$uname.':'.$udom}},$usec);
10876: }
10877: if (ref($statushash) eq 'HASH') {
10878: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10879: }
10880: }
10881: }
10882: }
10883: }
10884: if (grep(/^ow$/,@{$roles})) {
10885: if ((defined($cdom)) && (defined($cnum))) {
10886: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10887: if ( defined($csettings{'internal.courseowner'}) ) {
10888: my $owner = $csettings{'internal.courseowner'};
10889: next if ($owner eq '');
10890: my ($ownername,$ownerdom);
10891: if ($owner =~ /^([^:]+):([^:]+)$/) {
10892: $ownername = $1;
10893: $ownerdom = $2;
10894: } else {
10895: $ownername = $owner;
10896: $ownerdom = $cdom;
10897: $owner = $ownername.':'.$ownerdom;
10898: }
10899: @{$$users{'ow'}{$owner}} = 'any';
10900: if (defined($userdata) &&
10901: !exists($$userdata{$owner})) {
10902: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
10903: if (!grep(/^none$/,@{$seclists{$owner}})) {
10904: push(@{$seclists{$owner}},'none');
10905: }
10906: if (ref($statushash) eq 'HASH') {
10907: $statushash->{$owner}{'ow'}{'none'} = 'Any';
10908: }
10909: }
10910: }
10911: }
10912: }
10913: foreach my $user (keys(%seclists)) {
10914: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10915: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10916: }
10917: }
10918: return;
10919: }
10920:
10921: sub get_user_info {
10922: my ($udom,$uname,$idx,$userdata) = @_;
10923: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
10924: &plainname($uname,$udom,'lastname');
10925: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10926: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10927: my %idhash = &Apache::lonnet::idrget($udom,($uname));
10928: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
10929: return;
10930: }
10931:
10932: ###############################################
10933:
10934: =pod
10935:
10936: =item * &get_user_quota()
10937:
10938: Retrieves quota assigned for storage of user files.
10939: Default is to report quota for portfolio files.
10940:
10941: Incoming parameters:
10942: 1. user's username
10943: 2. user's domain
10944: 3. quota name - portfolio, author, or course
10945: (if no quota name provided, defaults to portfolio).
10946: 4. crstype - official, unofficial, textbook, placement or community,
10947: if quota name is course
10948:
10949: Returns:
10950: 1. Disk quota (in MB) assigned to student.
10951: 2. (Optional) Type of setting: custom or default
10952: (individually assigned or default for user's
10953: institutional status).
10954: 3. (Optional) - User's institutional status (e.g., faculty, staff
10955: or student - types as defined in localenroll::inst_usertypes
10956: for user's domain, which determines default quota for user.
10957: 4. (Optional) - Default quota which would apply to the user.
10958:
10959: If a value has been stored in the user's environment,
10960: it will return that, otherwise it returns the maximal default
10961: defined for the user's institutional status(es) in the domain.
10962:
10963: =cut
10964:
10965: ###############################################
10966:
10967:
10968: sub get_user_quota {
10969: my ($uname,$udom,$quotaname,$crstype) = @_;
10970: my ($quota,$quotatype,$settingstatus,$defquota);
10971: if (!defined($udom)) {
10972: $udom = $env{'user.domain'};
10973: }
10974: if (!defined($uname)) {
10975: $uname = $env{'user.name'};
10976: }
10977: if (($udom eq '' || $uname eq '') ||
10978: ($udom eq 'public') && ($uname eq 'public')) {
10979: $quota = 0;
10980: $quotatype = 'default';
10981: $defquota = 0;
10982: } else {
10983: my $inststatus;
10984: if ($quotaname eq 'course') {
10985: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10986: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10987: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10988: } else {
10989: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10990: $quota = $cenv{'internal.uploadquota'};
10991: }
10992: } else {
10993: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10994: if ($quotaname eq 'author') {
10995: $quota = $env{'environment.authorquota'};
10996: } else {
10997: $quota = $env{'environment.portfolioquota'};
10998: }
10999: $inststatus = $env{'environment.inststatus'};
11000: } else {
11001: my %userenv =
11002: &Apache::lonnet::get('environment',['portfolioquota',
11003: 'authorquota','inststatus'],$udom,$uname);
11004: my ($tmp) = keys(%userenv);
11005: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11006: if ($quotaname eq 'author') {
11007: $quota = $userenv{'authorquota'};
11008: } else {
11009: $quota = $userenv{'portfolioquota'};
11010: }
11011: $inststatus = $userenv{'inststatus'};
11012: } else {
11013: undef(%userenv);
11014: }
11015: }
11016: }
11017: if ($quota eq '' || wantarray) {
11018: if ($quotaname eq 'course') {
11019: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11020: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
11021: ($crstype eq 'community') || ($crstype eq 'textbook') ||
11022: ($crstype eq 'placement')) {
11023: $defquota = $domdefs{$crstype.'quota'};
11024: }
11025: if ($defquota eq '') {
11026: $defquota = 500;
11027: }
11028: } else {
11029: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11030: }
11031: if ($quota eq '') {
11032: $quota = $defquota;
11033: $quotatype = 'default';
11034: } else {
11035: $quotatype = 'custom';
11036: }
11037: }
11038: }
11039: if (wantarray) {
11040: return ($quota,$quotatype,$settingstatus,$defquota);
11041: } else {
11042: return $quota;
11043: }
11044: }
11045:
11046: ###############################################
11047:
11048: =pod
11049:
11050: =item * &default_quota()
11051:
11052: Retrieves default quota assigned for storage of user portfolio files,
11053: given an (optional) user's institutional status.
11054:
11055: Incoming parameters:
11056:
11057: 1. domain
11058: 2. (Optional) institutional status(es). This is a : separated list of
11059: status types (e.g., faculty, staff, student etc.)
11060: which apply to the user for whom the default is being retrieved.
11061: If the institutional status string in undefined, the domain
11062: default quota will be returned.
11063: 3. quota name - portfolio, author, or course
11064: (if no quota name provided, defaults to portfolio).
11065:
11066: Returns:
11067:
11068: 1. Default disk quota (in MB) for user portfolios in the domain.
11069: 2. (Optional) institutional type which determined the value of the
11070: default quota.
11071:
11072: If a value has been stored in the domain's configuration db,
11073: it will return that, otherwise it returns 20 (for backwards
11074: compatibility with domains which have not set up a configuration
11075: db file; the original statically defined portfolio quota was 20 MB).
11076:
11077: If the user's status includes multiple types (e.g., staff and student),
11078: the largest default quota which applies to the user determines the
11079: default quota returned.
11080:
11081: =cut
11082:
11083: ###############################################
11084:
11085:
11086: sub default_quota {
11087: my ($udom,$inststatus,$quotaname) = @_;
11088: my ($defquota,$settingstatus);
11089: my %quotahash = &Apache::lonnet::get_dom('configuration',
11090: ['quotas'],$udom);
11091: my $key = 'defaultquota';
11092: if ($quotaname eq 'author') {
11093: $key = 'authorquota';
11094: }
11095: if (ref($quotahash{'quotas'}) eq 'HASH') {
11096: if ($inststatus ne '') {
11097: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11098: foreach my $item (@statuses) {
11099: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11100: if ($quotahash{'quotas'}{$key}{$item} ne '') {
11101: if ($defquota eq '') {
11102: $defquota = $quotahash{'quotas'}{$key}{$item};
11103: $settingstatus = $item;
11104: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11105: $defquota = $quotahash{'quotas'}{$key}{$item};
11106: $settingstatus = $item;
11107: }
11108: }
11109: } elsif ($key eq 'defaultquota') {
11110: if ($quotahash{'quotas'}{$item} ne '') {
11111: if ($defquota eq '') {
11112: $defquota = $quotahash{'quotas'}{$item};
11113: $settingstatus = $item;
11114: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11115: $defquota = $quotahash{'quotas'}{$item};
11116: $settingstatus = $item;
11117: }
11118: }
11119: }
11120: }
11121: }
11122: if ($defquota eq '') {
11123: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11124: $defquota = $quotahash{'quotas'}{$key}{'default'};
11125: } elsif ($key eq 'defaultquota') {
11126: $defquota = $quotahash{'quotas'}{'default'};
11127: }
11128: $settingstatus = 'default';
11129: if ($defquota eq '') {
11130: if ($quotaname eq 'author') {
11131: $defquota = 500;
11132: }
11133: }
11134: }
11135: } else {
11136: $settingstatus = 'default';
11137: if ($quotaname eq 'author') {
11138: $defquota = 500;
11139: } else {
11140: $defquota = 20;
11141: }
11142: }
11143: if (wantarray) {
11144: return ($defquota,$settingstatus);
11145: } else {
11146: return $defquota;
11147: }
11148: }
11149:
11150: ###############################################
11151:
11152: =pod
11153:
11154: =item * &excess_filesize_warning()
11155:
11156: Returns warning message if upload of file to authoring space, or copying
11157: of existing file within authoring space will cause quota for the authoring
11158: space to be exceeded.
11159:
11160: Same, if upload of a file directly to a course/community via Course Editor
11161: will cause quota for uploaded content for the course to be exceeded.
11162:
11163: Inputs: 7
11164: 1. username or coursenum
11165: 2. domain
11166: 3. context ('author' or 'course')
11167: 4. filename of file for which action is being requested
11168: 5. filesize (kB) of file
11169: 6. action being taken: copy or upload.
11170: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11171:
11172: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11173: otherwise return null.
11174:
11175: =back
11176:
11177: =cut
11178:
11179: sub excess_filesize_warning {
11180: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11181: my $current_disk_usage = 0;
11182: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11183: if ($context eq 'author') {
11184: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11185: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11186: } else {
11187: foreach my $subdir ('docs','supplemental') {
11188: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11189: }
11190: }
11191: $disk_quota = int($disk_quota * 1000);
11192: if (($current_disk_usage + $filesize) > $disk_quota) {
11193: return '<p class="LC_warning">'.
11194: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11195: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11196: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11197: $disk_quota,$current_disk_usage).
11198: '</p>';
11199: }
11200: return;
11201: }
11202:
11203: ###############################################
11204:
11205:
11206:
11207:
11208: sub get_secgrprole_info {
11209: my ($cdom,$cnum,$needroles,$type) = @_;
11210: my %sections_count = &get_sections($cdom,$cnum);
11211: my @sections = (sort {$a <=> $b} keys(%sections_count));
11212: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11213: my @groups = sort(keys(%curr_groups));
11214: my $allroles = [];
11215: my $rolehash;
11216: my $accesshash = {
11217: active => 'Currently has access',
11218: future => 'Will have future access',
11219: previous => 'Previously had access',
11220: };
11221: if ($needroles) {
11222: $rolehash = {'all' => 'all'};
11223: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11224: if (&Apache::lonnet::error(%user_roles)) {
11225: undef(%user_roles);
11226: }
11227: foreach my $item (keys(%user_roles)) {
11228: my ($role)=split(/\:/,$item,2);
11229: if ($role eq 'cr') { next; }
11230: if ($role =~ /^cr/) {
11231: $$rolehash{$role} = (split('/',$role))[3];
11232: } else {
11233: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11234: }
11235: }
11236: foreach my $key (sort(keys(%{$rolehash}))) {
11237: push(@{$allroles},$key);
11238: }
11239: push (@{$allroles},'st');
11240: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11241: }
11242: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11243: }
11244:
11245: sub user_picker {
11246: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11247: my $currdom = $dom;
11248: my @alldoms = &Apache::lonnet::all_domains();
11249: if (@alldoms == 1) {
11250: my %domsrch = &Apache::lonnet::get_dom('configuration',
11251: ['directorysrch'],$alldoms[0]);
11252: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11253: my $showdom = $domdesc;
11254: if ($showdom eq '') {
11255: $showdom = $dom;
11256: }
11257: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11258: if ((!$domsrch{'directorysrch'}{'available'}) &&
11259: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11260: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11261: }
11262: }
11263: }
11264: my %curr_selected = (
11265: srchin => 'dom',
11266: srchby => 'lastname',
11267: );
11268: my $srchterm;
11269: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11270: if ($srch->{'srchby'} ne '') {
11271: $curr_selected{'srchby'} = $srch->{'srchby'};
11272: }
11273: if ($srch->{'srchin'} ne '') {
11274: $curr_selected{'srchin'} = $srch->{'srchin'};
11275: }
11276: if ($srch->{'srchtype'} ne '') {
11277: $curr_selected{'srchtype'} = $srch->{'srchtype'};
11278: }
11279: if ($srch->{'srchdomain'} ne '') {
11280: $currdom = $srch->{'srchdomain'};
11281: }
11282: $srchterm = $srch->{'srchterm'};
11283: }
11284: my %html_lt=&Apache::lonlocal::texthash(
11285: 'usr' => 'Search criteria',
11286: 'doma' => 'Domain/institution to search',
11287: 'uname' => 'username',
11288: 'lastname' => 'last name',
11289: 'lastfirst' => 'last name, first name',
11290: 'crs' => 'in this course',
11291: 'dom' => 'in selected LON-CAPA domain',
11292: 'alc' => 'all LON-CAPA',
11293: 'instd' => 'in institutional directory for selected domain',
11294: 'exact' => 'is',
11295: 'contains' => 'contains',
11296: 'begins' => 'begins with',
11297: );
11298: my %js_lt=&Apache::lonlocal::texthash(
11299: 'youm' => "You must include some text to search for.",
11300: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11301: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11302: 'yomc' => "You must choose a domain when using an institutional directory search.",
11303: 'ymcd' => "You must choose a domain when using a domain search.",
11304: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
11305: 'whse' => "When searching by last,first you must include at least one character in the first name.",
11306: 'thfo' => "The following need to be corrected before the search can be run:",
11307: );
11308: &html_escape(\%html_lt);
11309: &js_escape(\%js_lt);
11310: my $domform;
11311: my $allow_blank = 1;
11312: if ($fixeddom) {
11313: $allow_blank = 0;
11314: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11315: } else {
11316: my $defdom = $env{'request.role.domain'};
11317: my ($trusted,$untrusted);
11318: if (($context eq 'requestcrs') || ($context eq 'course')) {
11319: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11320: } elsif ($context eq 'author') {
11321: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11322: } elsif ($context eq 'domain') {
11323: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11324: }
11325: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11326: }
11327: my $srchinsel = ' <select name="srchin">';
11328:
11329: my @srchins = ('crs','dom','alc','instd');
11330:
11331: foreach my $option (@srchins) {
11332: # FIXME 'alc' option unavailable until
11333: # loncreateuser::print_user_query_page()
11334: # has been completed.
11335: next if ($option eq 'alc');
11336: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
11337: next if ($option eq 'crs' && !$env{'request.course.id'});
11338: next if (($option eq 'instd') && ($noinstd));
11339: if ($curr_selected{'srchin'} eq $option) {
11340: $srchinsel .= '
11341: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11342: } else {
11343: $srchinsel .= '
11344: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11345: }
11346: }
11347: $srchinsel .= "\n </select>\n";
11348:
11349: my $srchbysel = ' <select name="srchby">';
11350: foreach my $option ('lastname','lastfirst','uname') {
11351: if ($curr_selected{'srchby'} eq $option) {
11352: $srchbysel .= '
11353: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11354: } else {
11355: $srchbysel .= '
11356: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11357: }
11358: }
11359: $srchbysel .= "\n </select>\n";
11360:
11361: my $srchtypesel = ' <select name="srchtype">';
11362: foreach my $option ('begins','contains','exact') {
11363: if ($curr_selected{'srchtype'} eq $option) {
11364: $srchtypesel .= '
11365: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11366: } else {
11367: $srchtypesel .= '
11368: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11369: }
11370: }
11371: $srchtypesel .= "\n </select>\n";
11372:
11373: my ($newuserscript,$new_user_create);
11374: my $context_dom = $env{'request.role.domain'};
11375: if ($context eq 'requestcrs') {
11376: if ($env{'form.coursedom'} ne '') {
11377: $context_dom = $env{'form.coursedom'};
11378: }
11379: }
11380: if ($forcenewuser) {
11381: if (ref($srch) eq 'HASH') {
11382: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11383: if ($cancreate) {
11384: $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>';
11385: } else {
11386: my $helplink = 'javascript:helpMenu('."'display'".')';
11387: my %usertypetext = (
11388: official => 'institutional',
11389: unofficial => 'non-institutional',
11390: );
11391: $new_user_create = '<p class="LC_warning">'
11392: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11393: .' '
11394: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11395: ,'<a href="'.$helplink.'">','</a>')
11396: .'</p><br />';
11397: }
11398: }
11399: }
11400:
11401: $newuserscript = <<"ENDSCRIPT";
11402:
11403: function setSearch(createnew,callingForm) {
11404: if (createnew == 1) {
11405: for (var i=0; i<callingForm.srchby.length; i++) {
11406: if (callingForm.srchby.options[i].value == 'uname') {
11407: callingForm.srchby.selectedIndex = i;
11408: }
11409: }
11410: for (var i=0; i<callingForm.srchin.length; i++) {
11411: if ( callingForm.srchin.options[i].value == 'dom') {
11412: callingForm.srchin.selectedIndex = i;
11413: }
11414: }
11415: for (var i=0; i<callingForm.srchtype.length; i++) {
11416: if (callingForm.srchtype.options[i].value == 'exact') {
11417: callingForm.srchtype.selectedIndex = i;
11418: }
11419: }
11420: for (var i=0; i<callingForm.srchdomain.length; i++) {
11421: if (callingForm.srchdomain.options[i].value == '$context_dom') {
11422: callingForm.srchdomain.selectedIndex = i;
11423: }
11424: }
11425: }
11426: }
11427: ENDSCRIPT
11428:
11429: }
11430:
11431: my $output = <<"END_BLOCK";
11432: <script type="text/javascript">
11433: // <![CDATA[
11434: function validateEntry(callingForm) {
11435:
11436: var checkok = 1;
11437: var srchin;
11438: for (var i=0; i<callingForm.srchin.length; i++) {
11439: if ( callingForm.srchin[i].checked ) {
11440: srchin = callingForm.srchin[i].value;
11441: }
11442: }
11443:
11444: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11445: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11446: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11447: var srchterm = callingForm.srchterm.value;
11448: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11449: var msg = "";
11450:
11451: if (srchterm == "") {
11452: checkok = 0;
11453: msg += "$js_lt{'youm'}\\n";
11454: }
11455:
11456: if (srchtype== 'begins') {
11457: if (srchterm.length < 2) {
11458: checkok = 0;
11459: msg += "$js_lt{'thte'}\\n";
11460: }
11461: }
11462:
11463: if (srchtype== 'contains') {
11464: if (srchterm.length < 3) {
11465: checkok = 0;
11466: msg += "$js_lt{'thet'}\\n";
11467: }
11468: }
11469: if (srchin == 'instd') {
11470: if (srchdomain == '') {
11471: checkok = 0;
11472: msg += "$js_lt{'yomc'}\\n";
11473: }
11474: }
11475: if (srchin == 'dom') {
11476: if (srchdomain == '') {
11477: checkok = 0;
11478: msg += "$js_lt{'ymcd'}\\n";
11479: }
11480: }
11481: if (srchby == 'lastfirst') {
11482: if (srchterm.indexOf(",") == -1) {
11483: checkok = 0;
11484: msg += "$js_lt{'whus'}\\n";
11485: }
11486: if (srchterm.indexOf(",") == srchterm.length -1) {
11487: checkok = 0;
11488: msg += "$js_lt{'whse'}\\n";
11489: }
11490: }
11491: if (checkok == 0) {
11492: alert("$js_lt{'thfo'}\\n"+msg);
11493: return;
11494: }
11495: if (checkok == 1) {
11496: callingForm.submit();
11497: }
11498: }
11499:
11500: $newuserscript
11501:
11502: // ]]>
11503: </script>
11504:
11505: $new_user_create
11506:
11507: END_BLOCK
11508:
11509: $output .= &Apache::lonhtmlcommon::start_pick_box().
11510: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11511: $domform.
11512: &Apache::lonhtmlcommon::row_closure().
11513: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11514: $srchbysel.
11515: $srchtypesel.
11516: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11517: $srchinsel.
11518: &Apache::lonhtmlcommon::row_closure(1).
11519: &Apache::lonhtmlcommon::end_pick_box().
11520: '<br />';
11521: return ($output,1);
11522: }
11523:
11524: sub user_rule_check {
11525: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11526: my ($response,%inst_response);
11527: if (ref($usershash) eq 'HASH') {
11528: if (keys(%{$usershash}) > 1) {
11529: my (%by_username,%by_id,%userdoms);
11530: my $checkid;
11531: if (ref($checks) eq 'HASH') {
11532: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11533: $checkid = 1;
11534: }
11535: }
11536: foreach my $user (keys(%{$usershash})) {
11537: my ($uname,$udom) = split(/:/,$user);
11538: if ($checkid) {
11539: if (ref($usershash->{$user}) eq 'HASH') {
11540: if ($usershash->{$user}->{'id'} ne '') {
11541: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
11542: $userdoms{$udom} = 1;
11543: if (ref($inst_results) eq 'HASH') {
11544: $inst_results->{$uname.':'.$udom} = {};
11545: }
11546: }
11547: }
11548: } else {
11549: $by_username{$udom}{$uname} = 1;
11550: $userdoms{$udom} = 1;
11551: if (ref($inst_results) eq 'HASH') {
11552: $inst_results->{$uname.':'.$udom} = {};
11553: }
11554: }
11555: }
11556: foreach my $udom (keys(%userdoms)) {
11557: if (!$got_rules->{$udom}) {
11558: my %domconfig = &Apache::lonnet::get_dom('configuration',
11559: ['usercreation'],$udom);
11560: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11561: foreach my $item ('username','id') {
11562: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11563: $$curr_rules{$udom}{$item} =
11564: $domconfig{'usercreation'}{$item.'_rule'};
11565: }
11566: }
11567: }
11568: $got_rules->{$udom} = 1;
11569: }
11570: }
11571: if ($checkid) {
11572: foreach my $udom (keys(%by_id)) {
11573: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11574: if ($outcome eq 'ok') {
11575: foreach my $id (keys(%{$by_id{$udom}})) {
11576: my $uname = $by_id{$udom}{$id};
11577: $inst_response{$uname.':'.$udom} = $outcome;
11578: }
11579: if (ref($results) eq 'HASH') {
11580: foreach my $uname (keys(%{$results})) {
11581: if (exists($inst_response{$uname.':'.$udom})) {
11582: $inst_response{$uname.':'.$udom} = $outcome;
11583: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11584: }
11585: }
11586: }
11587: }
11588: }
11589: } else {
11590: foreach my $udom (keys(%by_username)) {
11591: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11592: if ($outcome eq 'ok') {
11593: foreach my $uname (keys(%{$by_username{$udom}})) {
11594: $inst_response{$uname.':'.$udom} = $outcome;
11595: }
11596: if (ref($results) eq 'HASH') {
11597: foreach my $uname (keys(%{$results})) {
11598: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11599: }
11600: }
11601: }
11602: }
11603: }
11604: } elsif (keys(%{$usershash}) == 1) {
11605: my $user = (keys(%{$usershash}))[0];
11606: my ($uname,$udom) = split(/:/,$user);
11607: if (($udom ne '') && ($uname ne '')) {
11608: if (ref($usershash->{$user}) eq 'HASH') {
11609: if (ref($checks) eq 'HASH') {
11610: if (defined($checks->{'username'})) {
11611: ($inst_response{$user},%{$inst_results->{$user}}) =
11612: &Apache::lonnet::get_instuser($udom,$uname);
11613: } elsif (defined($checks->{'id'})) {
11614: if ($usershash->{$user}->{'id'} ne '') {
11615: ($inst_response{$user},%{$inst_results->{$user}}) =
11616: &Apache::lonnet::get_instuser($udom,undef,
11617: $usershash->{$user}->{'id'});
11618: } else {
11619: ($inst_response{$user},%{$inst_results->{$user}}) =
11620: &Apache::lonnet::get_instuser($udom,$uname);
11621: }
11622: }
11623: } else {
11624: ($inst_response{$user},%{$inst_results->{$user}}) =
11625: &Apache::lonnet::get_instuser($udom,$uname);
11626: return;
11627: }
11628: if (!$got_rules->{$udom}) {
11629: my %domconfig = &Apache::lonnet::get_dom('configuration',
11630: ['usercreation'],$udom);
11631: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11632: foreach my $item ('username','id') {
11633: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11634: $$curr_rules{$udom}{$item} =
11635: $domconfig{'usercreation'}{$item.'_rule'};
11636: }
11637: }
11638: }
11639: $got_rules->{$udom} = 1;
11640: }
11641: }
11642: } else {
11643: return;
11644: }
11645: } else {
11646: return;
11647: }
11648: foreach my $user (keys(%{$usershash})) {
11649: my ($uname,$udom) = split(/:/,$user);
11650: next if (($udom eq '') || ($uname eq ''));
11651: my $id;
11652: if (ref($inst_results) eq 'HASH') {
11653: if (ref($inst_results->{$user}) eq 'HASH') {
11654: $id = $inst_results->{$user}->{'id'};
11655: }
11656: }
11657: if ($id eq '') {
11658: if (ref($usershash->{$user})) {
11659: $id = $usershash->{$user}->{'id'};
11660: }
11661: }
11662: foreach my $item (keys(%{$checks})) {
11663: if (ref($$curr_rules{$udom}) eq 'HASH') {
11664: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11665: if (@{$$curr_rules{$udom}{$item}} > 0) {
11666: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11667: $$curr_rules{$udom}{$item});
11668: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11669: if ($rule_check{$rule}) {
11670: $$rulematch{$user}{$item} = $rule;
11671: if ($inst_response{$user} eq 'ok') {
11672: if (ref($inst_results) eq 'HASH') {
11673: if (ref($inst_results->{$user}) eq 'HASH') {
11674: if (keys(%{$inst_results->{$user}}) == 0) {
11675: $$alerts{$item}{$udom}{$uname} = 1;
11676: } elsif ($item eq 'id') {
11677: if ($inst_results->{$user}->{'id'} eq '') {
11678: $$alerts{$item}{$udom}{$uname} = 1;
11679: }
11680: }
11681: }
11682: }
11683: }
11684: last;
11685: }
11686: }
11687: }
11688: }
11689: }
11690: }
11691: }
11692: }
11693: return;
11694: }
11695:
11696: sub user_rule_formats {
11697: my ($domain,$domdesc,$curr_rules,$check) = @_;
11698: my %text = (
11699: 'username' => 'Usernames',
11700: 'id' => 'IDs',
11701: );
11702: my $output;
11703: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11704: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11705: if (@{$ruleorder} > 0) {
11706: $output = '<br />'.
11707: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11708: '<span class="LC_cusr_emph">','</span>',$domdesc).
11709: ' <ul>';
11710: foreach my $rule (@{$ruleorder}) {
11711: if (ref($curr_rules) eq 'ARRAY') {
11712: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11713: if (ref($rules->{$rule}) eq 'HASH') {
11714: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11715: $rules->{$rule}{'desc'}.'</li>';
11716: }
11717: }
11718: }
11719: }
11720: $output .= '</ul>';
11721: }
11722: }
11723: return $output;
11724: }
11725:
11726: sub instrule_disallow_msg {
11727: my ($checkitem,$domdesc,$count,$mode) = @_;
11728: my $response;
11729: my %text = (
11730: item => 'username',
11731: items => 'usernames',
11732: match => 'matches',
11733: do => 'does',
11734: action => 'a username',
11735: one => 'one',
11736: );
11737: if ($count > 1) {
11738: $text{'item'} = 'usernames';
11739: $text{'match'} ='match';
11740: $text{'do'} = 'do';
11741: $text{'action'} = 'usernames',
11742: $text{'one'} = 'ones';
11743: }
11744: if ($checkitem eq 'id') {
11745: $text{'items'} = 'IDs';
11746: $text{'item'} = 'ID';
11747: $text{'action'} = 'an ID';
11748: if ($count > 1) {
11749: $text{'item'} = 'IDs';
11750: $text{'action'} = 'IDs';
11751: }
11752: }
11753: $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 />';
11754: if ($mode eq 'upload') {
11755: if ($checkitem eq 'username') {
11756: $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'}.");
11757: } elsif ($checkitem eq 'id') {
11758: $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.");
11759: }
11760: } elsif ($mode eq 'selfcreate') {
11761: if ($checkitem eq 'id') {
11762: $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.");
11763: }
11764: } else {
11765: if ($checkitem eq 'username') {
11766: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11767: } elsif ($checkitem eq 'id') {
11768: $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.");
11769: }
11770: }
11771: return $response;
11772: }
11773:
11774: sub personal_data_fieldtitles {
11775: my %fieldtitles = &Apache::lonlocal::texthash (
11776: id => 'Student/Employee ID',
11777: permanentemail => 'E-mail address',
11778: lastname => 'Last Name',
11779: firstname => 'First Name',
11780: middlename => 'Middle Name',
11781: generation => 'Generation',
11782: gen => 'Generation',
11783: inststatus => 'Affiliation',
11784: );
11785: return %fieldtitles;
11786: }
11787:
11788: sub sorted_inst_types {
11789: my ($dom) = @_;
11790: my ($usertypes,$order);
11791: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11792: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11793: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11794: $order = $domdefaults{'inststatus'}{'inststatusorder'};
11795: } else {
11796: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11797: }
11798: my $othertitle = &mt('All users');
11799: if ($env{'request.course.id'}) {
11800: $othertitle = &mt('Any users');
11801: }
11802: my @types;
11803: if (ref($order) eq 'ARRAY') {
11804: @types = @{$order};
11805: }
11806: if (@types == 0) {
11807: if (ref($usertypes) eq 'HASH') {
11808: @types = sort(keys(%{$usertypes}));
11809: }
11810: }
11811: if (keys(%{$usertypes}) > 0) {
11812: $othertitle = &mt('Other users');
11813: }
11814: return ($othertitle,$usertypes,\@types);
11815: }
11816:
11817: sub get_institutional_codes {
11818: my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11819: # Get complete list of course sections to update
11820: my @currsections = ();
11821: my @currxlists = ();
11822: my (%unclutteredsec,%unclutteredlcsec);
11823: my $coursecode = $$settings{'internal.coursecode'};
11824: my $crskey = $crs.':'.$coursecode;
11825: @{$unclutteredsec{$crskey}} = ();
11826: @{$unclutteredlcsec{$crskey}} = ();
11827:
11828: if ($$settings{'internal.sectionnums'} ne '') {
11829: @currsections = split(/,/,$$settings{'internal.sectionnums'});
11830: }
11831:
11832: if ($$settings{'internal.crosslistings'} ne '') {
11833: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11834: }
11835:
11836: if (@currxlists > 0) {
11837: foreach my $xl (@currxlists) {
11838: if ($xl =~ /^([^:]+):(\w*)$/) {
11839: unless (grep/^$1$/,@{$allcourses}) {
11840: push(@{$allcourses},$1);
11841: $$LC_code{$1} = $2;
11842: }
11843: }
11844: }
11845: }
11846:
11847: if (@currsections > 0) {
11848: foreach my $sec (@currsections) {
11849: if ($sec =~ m/^(\w+):(\w*)$/ ) {
11850: my $instsec = $1;
11851: my $lc_sec = $2;
11852: unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11853: push(@{$unclutteredsec{$crskey}},$instsec);
11854: push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11855: }
11856: }
11857: }
11858: }
11859:
11860: if (@{$unclutteredsec{$crskey}} > 0) {
11861: my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11862: if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11863: for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11864: my $sec = $coursecode.$formattedsec{$crskey}[$i];
11865: unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11866: push(@{$allcourses},$sec);
11867: $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11868: }
11869: }
11870: }
11871: }
11872: return;
11873: }
11874:
11875: sub get_standard_codeitems {
11876: return ('Year','Semester','Department','Number','Section');
11877: }
11878:
11879: =pod
11880:
11881: =head1 Slot Helpers
11882:
11883: =over 4
11884:
11885: =item * sorted_slots()
11886:
11887: Sorts an array of slot names in order of an optional sort key,
11888: default sort is by slot start time (earliest first).
11889:
11890: Inputs:
11891:
11892: =over 4
11893:
11894: slotsarr - Reference to array of unsorted slot names.
11895:
11896: slots - Reference to hash of hash, where outer hash keys are slot names.
11897:
11898: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
11899:
11900: =back
11901:
11902: Returns:
11903:
11904: =over 4
11905:
11906: sorted - An array of slot names sorted by a specified sort key
11907: (default sort key is start time of the slot).
11908:
11909: =back
11910:
11911: =cut
11912:
11913:
11914: sub sorted_slots {
11915: my ($slotsarr,$slots,$sortkey) = @_;
11916: if ($sortkey eq '') {
11917: $sortkey = 'starttime';
11918: }
11919: my @sorted;
11920: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11921: @sorted =
11922: sort {
11923: if (ref($slots->{$a}) && ref($slots->{$b})) {
11924: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11925: }
11926: if (ref($slots->{$a})) { return -1;}
11927: if (ref($slots->{$b})) { return 1;}
11928: return 0;
11929: } @{$slotsarr};
11930: }
11931: return @sorted;
11932: }
11933:
11934: =pod
11935:
11936: =item * get_future_slots()
11937:
11938: Inputs:
11939:
11940: =over 4
11941:
11942: cnum - course number
11943:
11944: cdom - course domain
11945:
11946: now - current UNIX time
11947:
11948: symb - optional symb
11949:
11950: =back
11951:
11952: Returns:
11953:
11954: =over 4
11955:
11956: sorted_reservable - ref to array of student_schedulable slots currently
11957: reservable, ordered by end date of reservation period.
11958:
11959: reservable_now - ref to hash of student_schedulable slots currently
11960: reservable.
11961:
11962: Keys in inner hash are:
11963: (a) symb: either blank or symb to which slot use is restricted.
11964: (b) endreserve: end date of reservation period.
11965: (c) uniqueperiod: start,end dates when slot is to be uniquely
11966: selected.
11967:
11968: sorted_future - ref to array of student_schedulable slots reservable in
11969: the future, ordered by start date of reservation period.
11970:
11971: future_reservable - ref to hash of student_schedulable slots reservable
11972: in the future.
11973:
11974: Keys in inner hash are:
11975: (a) symb: either blank or symb to which slot use is restricted.
11976: (b) startreserve: start date of reservation period.
11977: (c) uniqueperiod: start,end dates when slot is to be uniquely
11978: selected.
11979:
11980: =back
11981:
11982: =cut
11983:
11984: sub get_future_slots {
11985: my ($cnum,$cdom,$now,$symb) = @_;
11986: my $map;
11987: if ($symb) {
11988: ($map) = &Apache::lonnet::decode_symb($symb);
11989: }
11990: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11991: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11992: foreach my $slot (keys(%slots)) {
11993: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11994: if ($symb) {
11995: if ($slots{$slot}->{'symb'} ne '') {
11996: my $canuse;
11997: my %oksymbs;
11998: my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11999: map { $oksymbs{$_} = 1; } @slotsymbs;
12000: if ($oksymbs{$symb}) {
12001: $canuse = 1;
12002: } else {
12003: foreach my $item (@slotsymbs) {
12004: if ($item =~ /\.(page|sequence)$/) {
12005: (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12006: if (($map ne '') && ($map eq $sloturl)) {
12007: $canuse = 1;
12008: last;
12009: }
12010: }
12011: }
12012: }
12013: next unless ($canuse);
12014: }
12015: }
12016: if (($slots{$slot}->{'starttime'} > $now) &&
12017: ($slots{$slot}->{'endtime'} > $now)) {
12018: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12019: my $userallowed = 0;
12020: if ($slots{$slot}->{'allowedsections'}) {
12021: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12022: if (!defined($env{'request.role.sec'})
12023: && grep(/^No section assigned$/,@allowed_sec)) {
12024: $userallowed=1;
12025: } else {
12026: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12027: $userallowed=1;
12028: }
12029: }
12030: unless ($userallowed) {
12031: if (defined($env{'request.course.groups'})) {
12032: my @groups = split(/:/,$env{'request.course.groups'});
12033: foreach my $group (@groups) {
12034: if (grep(/^\Q$group\E$/,@allowed_sec)) {
12035: $userallowed=1;
12036: last;
12037: }
12038: }
12039: }
12040: }
12041: }
12042: if ($slots{$slot}->{'allowedusers'}) {
12043: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12044: my $user = $env{'user.name'}.':'.$env{'user.domain'};
12045: if (grep(/^\Q$user\E$/,@allowed_users)) {
12046: $userallowed = 1;
12047: }
12048: }
12049: next unless($userallowed);
12050: }
12051: my $startreserve = $slots{$slot}->{'startreserve'};
12052: my $endreserve = $slots{$slot}->{'endreserve'};
12053: my $symb = $slots{$slot}->{'symb'};
12054: my $uniqueperiod;
12055: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12056: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12057: }
12058: if (($startreserve < $now) &&
12059: (!$endreserve || $endreserve > $now)) {
12060: my $lastres = $endreserve;
12061: if (!$lastres) {
12062: $lastres = $slots{$slot}->{'starttime'};
12063: }
12064: $reservable_now{$slot} = {
12065: symb => $symb,
12066: endreserve => $lastres,
12067: uniqueperiod => $uniqueperiod,
12068: };
12069: } elsif (($startreserve > $now) &&
12070: (!$endreserve || $endreserve > $startreserve)) {
12071: $future_reservable{$slot} = {
12072: symb => $symb,
12073: startreserve => $startreserve,
12074: uniqueperiod => $uniqueperiod,
12075: };
12076: }
12077: }
12078: }
12079: my @unsorted_reservable = keys(%reservable_now);
12080: if (@unsorted_reservable > 0) {
12081: @sorted_reservable =
12082: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12083: }
12084: my @unsorted_future = keys(%future_reservable);
12085: if (@unsorted_future > 0) {
12086: @sorted_future =
12087: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12088: }
12089: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12090: }
12091:
12092: =pod
12093:
12094: =back
12095:
12096: =head1 HTTP Helpers
12097:
12098: =over 4
12099:
12100: =item * &get_unprocessed_cgi($query,$possible_names)
12101:
12102: Modify the %env hash to contain unprocessed CGI form parameters held in
12103: $query. The parameters listed in $possible_names (an array reference),
12104: will be set in $env{'form.name'} if they do not already exist.
12105:
12106: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
12107: $possible_names is an ref to an array of form element names. As an example:
12108: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12109: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12110:
12111: =cut
12112:
12113: sub get_unprocessed_cgi {
12114: my ($query,$possible_names)= @_;
12115: # $Apache::lonxml::debug=1;
12116: foreach my $pair (split(/&/,$query)) {
12117: my ($name, $value) = split(/=/,$pair);
12118: $name = &unescape($name);
12119: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12120: $value =~ tr/+/ /;
12121: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12122: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12123: }
12124: }
12125: }
12126:
12127: =pod
12128:
12129: =item * &cacheheader()
12130:
12131: returns cache-controlling header code
12132:
12133: =cut
12134:
12135: sub cacheheader {
12136: unless ($env{'request.method'} eq 'GET') { return ''; }
12137: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12138: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12139: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12140: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12141: return $output;
12142: }
12143:
12144: =pod
12145:
12146: =item * &no_cache($r)
12147:
12148: specifies header code to not have cache
12149:
12150: =cut
12151:
12152: sub no_cache {
12153: my ($r) = @_;
12154: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12155: $env{'request.method'} ne 'GET') { return ''; }
12156: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12157: $r->no_cache(1);
12158: $r->header_out("Expires" => $date);
12159: $r->header_out("Pragma" => "no-cache");
12160: }
12161:
12162: sub content_type {
12163: my ($r,$type,$charset) = @_;
12164: if ($r) {
12165: # Note that printout.pl calls this with undef for $r.
12166: &no_cache($r);
12167: }
12168: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12169: unless ($charset) {
12170: $charset=&Apache::lonlocal::current_encoding;
12171: }
12172: if ($charset) { $type.='; charset='.$charset; }
12173: if ($r) {
12174: $r->content_type($type);
12175: } else {
12176: print("Content-type: $type\n\n");
12177: }
12178: }
12179:
12180: =pod
12181:
12182: =item * &add_to_env($name,$value)
12183:
12184: adds $name to the %env hash with value
12185: $value, if $name already exists, the entry is converted to an array
12186: reference and $value is added to the array.
12187:
12188: =cut
12189:
12190: sub add_to_env {
12191: my ($name,$value)=@_;
12192: if (defined($env{$name})) {
12193: if (ref($env{$name})) {
12194: #already have multiple values
12195: push(@{ $env{$name} },$value);
12196: } else {
12197: #first time seeing multiple values, convert hash entry to an arrayref
12198: my $first=$env{$name};
12199: undef($env{$name});
12200: push(@{ $env{$name} },$first,$value);
12201: }
12202: } else {
12203: $env{$name}=$value;
12204: }
12205: }
12206:
12207: =pod
12208:
12209: =item * &get_env_multiple($name)
12210:
12211: gets $name from the %env hash, it seemlessly handles the cases where multiple
12212: values may be defined and end up as an array ref.
12213:
12214: returns an array of values
12215:
12216: =cut
12217:
12218: sub get_env_multiple {
12219: my ($name) = @_;
12220: my @values;
12221: if (defined($env{$name})) {
12222: # exists is it an array
12223: if (ref($env{$name})) {
12224: @values=@{ $env{$name} };
12225: } else {
12226: $values[0]=$env{$name};
12227: }
12228: }
12229: return(@values);
12230: }
12231:
12232: # Looks at given dependencies, and returns something depending on the context.
12233: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12234: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12235: # For all other contexts, returns ($output, $counter, $numpathchg).
12236: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12237: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
12238: # $numpathchg: integer with the number of cleaned up dependency paths.
12239: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12240: # \%mapping: hash reference clean path -> original path for all dependencies.
12241: # @param {string} actionurl - The path to the handler, indicative of the context.
12242: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12243: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12244: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12245: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
12246: # @return {Array} - array depending on the context (not a reference)
12247: sub ask_for_embedded_content {
12248: # NOTE: documentation was added afterwards, it could be wrong
12249: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12250: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12251: %currsubfile,%unused,$rem);
12252: my $counter = 0;
12253: my $numnew = 0;
12254: my $numremref = 0;
12255: my $numinvalid = 0;
12256: my $numpathchg = 0;
12257: my $numexisting = 0;
12258: my $numunused = 0;
12259: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12260: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12261: my $heading = &mt('Upload embedded files');
12262: my $buttontext = &mt('Upload');
12263:
12264: # fills these variables based on the context:
12265: # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12266: # $path, $fileloc, $title, $rem, $filename
12267: if ($env{'request.course.id'}) {
12268: if ($actionurl eq '/adm/dependencies') {
12269: $navmap = Apache::lonnavmaps::navmap->new();
12270: }
12271: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12272: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12273: }
12274: if (($actionurl eq '/adm/portfolio') ||
12275: ($actionurl eq '/adm/coursegrp_portfolio')) {
12276: my $current_path='/';
12277: if ($env{'form.currentpath'}) {
12278: $current_path = $env{'form.currentpath'};
12279: }
12280: if ($actionurl eq '/adm/coursegrp_portfolio') {
12281: $udom = $cdom;
12282: $uname = $cnum;
12283: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12284: } else {
12285: $udom = $env{'user.domain'};
12286: $uname = $env{'user.name'};
12287: $url = '/userfiles/portfolio';
12288: }
12289: $toplevel = $url.'/';
12290: $url .= $current_path;
12291: $getpropath = 1;
12292: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12293: ($actionurl eq '/adm/imsimport')) {
12294: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12295: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12296: $toplevel = $url;
12297: if ($rest ne '') {
12298: $url .= $rest;
12299: }
12300: } elsif ($actionurl eq '/adm/coursedocs') {
12301: if (ref($args) eq 'HASH') {
12302: $url = $args->{'docs_url'};
12303: $toplevel = $url;
12304: if ($args->{'context'} eq 'paste') {
12305: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12306: ($path) =
12307: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12308: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12309: $fileloc =~ s{^/}{};
12310: }
12311: }
12312: } elsif ($actionurl eq '/adm/dependencies') {
12313: if ($env{'request.course.id'} ne '') {
12314: if (ref($args) eq 'HASH') {
12315: $url = $args->{'docs_url'};
12316: $title = $args->{'docs_title'};
12317: $toplevel = $url;
12318: unless ($toplevel =~ m{^/}) {
12319: $toplevel = "/$url";
12320: }
12321: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12322: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12323: $path = $1;
12324: } else {
12325: ($path) =
12326: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12327: }
12328: if ($toplevel=~/^\/*(uploaded|editupload)/) {
12329: $fileloc = $toplevel;
12330: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12331: my ($udom,$uname,$fname) =
12332: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12333: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12334: } else {
12335: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12336: }
12337: $fileloc =~ s{^/}{};
12338: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12339: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12340: }
12341: }
12342: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12343: $udom = $cdom;
12344: $uname = $cnum;
12345: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12346: $toplevel = $url;
12347: $path = $url;
12348: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12349: $fileloc =~ s{^/}{};
12350: }
12351:
12352: # parses the dependency paths to get some info
12353: # fills $newfiles, $mapping, $subdependencies, $dependencies
12354: # $newfiles: hash URL -> 1 for new files or external URLs
12355: # (will be completed later)
12356: # $mapping:
12357: # for external URLs: external URL -> external URL
12358: # for relative paths: clean path -> original path
12359: # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12360: # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12361: foreach my $file (keys(%{$allfiles})) {
12362: my $embed_file;
12363: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12364: $embed_file = $1;
12365: } else {
12366: $embed_file = $file;
12367: }
12368: my ($absolutepath,$cleaned_file);
12369: if ($embed_file =~ m{^\w+://}) {
12370: $cleaned_file = $embed_file;
12371: $newfiles{$cleaned_file} = 1;
12372: $mapping{$cleaned_file} = $embed_file;
12373: } else {
12374: $cleaned_file = &clean_path($embed_file);
12375: if ($embed_file =~ m{^/}) {
12376: $absolutepath = $embed_file;
12377: }
12378: if ($cleaned_file =~ m{/}) {
12379: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12380: $path = &check_for_traversal($path,$url,$toplevel);
12381: my $item = $fname;
12382: if ($path ne '') {
12383: $item = $path.'/'.$fname;
12384: $subdependencies{$path}{$fname} = 1;
12385: } else {
12386: $dependencies{$item} = 1;
12387: }
12388: if ($absolutepath) {
12389: $mapping{$item} = $absolutepath;
12390: } else {
12391: $mapping{$item} = $embed_file;
12392: }
12393: } else {
12394: $dependencies{$embed_file} = 1;
12395: if ($absolutepath) {
12396: $mapping{$cleaned_file} = $absolutepath;
12397: } else {
12398: $mapping{$cleaned_file} = $embed_file;
12399: }
12400: }
12401: }
12402: }
12403:
12404: # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12405: # and lists
12406: # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12407: # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12408: # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12409: # the path had to be cleaned up
12410: # $existing: hash clean path -> 1 if the file exists
12411: # $numexisting: number of keys in $existing
12412: # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12413: # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12414: # dependency subdirectories that are
12415: # not listed as dependencies, with some exceptions using $rem
12416: my $dirptr = 16384;
12417: foreach my $path (keys(%subdependencies)) {
12418: $currsubfile{$path} = {};
12419: if (($actionurl eq '/adm/portfolio') ||
12420: ($actionurl eq '/adm/coursegrp_portfolio')) {
12421: my ($sublistref,$listerror) =
12422: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12423: if (ref($sublistref) eq 'ARRAY') {
12424: foreach my $line (@{$sublistref}) {
12425: my ($file_name,$rest) = split(/\&/,$line,2);
12426: $currsubfile{$path}{$file_name} = 1;
12427: }
12428: }
12429: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12430: if (opendir(my $dir,$url.'/'.$path)) {
12431: my @subdir_list = grep(!/^\./,readdir($dir));
12432: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12433: }
12434: } elsif (($actionurl eq '/adm/dependencies') ||
12435: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12436: ($args->{'context'} eq 'paste')) ||
12437: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12438: if ($env{'request.course.id'} ne '') {
12439: my $dir;
12440: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12441: $dir = $fileloc;
12442: } else {
12443: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12444: }
12445: if ($dir ne '') {
12446: my ($sublistref,$listerror) =
12447: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12448: if (ref($sublistref) eq 'ARRAY') {
12449: foreach my $line (@{$sublistref}) {
12450: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12451: undef,$mtime)=split(/\&/,$line,12);
12452: unless (($testdir&$dirptr) ||
12453: ($file_name =~ /^\.\.?$/)) {
12454: $currsubfile{$path}{$file_name} = [$size,$mtime];
12455: }
12456: }
12457: }
12458: }
12459: }
12460: }
12461: foreach my $file (keys(%{$subdependencies{$path}})) {
12462: if (exists($currsubfile{$path}{$file})) {
12463: my $item = $path.'/'.$file;
12464: unless ($mapping{$item} eq $item) {
12465: $pathchanges{$item} = 1;
12466: }
12467: $existing{$item} = 1;
12468: $numexisting ++;
12469: } else {
12470: $newfiles{$path.'/'.$file} = 1;
12471: }
12472: }
12473: if ($actionurl eq '/adm/dependencies') {
12474: foreach my $path (keys(%currsubfile)) {
12475: if (ref($currsubfile{$path}) eq 'HASH') {
12476: foreach my $file (keys(%{$currsubfile{$path}})) {
12477: unless ($subdependencies{$path}{$file}) {
12478: next if (($rem ne '') &&
12479: (($env{"httpref.$rem"."$path/$file"} ne '') ||
12480: (ref($navmap) &&
12481: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12482: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12483: ($navmap->getResourceByUrl($rem."$path/$1")))))));
12484: $unused{$path.'/'.$file} = 1;
12485: }
12486: }
12487: }
12488: }
12489: }
12490: }
12491:
12492: # fills $currfile, hash file name -> 1 or [$size,$mtime]
12493: # for files in $url or $fileloc (target directory) in some contexts
12494: my %currfile;
12495: if (($actionurl eq '/adm/portfolio') ||
12496: ($actionurl eq '/adm/coursegrp_portfolio')) {
12497: my ($dirlistref,$listerror) =
12498: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12499: if (ref($dirlistref) eq 'ARRAY') {
12500: foreach my $line (@{$dirlistref}) {
12501: my ($file_name,$rest) = split(/\&/,$line,2);
12502: $currfile{$file_name} = 1;
12503: }
12504: }
12505: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12506: if (opendir(my $dir,$url)) {
12507: my @dir_list = grep(!/^\./,readdir($dir));
12508: map {$currfile{$_} = 1;} @dir_list;
12509: }
12510: } elsif (($actionurl eq '/adm/dependencies') ||
12511: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12512: ($args->{'context'} eq 'paste')) ||
12513: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12514: if ($env{'request.course.id'} ne '') {
12515: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12516: if ($dir ne '') {
12517: my ($dirlistref,$listerror) =
12518: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12519: if (ref($dirlistref) eq 'ARRAY') {
12520: foreach my $line (@{$dirlistref}) {
12521: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12522: $size,undef,$mtime)=split(/\&/,$line,12);
12523: unless (($testdir&$dirptr) ||
12524: ($file_name =~ /^\.\.?$/)) {
12525: $currfile{$file_name} = [$size,$mtime];
12526: }
12527: }
12528: }
12529: }
12530: }
12531: }
12532: # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12533: # are not in subdirectories, using $currfile
12534: foreach my $file (keys(%dependencies)) {
12535: if (exists($currfile{$file})) {
12536: unless ($mapping{$file} eq $file) {
12537: $pathchanges{$file} = 1;
12538: }
12539: $existing{$file} = 1;
12540: $numexisting ++;
12541: } else {
12542: $newfiles{$file} = 1;
12543: }
12544: }
12545: foreach my $file (keys(%currfile)) {
12546: unless (($file eq $filename) ||
12547: ($file eq $filename.'.bak') ||
12548: ($dependencies{$file})) {
12549: if ($actionurl eq '/adm/dependencies') {
12550: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12551: next if (($rem ne '') &&
12552: (($env{"httpref.$rem".$file} ne '') ||
12553: (ref($navmap) &&
12554: (($navmap->getResourceByUrl($rem.$file) ne '') ||
12555: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12556: ($navmap->getResourceByUrl($rem.$1)))))));
12557: }
12558: }
12559: $unused{$file} = 1;
12560: }
12561: }
12562:
12563: # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12564: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12565: ($args->{'context'} eq 'paste')) {
12566: $counter = scalar(keys(%existing));
12567: $numpathchg = scalar(keys(%pathchanges));
12568: return ($output,$counter,$numpathchg,\%existing);
12569: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
12570: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12571: $counter = scalar(keys(%existing));
12572: $numpathchg = scalar(keys(%pathchanges));
12573: return ($output,$counter,$numpathchg,\%existing,\%mapping);
12574: }
12575:
12576: # returns HTML otherwise, with dependency results and to ask for more uploads
12577:
12578: # $upload_output: missing dependencies (with upload form)
12579: # $modify_output: uploaded dependencies (in use)
12580: # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12581: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12582: if ($actionurl eq '/adm/dependencies') {
12583: next if ($embed_file =~ m{^\w+://});
12584: }
12585: $upload_output .= &start_data_table_row().
12586: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12587: '<span class="LC_filename">'.$embed_file.'</span>';
12588: unless ($mapping{$embed_file} eq $embed_file) {
12589: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12590: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12591: }
12592: $upload_output .= '</td>';
12593: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
12594: $upload_output.='<td align="right">'.
12595: '<span class="LC_info LC_fontsize_medium">'.
12596: &mt("URL points to web address").'</span>';
12597: $numremref++;
12598: } elsif ($args->{'error_on_invalid_names'}
12599: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12600: $upload_output.='<td align="right"><span class="LC_warning">'.
12601: &mt('Invalid characters').'</span>';
12602: $numinvalid++;
12603: } else {
12604: $upload_output .= '<td>'.
12605: &embedded_file_element('upload_embedded',$counter,
12606: $embed_file,\%mapping,
12607: $allfiles,$codebase,'upload');
12608: $counter ++;
12609: $numnew ++;
12610: }
12611: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12612: }
12613: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12614: if ($actionurl eq '/adm/dependencies') {
12615: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12616: $modify_output .= &start_data_table_row().
12617: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12618: '<img src="'.&icon($embed_file).'" border="0" />'.
12619: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
12620: '<td>'.$size.'</td>'.
12621: '<td>'.$mtime.'</td>'.
12622: '<td><label><input type="checkbox" name="mod_upload_dep" '.
12623: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12624: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12625: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12626: &embedded_file_element('upload_embedded',$counter,
12627: $embed_file,\%mapping,
12628: $allfiles,$codebase,'modify').
12629: '</div></td>'.
12630: &end_data_table_row()."\n";
12631: $counter ++;
12632: } else {
12633: $upload_output .= &start_data_table_row().
12634: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12635: '<span class="LC_filename">'.$embed_file.'</span></td>'.
12636: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12637: &Apache::loncommon::end_data_table_row()."\n";
12638: }
12639: }
12640: my $delidx = $counter;
12641: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12642: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12643: $delete_output .= &start_data_table_row().
12644: '<td><img src="'.&icon($oldfile).'" />'.
12645: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
12646: '<td>'.$size.'</td>'.
12647: '<td>'.$mtime.'</td>'.
12648: '<td><label><input type="checkbox" name="del_upload_dep" '.
12649: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12650: &embedded_file_element('upload_embedded',$delidx,
12651: $oldfile,\%mapping,$allfiles,
12652: $codebase,'delete').'</td>'.
12653: &end_data_table_row()."\n";
12654: $numunused ++;
12655: $delidx ++;
12656: }
12657: if ($upload_output) {
12658: $upload_output = &start_data_table().
12659: $upload_output.
12660: &end_data_table()."\n";
12661: }
12662: if ($modify_output) {
12663: $modify_output = &start_data_table().
12664: &start_data_table_header_row().
12665: '<th>'.&mt('File').'</th>'.
12666: '<th>'.&mt('Size (KB)').'</th>'.
12667: '<th>'.&mt('Modified').'</th>'.
12668: '<th>'.&mt('Upload replacement?').'</th>'.
12669: &end_data_table_header_row().
12670: $modify_output.
12671: &end_data_table()."\n";
12672: }
12673: if ($delete_output) {
12674: $delete_output = &start_data_table().
12675: &start_data_table_header_row().
12676: '<th>'.&mt('File').'</th>'.
12677: '<th>'.&mt('Size (KB)').'</th>'.
12678: '<th>'.&mt('Modified').'</th>'.
12679: '<th>'.&mt('Delete?').'</th>'.
12680: &end_data_table_header_row().
12681: $delete_output.
12682: &end_data_table()."\n";
12683: }
12684: my $applies = 0;
12685: if ($numremref) {
12686: $applies ++;
12687: }
12688: if ($numinvalid) {
12689: $applies ++;
12690: }
12691: if ($numexisting) {
12692: $applies ++;
12693: }
12694: if ($counter || $numunused) {
12695: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12696: ' method="post" enctype="multipart/form-data">'."\n".
12697: $state.'<h3>'.$heading.'</h3>';
12698: if ($actionurl eq '/adm/dependencies') {
12699: if ($numnew) {
12700: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12701: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12702: $upload_output.'<br />'."\n";
12703: }
12704: if ($numexisting) {
12705: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12706: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12707: $modify_output.'<br />'."\n";
12708: $buttontext = &mt('Save changes');
12709: }
12710: if ($numunused) {
12711: $output .= '<h4>'.&mt('Unused files').'</h4>'.
12712: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12713: $delete_output.'<br />'."\n";
12714: $buttontext = &mt('Save changes');
12715: }
12716: } else {
12717: $output .= $upload_output.'<br />'."\n";
12718: }
12719: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12720: $counter.'" />'."\n";
12721: if ($actionurl eq '/adm/dependencies') {
12722: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12723: $numnew.'" />'."\n";
12724: } elsif ($actionurl eq '') {
12725: $output .= '<input type="hidden" name="phase" value="three" />';
12726: }
12727: } elsif ($applies) {
12728: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12729: if ($applies > 1) {
12730: $output .=
12731: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12732: if ($numremref) {
12733: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12734: }
12735: if ($numinvalid) {
12736: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12737: }
12738: if ($numexisting) {
12739: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12740: }
12741: $output .= '</ul><br />';
12742: } elsif ($numremref) {
12743: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12744: } elsif ($numinvalid) {
12745: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12746: } elsif ($numexisting) {
12747: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12748: }
12749: $output .= $upload_output.'<br />';
12750: }
12751: my ($pathchange_output,$chgcount);
12752: $chgcount = $counter;
12753: if (keys(%pathchanges) > 0) {
12754: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12755: if ($counter) {
12756: $output .= &embedded_file_element('pathchange',$chgcount,
12757: $embed_file,\%mapping,
12758: $allfiles,$codebase,'change');
12759: } else {
12760: $pathchange_output .=
12761: &start_data_table_row().
12762: '<td><input type ="checkbox" name="namechange" value="'.
12763: $chgcount.'" checked="checked" /></td>'.
12764: '<td>'.$mapping{$embed_file}.'</td>'.
12765: '<td>'.$embed_file.
12766: &embedded_file_element('pathchange',$numpathchg,$embed_file,
12767: \%mapping,$allfiles,$codebase,'change').
12768: '</td>'.&end_data_table_row();
12769: }
12770: $numpathchg ++;
12771: $chgcount ++;
12772: }
12773: }
12774: if (($counter) || ($numunused)) {
12775: if ($numpathchg) {
12776: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12777: $numpathchg.'" />'."\n";
12778: }
12779: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12780: ($actionurl eq '/adm/imsimport')) {
12781: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12782: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12783: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12784: } elsif ($actionurl eq '/adm/dependencies') {
12785: $output .= '<input type="hidden" name="action" value="process_changes" />';
12786: }
12787: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12788: } elsif ($numpathchg) {
12789: my %pathchange = ();
12790: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12791: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12792: $output .= '<p>'.&mt('or').'</p>';
12793: }
12794: }
12795: return ($output,$counter,$numpathchg);
12796: }
12797:
12798: =pod
12799:
12800: =item * clean_path($name)
12801:
12802: Performs clean-up of directories, subdirectories and filename in an
12803: embedded object, referenced in an HTML file which is being uploaded
12804: to a course or portfolio, where
12805: "Upload embedded images/multimedia files if HTML file" checkbox was
12806: checked.
12807:
12808: Clean-up is similar to replacements in lonnet::clean_filename()
12809: except each / between sub-directory and next level is preserved.
12810:
12811: =cut
12812:
12813: sub clean_path {
12814: my ($embed_file) = @_;
12815: $embed_file =~s{^/+}{};
12816: my @contents;
12817: if ($embed_file =~ m{/}) {
12818: @contents = split(/\//,$embed_file);
12819: } else {
12820: @contents = ($embed_file);
12821: }
12822: my $lastidx = scalar(@contents)-1;
12823: for (my $i=0; $i<=$lastidx; $i++) {
12824: $contents[$i]=~s{\\}{/}g;
12825: $contents[$i]=~s/\s+/\_/g;
12826: $contents[$i]=~s{[^/\w\.\-]}{}g;
12827: if ($i == $lastidx) {
12828: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12829: }
12830: }
12831: if ($lastidx > 0) {
12832: return join('/',@contents);
12833: } else {
12834: return $contents[0];
12835: }
12836: }
12837:
12838: sub embedded_file_element {
12839: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12840: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12841: (ref($codebase) eq 'HASH'));
12842: my $output;
12843: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12844: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12845: }
12846: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12847: &escape($embed_file).'" />';
12848: unless (($context eq 'upload_embedded') &&
12849: ($mapping->{$embed_file} eq $embed_file)) {
12850: $output .='
12851: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12852: }
12853: my $attrib;
12854: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12855: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12856: }
12857: $output .=
12858: "\n\t\t".
12859: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12860: $attrib.'" />';
12861: if (exists($codebase->{$mapping->{$embed_file}})) {
12862: $output .=
12863: "\n\t\t".
12864: '<input name="codebase_'.$num.'" type="hidden" value="'.
12865: &escape($codebase->{$mapping->{$embed_file}}).'" />';
12866: }
12867: return $output;
12868: }
12869:
12870: sub get_dependency_details {
12871: my ($currfile,$currsubfile,$embed_file) = @_;
12872: my ($size,$mtime,$showsize,$showmtime);
12873: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12874: if ($embed_file =~ m{/}) {
12875: my ($path,$fname) = split(/\//,$embed_file);
12876: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12877: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12878: }
12879: } else {
12880: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12881: ($size,$mtime) = @{$currfile->{$embed_file}};
12882: }
12883: }
12884: $showsize = $size/1024.0;
12885: $showsize = sprintf("%.1f",$showsize);
12886: if ($mtime > 0) {
12887: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12888: }
12889: }
12890: return ($showsize,$showmtime);
12891: }
12892:
12893: sub ask_embedded_js {
12894: return <<"END";
12895: <script type="text/javascript"">
12896: // <![CDATA[
12897: function toggleBrowse(counter) {
12898: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12899: var fileid = document.getElementById('embedded_item_'+counter);
12900: var uploaddivid = document.getElementById('moduploaddep_'+counter);
12901: if (chkboxid.checked == true) {
12902: uploaddivid.style.display='block';
12903: } else {
12904: uploaddivid.style.display='none';
12905: fileid.value = '';
12906: }
12907: }
12908: // ]]>
12909: </script>
12910:
12911: END
12912: }
12913:
12914: sub upload_embedded {
12915: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12916: $current_disk_usage,$hiddenstate,$actionurl) = @_;
12917: my (%pathchange,$output,$modifyform,$footer,$returnflag);
12918: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12919: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12920: my $orig_uploaded_filename =
12921: $env{'form.embedded_item_'.$i.'.filename'};
12922: foreach my $type ('orig','ref','attrib','codebase') {
12923: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12924: $env{'form.embedded_'.$type.'_'.$i} =
12925: &unescape($env{'form.embedded_'.$type.'_'.$i});
12926: }
12927: }
12928: my ($path,$fname) =
12929: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12930: # no path, whole string is fname
12931: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12932: $fname = &Apache::lonnet::clean_filename($fname);
12933: # See if there is anything left
12934: next if ($fname eq '');
12935:
12936: # Check if file already exists as a file or directory.
12937: my ($state,$msg);
12938: if ($context eq 'portfolio') {
12939: my $port_path = $dirpath;
12940: if ($group ne '') {
12941: $port_path = "groups/$group/$port_path";
12942: }
12943: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12944: $fname,$group,'embedded_item_'.$i,
12945: $dir_root,$port_path,$disk_quota,
12946: $current_disk_usage,$uname,$udom);
12947: if ($state eq 'will_exceed_quota'
12948: || $state eq 'file_locked') {
12949: $output .= $msg;
12950: next;
12951: }
12952: } elsif (($context eq 'author') || ($context eq 'testbank')) {
12953: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12954: if ($state eq 'exists') {
12955: $output .= $msg;
12956: next;
12957: }
12958: }
12959: # Check if extension is valid
12960: if (($fname =~ /\.(\w+)$/) &&
12961: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12962: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12963: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12964: next;
12965: } elsif (($fname =~ /\.(\w+)$/) &&
12966: (!defined(&Apache::loncommon::fileembstyle($1)))) {
12967: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12968: next;
12969: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12970: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12971: next;
12972: }
12973: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12974: my $subdir = $path;
12975: $subdir =~ s{/+$}{};
12976: if ($context eq 'portfolio') {
12977: my $result;
12978: if ($state eq 'existingfile') {
12979: $result=
12980: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12981: $dirpath.$env{'form.currentpath'}.$subdir);
12982: } else {
12983: $result=
12984: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12985: $dirpath.
12986: $env{'form.currentpath'}.$subdir);
12987: if ($result !~ m|^/uploaded/|) {
12988: $output .= '<span class="LC_error">'
12989: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12990: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12991: .'</span><br />';
12992: next;
12993: } else {
12994: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12995: $path.$fname.'</span>').'<br />';
12996: }
12997: }
12998: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12999: my $extendedsubdir = $dirpath.'/'.$subdir;
13000: $extendedsubdir =~ s{/+$}{};
13001: my $result =
13002: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13003: if ($result !~ m|^/uploaded/|) {
13004: $output .= '<span class="LC_error">'
13005: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13006: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13007: .'</span><br />';
13008: next;
13009: } else {
13010: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13011: $path.$fname.'</span>').'<br />';
13012: if ($context eq 'syllabus') {
13013: &Apache::lonnet::make_public_indefinitely($result);
13014: }
13015: }
13016: } else {
13017: # Save the file
13018: my $target = $env{'form.embedded_item_'.$i};
13019: my $fullpath = $dir_root.$dirpath.'/'.$path;
13020: my $dest = $fullpath.$fname;
13021: my $url = $url_root.$dirpath.'/'.$path.$fname;
13022: my @parts=split(/\//,"$dirpath/$path");
13023: my $count;
13024: my $filepath = $dir_root;
13025: foreach my $subdir (@parts) {
13026: $filepath .= "/$subdir";
13027: if (!-e $filepath) {
13028: mkdir($filepath,0770);
13029: }
13030: }
13031: my $fh;
13032: if (!open($fh,'>'.$dest)) {
13033: &Apache::lonnet::logthis('Failed to create '.$dest);
13034: $output .= '<span class="LC_error">'.
13035: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13036: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13037: '</span><br />';
13038: } else {
13039: if (!print $fh $env{'form.embedded_item_'.$i}) {
13040: &Apache::lonnet::logthis('Failed to write to '.$dest);
13041: $output .= '<span class="LC_error">'.
13042: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13043: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13044: '</span><br />';
13045: } else {
13046: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13047: $url.'</span>').'<br />';
13048: unless ($context eq 'testbank') {
13049: $footer .= &mt('View embedded file: [_1]',
13050: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13051: }
13052: }
13053: close($fh);
13054: }
13055: }
13056: if ($env{'form.embedded_ref_'.$i}) {
13057: $pathchange{$i} = 1;
13058: }
13059: }
13060: if ($output) {
13061: $output = '<p>'.$output.'</p>';
13062: }
13063: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13064: $returnflag = 'ok';
13065: my $numpathchgs = scalar(keys(%pathchange));
13066: if ($numpathchgs > 0) {
13067: if ($context eq 'portfolio') {
13068: $output .= '<p>'.&mt('or').'</p>';
13069: } elsif ($context eq 'testbank') {
13070: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13071: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13072: $returnflag = 'modify_orightml';
13073: }
13074: }
13075: return ($output.$footer,$returnflag,$numpathchgs);
13076: }
13077:
13078: sub modify_html_form {
13079: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13080: my $end = 0;
13081: my $modifyform;
13082: if ($context eq 'upload_embedded') {
13083: return unless (ref($pathchange) eq 'HASH');
13084: if ($env{'form.number_embedded_items'}) {
13085: $end += $env{'form.number_embedded_items'};
13086: }
13087: if ($env{'form.number_pathchange_items'}) {
13088: $end += $env{'form.number_pathchange_items'};
13089: }
13090: if ($end) {
13091: for (my $i=0; $i<$end; $i++) {
13092: if ($i < $env{'form.number_embedded_items'}) {
13093: next unless($pathchange->{$i});
13094: }
13095: $modifyform .=
13096: &start_data_table_row().
13097: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13098: 'checked="checked" /></td>'.
13099: '<td>'.$env{'form.embedded_ref_'.$i}.
13100: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13101: &escape($env{'form.embedded_ref_'.$i}).'" />'.
13102: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13103: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13104: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13105: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13106: '<td>'.$env{'form.embedded_orig_'.$i}.
13107: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13108: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13109: &end_data_table_row();
13110: }
13111: }
13112: } else {
13113: $modifyform = $pathchgtable;
13114: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13115: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13116: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13117: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13118: }
13119: }
13120: if ($modifyform) {
13121: if ($actionurl eq '/adm/dependencies') {
13122: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13123: }
13124: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13125: '<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".
13126: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13127: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13128: '</ol></p>'."\n".'<p>'.
13129: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13130: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13131: &start_data_table()."\n".
13132: &start_data_table_header_row().
13133: '<th>'.&mt('Change?').'</th>'.
13134: '<th>'.&mt('Current reference').'</th>'.
13135: '<th>'.&mt('Required reference').'</th>'.
13136: &end_data_table_header_row()."\n".
13137: $modifyform.
13138: &end_data_table().'<br />'."\n".$hiddenstate.
13139: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13140: '</form>'."\n";
13141: }
13142: return;
13143: }
13144:
13145: sub modify_html_refs {
13146: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13147: my $container;
13148: if ($context eq 'portfolio') {
13149: $container = $env{'form.container'};
13150: } elsif ($context eq 'coursedoc') {
13151: $container = $env{'form.primaryurl'};
13152: } elsif ($context eq 'manage_dependencies') {
13153: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13154: $container = "/$container";
13155: } elsif ($context eq 'syllabus') {
13156: $container = $url;
13157: } else {
13158: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13159: }
13160: my (%allfiles,%codebase,$output,$content);
13161: my @changes = &get_env_multiple('form.namechange');
13162: unless ((@changes > 0) || ($context eq 'syllabus')) {
13163: if (wantarray) {
13164: return ('',0,0);
13165: } else {
13166: return;
13167: }
13168: }
13169: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
13170: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13171: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13172: if (wantarray) {
13173: return ('',0,0);
13174: } else {
13175: return;
13176: }
13177: }
13178: $content = &Apache::lonnet::getfile($container);
13179: if ($content eq '-1') {
13180: if (wantarray) {
13181: return ('',0,0);
13182: } else {
13183: return;
13184: }
13185: }
13186: } else {
13187: unless ($container =~ /^\Q$dir_root\E/) {
13188: if (wantarray) {
13189: return ('',0,0);
13190: } else {
13191: return;
13192: }
13193: }
13194: if (open(my $fh,'<',$container)) {
13195: $content = join('', <$fh>);
13196: close($fh);
13197: } else {
13198: if (wantarray) {
13199: return ('',0,0);
13200: } else {
13201: return;
13202: }
13203: }
13204: }
13205: my ($count,$codebasecount) = (0,0);
13206: my $mm = new File::MMagic;
13207: my $mime_type = $mm->checktype_contents($content);
13208: if ($mime_type eq 'text/html') {
13209: my $parse_result =
13210: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13211: \%codebase,\$content);
13212: if ($parse_result eq 'ok') {
13213: foreach my $i (@changes) {
13214: my $orig = &unescape($env{'form.embedded_orig_'.$i});
13215: my $ref = &unescape($env{'form.embedded_ref_'.$i});
13216: if ($allfiles{$ref}) {
13217: my $newname = $orig;
13218: my ($attrib_regexp,$codebase);
13219: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13220: if ($attrib_regexp =~ /:/) {
13221: $attrib_regexp =~ s/\:/|/g;
13222: }
13223: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13224: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13225: $count += $numchg;
13226: $allfiles{$newname} = $allfiles{$ref};
13227: delete($allfiles{$ref});
13228: }
13229: if ($env{'form.embedded_codebase_'.$i} ne '') {
13230: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13231: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13232: $codebasecount ++;
13233: }
13234: }
13235: }
13236: my $skiprewrites;
13237: if ($count || $codebasecount) {
13238: my $saveresult;
13239: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
13240: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13241: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13242: if ($url eq $container) {
13243: my ($fname) = ($container =~ m{/([^/]+)$});
13244: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13245: $count,'<span class="LC_filename">'.
13246: $fname.'</span>').'</p>';
13247: } else {
13248: $output = '<p class="LC_error">'.
13249: &mt('Error: update failed for: [_1].',
13250: '<span class="LC_filename">'.
13251: $container.'</span>').'</p>';
13252: }
13253: if ($context eq 'syllabus') {
13254: unless ($saveresult eq 'ok') {
13255: $skiprewrites = 1;
13256: }
13257: }
13258: } else {
13259: if (open(my $fh,'>',$container)) {
13260: print $fh $content;
13261: close($fh);
13262: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13263: $count,'<span class="LC_filename">'.
13264: $container.'</span>').'</p>';
13265: } else {
13266: $output = '<p class="LC_error">'.
13267: &mt('Error: could not update [_1].',
13268: '<span class="LC_filename">'.
13269: $container.'</span>').'</p>';
13270: }
13271: }
13272: }
13273: if (($context eq 'syllabus') && (!$skiprewrites)) {
13274: my ($actionurl,$state);
13275: $actionurl = "/public/$udom/$uname/syllabus";
13276: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13277: &ask_for_embedded_content($actionurl,$state,\%allfiles,
13278: \%codebase,
13279: {'context' => 'rewrites',
13280: 'ignore_remote_references' => 1,});
13281: if (ref($mapping) eq 'HASH') {
13282: my $rewrites = 0;
13283: foreach my $key (keys(%{$mapping})) {
13284: next if ($key =~ m{^https?://});
13285: my $ref = $mapping->{$key};
13286: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13287: my $attrib;
13288: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13289: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13290: }
13291: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13292: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13293: $rewrites += $numchg;
13294: }
13295: }
13296: if ($rewrites) {
13297: my $saveresult;
13298: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13299: if ($url eq $container) {
13300: my ($fname) = ($container =~ m{/([^/]+)$});
13301: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13302: $count,'<span class="LC_filename">'.
13303: $fname.'</span>').'</p>';
13304: } else {
13305: $output .= '<p class="LC_error">'.
13306: &mt('Error: could not update links in [_1].',
13307: '<span class="LC_filename">'.
13308: $container.'</span>').'</p>';
13309:
13310: }
13311: }
13312: }
13313: }
13314: } else {
13315: &logthis('Failed to parse '.$container.
13316: ' to modify references: '.$parse_result);
13317: }
13318: }
13319: if (wantarray) {
13320: return ($output,$count,$codebasecount);
13321: } else {
13322: return $output;
13323: }
13324: }
13325:
13326: sub check_for_existing {
13327: my ($path,$fname,$element) = @_;
13328: my ($state,$msg);
13329: if (-d $path.'/'.$fname) {
13330: $state = 'exists';
13331: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13332: } elsif (-e $path.'/'.$fname) {
13333: $state = 'exists';
13334: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13335: }
13336: if ($state eq 'exists') {
13337: $msg = '<span class="LC_error">'.$msg.'</span><br />';
13338: }
13339: return ($state,$msg);
13340: }
13341:
13342: sub check_for_upload {
13343: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13344: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13345: my $filesize = length($env{'form.'.$element});
13346: if (!$filesize) {
13347: my $msg = '<span class="LC_error">'.
13348: &mt('Unable to upload [_1]. (size = [_2] bytes)',
13349: '<span class="LC_filename">'.$fname.'</span>',
13350: $filesize).'<br />'.
13351: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13352: '</span>';
13353: return ('zero_bytes',$msg);
13354: }
13355: $filesize = $filesize/1000; #express in k (1024?)
13356: my $getpropath = 1;
13357: my ($dirlistref,$listerror) =
13358: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13359: my $found_file = 0;
13360: my $locked_file = 0;
13361: my @lockers;
13362: my $navmap;
13363: if ($env{'request.course.id'}) {
13364: $navmap = Apache::lonnavmaps::navmap->new();
13365: }
13366: if (ref($dirlistref) eq 'ARRAY') {
13367: foreach my $line (@{$dirlistref}) {
13368: my ($file_name,$rest)=split(/\&/,$line,2);
13369: if ($file_name eq $fname){
13370: $file_name = $path.$file_name;
13371: if ($group ne '') {
13372: $file_name = $group.$file_name;
13373: }
13374: $found_file = 1;
13375: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13376: foreach my $lock (@lockers) {
13377: if (ref($lock) eq 'ARRAY') {
13378: my ($symb,$crsid) = @{$lock};
13379: if ($crsid eq $env{'request.course.id'}) {
13380: if (ref($navmap)) {
13381: my $res = $navmap->getBySymb($symb);
13382: foreach my $part (@{$res->parts()}) {
13383: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13384: unless (($slot_status == $res->RESERVED) ||
13385: ($slot_status == $res->RESERVED_LOCATION)) {
13386: $locked_file = 1;
13387: }
13388: }
13389: } else {
13390: $locked_file = 1;
13391: }
13392: } else {
13393: $locked_file = 1;
13394: }
13395: }
13396: }
13397: } else {
13398: my @info = split(/\&/,$rest);
13399: my $currsize = $info[6]/1000;
13400: if ($currsize < $filesize) {
13401: my $extra = $filesize - $currsize;
13402: if (($current_disk_usage + $extra) > $disk_quota) {
13403: my $msg = '<p class="LC_warning">'.
13404: &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.',
13405: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13406: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13407: $disk_quota,$current_disk_usage).'</p>';
13408: return ('will_exceed_quota',$msg);
13409: }
13410: }
13411: }
13412: }
13413: }
13414: }
13415: if (($current_disk_usage + $filesize) > $disk_quota){
13416: my $msg = '<p class="LC_warning">'.
13417: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13418: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13419: return ('will_exceed_quota',$msg);
13420: } elsif ($found_file) {
13421: if ($locked_file) {
13422: my $msg = '<p class="LC_warning">';
13423: $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>');
13424: $msg .= '</p>';
13425: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13426: return ('file_locked',$msg);
13427: } else {
13428: my $msg = '<p class="LC_error">';
13429: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13430: $msg .= '</p>';
13431: return ('existingfile',$msg);
13432: }
13433: }
13434: }
13435:
13436: sub check_for_traversal {
13437: my ($path,$url,$toplevel) = @_;
13438: my @parts=split(/\//,$path);
13439: my $cleanpath;
13440: my $fullpath = $url;
13441: for (my $i=0;$i<@parts;$i++) {
13442: next if ($parts[$i] eq '.');
13443: if ($parts[$i] eq '..') {
13444: $fullpath =~ s{([^/]+/)$}{};
13445: } else {
13446: $fullpath .= $parts[$i].'/';
13447: }
13448: }
13449: if ($fullpath =~ /^\Q$url\E(.*)$/) {
13450: $cleanpath = $1;
13451: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13452: my $curr_toprel = $1;
13453: my @parts = split(/\//,$curr_toprel);
13454: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13455: my @urlparts = split(/\//,$url_toprel);
13456: my $doubledots;
13457: my $startdiff = -1;
13458: for (my $i=0; $i<@urlparts; $i++) {
13459: if ($startdiff == -1) {
13460: unless ($urlparts[$i] eq $parts[$i]) {
13461: $startdiff = $i;
13462: $doubledots .= '../';
13463: }
13464: } else {
13465: $doubledots .= '../';
13466: }
13467: }
13468: if ($startdiff > -1) {
13469: $cleanpath = $doubledots;
13470: for (my $i=$startdiff; $i<@parts; $i++) {
13471: $cleanpath .= $parts[$i].'/';
13472: }
13473: }
13474: }
13475: $cleanpath =~ s{(/)$}{};
13476: return $cleanpath;
13477: }
13478:
13479: sub is_archive_file {
13480: my ($mimetype) = @_;
13481: if (($mimetype eq 'application/octet-stream') ||
13482: ($mimetype eq 'application/x-stuffit') ||
13483: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13484: return 1;
13485: }
13486: return;
13487: }
13488:
13489: sub decompress_form {
13490: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13491: my %lt = &Apache::lonlocal::texthash (
13492: this => 'This file is an archive file.',
13493: camt => 'This file is a Camtasia archive file.',
13494: itsc => 'Its contents are as follows:',
13495: youm => 'You may wish to extract its contents.',
13496: extr => 'Extract contents',
13497: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13498: proa => 'Process automatically?',
13499: yes => 'Yes',
13500: no => 'No',
13501: fold => 'Title for folder containing movie',
13502: movi => 'Title for page containing embedded movie',
13503: );
13504: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13505: my ($is_camtasia,$topdir,%toplevel,@paths);
13506: my $info = &list_archive_contents($fileloc,\@paths);
13507: if (@paths) {
13508: foreach my $path (@paths) {
13509: $path =~ s{^/}{};
13510: if ($path =~ m{^([^/]+)/$}) {
13511: $topdir = $1;
13512: }
13513: if ($path =~ m{^([^/]+)/}) {
13514: $toplevel{$1} = $path;
13515: } else {
13516: $toplevel{$path} = $path;
13517: }
13518: }
13519: }
13520: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13521: my @camtasia6 = ("$topdir/","$topdir/index.html",
13522: "$topdir/media/",
13523: "$topdir/media/$topdir.mp4",
13524: "$topdir/media/FirstFrame.png",
13525: "$topdir/media/player.swf",
13526: "$topdir/media/swfobject.js",
13527: "$topdir/media/expressInstall.swf");
13528: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13529: "$topdir/$topdir.mp4",
13530: "$topdir/$topdir\_config.xml",
13531: "$topdir/$topdir\_controller.swf",
13532: "$topdir/$topdir\_embed.css",
13533: "$topdir/$topdir\_First_Frame.png",
13534: "$topdir/$topdir\_player.html",
13535: "$topdir/$topdir\_Thumbnails.png",
13536: "$topdir/playerProductInstall.swf",
13537: "$topdir/scripts/",
13538: "$topdir/scripts/config_xml.js",
13539: "$topdir/scripts/handlebars.js",
13540: "$topdir/scripts/jquery-1.7.1.min.js",
13541: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13542: "$topdir/scripts/modernizr.js",
13543: "$topdir/scripts/player-min.js",
13544: "$topdir/scripts/swfobject.js",
13545: "$topdir/skins/",
13546: "$topdir/skins/configuration_express.xml",
13547: "$topdir/skins/express_show/",
13548: "$topdir/skins/express_show/player-min.css",
13549: "$topdir/skins/express_show/spritesheet.png");
13550: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13551: "$topdir/$topdir.mp4",
13552: "$topdir/$topdir\_config.xml",
13553: "$topdir/$topdir\_controller.swf",
13554: "$topdir/$topdir\_embed.css",
13555: "$topdir/$topdir\_First_Frame.png",
13556: "$topdir/$topdir\_player.html",
13557: "$topdir/$topdir\_Thumbnails.png",
13558: "$topdir/playerProductInstall.swf",
13559: "$topdir/scripts/",
13560: "$topdir/scripts/config_xml.js",
13561: "$topdir/scripts/techsmith-smart-player.min.js",
13562: "$topdir/skins/",
13563: "$topdir/skins/configuration_express.xml",
13564: "$topdir/skins/express_show/",
13565: "$topdir/skins/express_show/spritesheet.min.css",
13566: "$topdir/skins/express_show/spritesheet.png",
13567: "$topdir/skins/express_show/techsmith-smart-player.min.css");
13568: my @diffs = &compare_arrays(\@paths,\@camtasia6);
13569: if (@diffs == 0) {
13570: $is_camtasia = 6;
13571: } else {
13572: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13573: if (@diffs == 0) {
13574: $is_camtasia = 8;
13575: } else {
13576: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13577: if (@diffs == 0) {
13578: $is_camtasia = 8;
13579: }
13580: }
13581: }
13582: }
13583: my $output;
13584: if ($is_camtasia) {
13585: $output = <<"ENDCAM";
13586: <script type="text/javascript" language="Javascript">
13587: // <![CDATA[
13588:
13589: function camtasiaToggle() {
13590: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13591: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13592: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13593: document.getElementById('camtasia_titles').style.display='block';
13594: } else {
13595: document.getElementById('camtasia_titles').style.display='none';
13596: }
13597: }
13598: }
13599: return;
13600: }
13601:
13602: // ]]>
13603: </script>
13604: <p>$lt{'camt'}</p>
13605: ENDCAM
13606: } else {
13607: $output = '<p>'.$lt{'this'};
13608: if ($info eq '') {
13609: $output .= ' '.$lt{'youm'}.'</p>'."\n";
13610: } else {
13611: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13612: '<div><pre>'.$info.'</pre></div>';
13613: }
13614: }
13615: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13616: my $duplicates;
13617: my $num = 0;
13618: if (ref($dirlist) eq 'ARRAY') {
13619: foreach my $item (@{$dirlist}) {
13620: if (ref($item) eq 'ARRAY') {
13621: if (exists($toplevel{$item->[0]})) {
13622: $duplicates .=
13623: &start_data_table_row().
13624: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13625: 'value="0" checked="checked" />'.&mt('No').'</label>'.
13626: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
13627: 'value="1" />'.&mt('Yes').'</label>'.
13628: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13629: '<td>'.$item->[0].'</td>';
13630: if ($item->[2]) {
13631: $duplicates .= '<td>'.&mt('Directory').'</td>';
13632: } else {
13633: $duplicates .= '<td>'.&mt('File').'</td>';
13634: }
13635: $duplicates .= '<td>'.$item->[3].'</td>'.
13636: '<td>'.
13637: &Apache::lonlocal::locallocaltime($item->[4]).
13638: '</td>'.
13639: &end_data_table_row();
13640: $num ++;
13641: }
13642: }
13643: }
13644: }
13645: my $itemcount;
13646: if (@paths > 0) {
13647: $itemcount = scalar(@paths);
13648: } else {
13649: $itemcount = 1;
13650: }
13651: if ($is_camtasia) {
13652: $output .= $lt{'auto'}.'<br />'.
13653: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13654: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13655: $lt{'yes'}.'</label> <label>'.
13656: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13657: $lt{'no'}.'</label></span><br />'.
13658: '<div id="camtasia_titles" style="display:block">'.
13659: &Apache::lonhtmlcommon::start_pick_box().
13660: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13661: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13662: &Apache::lonhtmlcommon::row_closure().
13663: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13664: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13665: &Apache::lonhtmlcommon::row_closure(1).
13666: &Apache::lonhtmlcommon::end_pick_box().
13667: '</div>';
13668: }
13669: $output .=
13670: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13671: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13672: "\n";
13673: if ($duplicates ne '') {
13674: $output .= '<p><span class="LC_warning">'.
13675: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
13676: &start_data_table().
13677: &start_data_table_header_row().
13678: '<th>'.&mt('Overwrite?').'</th>'.
13679: '<th>'.&mt('Name').'</th>'.
13680: '<th>'.&mt('Type').'</th>'.
13681: '<th>'.&mt('Size').'</th>'.
13682: '<th>'.&mt('Last modified').'</th>'.
13683: &end_data_table_header_row().
13684: $duplicates.
13685: &end_data_table().
13686: '</p>';
13687: }
13688: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13689: if (ref($hiddenelements) eq 'HASH') {
13690: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13691: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13692: }
13693: }
13694: $output .= <<"END";
13695: <br />
13696: <input type="submit" name="decompress" value="$lt{'extr'}" />
13697: </form>
13698: $noextract
13699: END
13700: return $output;
13701: }
13702:
13703: sub decompression_utility {
13704: my ($program) = @_;
13705: my @utilities = ('tar','gunzip','bunzip2','unzip');
13706: my $location;
13707: if (grep(/^\Q$program\E$/,@utilities)) {
13708: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13709: '/usr/sbin/') {
13710: if (-x $dir.$program) {
13711: $location = $dir.$program;
13712: last;
13713: }
13714: }
13715: }
13716: return $location;
13717: }
13718:
13719: sub list_archive_contents {
13720: my ($file,$pathsref) = @_;
13721: my (@cmd,$output);
13722: my $needsregexp;
13723: if ($file =~ /\.zip$/) {
13724: @cmd = (&decompression_utility('unzip'),"-l");
13725: $needsregexp = 1;
13726: } elsif (($file =~ m/\.tar\.gz$/) ||
13727: ($file =~ /\.tgz$/)) {
13728: @cmd = (&decompression_utility('tar'),"-ztf");
13729: } elsif ($file =~ /\.tar\.bz2$/) {
13730: @cmd = (&decompression_utility('tar'),"-jtf");
13731: } elsif ($file =~ m|\.tar$|) {
13732: @cmd = (&decompression_utility('tar'),"-tf");
13733: }
13734: if (@cmd) {
13735: undef($!);
13736: undef($@);
13737: if (open(my $fh,"-|", @cmd, $file)) {
13738: while (my $line = <$fh>) {
13739: $output .= $line;
13740: chomp($line);
13741: my $item;
13742: if ($needsregexp) {
13743: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
13744: } else {
13745: $item = $line;
13746: }
13747: if ($item ne '') {
13748: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13749: push(@{$pathsref},$item);
13750: }
13751: }
13752: }
13753: close($fh);
13754: }
13755: }
13756: return $output;
13757: }
13758:
13759: sub decompress_uploaded_file {
13760: my ($file,$dir) = @_;
13761: &Apache::lonnet::appenv({'cgi.file' => $file});
13762: &Apache::lonnet::appenv({'cgi.dir' => $dir});
13763: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13764: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13765: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13766: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13767: my $decompressed = $env{'cgi.decompressed'};
13768: &Apache::lonnet::delenv('cgi.file');
13769: &Apache::lonnet::delenv('cgi.dir');
13770: &Apache::lonnet::delenv('cgi.decompressed');
13771: return ($decompressed,$result);
13772: }
13773:
13774: sub process_decompression {
13775: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13776: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13777: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13778: &mt('Unexpected file path.').'</p>'."\n";
13779: }
13780: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13781: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13782: &mt('Unexpected course context.').'</p>'."\n";
13783: }
13784: unless ($file eq &Apache::lonnet::clean_filename($file)) {
13785: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13786: &mt('Filename contained unexpected characters.').'</p>'."\n";
13787: }
13788: my ($dir,$error,$warning,$output);
13789: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13790: $error = &mt('Filename not a supported archive file type.').
13791: '<br />'.&mt('Filename should end with one of: [_1].',
13792: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13793: } else {
13794: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13795: if ($docuhome eq 'no_host') {
13796: $error = &mt('Could not determine home server for course.');
13797: } else {
13798: my @ids=&Apache::lonnet::current_machine_ids();
13799: my $currdir = "$dir_root/$destination";
13800: if (grep(/^\Q$docuhome\E$/,@ids)) {
13801: $dir = &LONCAPA::propath($docudom,$docuname).
13802: "$dir_root/$destination";
13803: } else {
13804: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13805: "$dir_root/$docudom/$docuname/$destination";
13806: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13807: $error = &mt('Archive file not found.');
13808: }
13809: }
13810: my (@to_overwrite,@to_skip);
13811: if ($env{'form.archive_overwrite_total'} > 0) {
13812: my $total = $env{'form.archive_overwrite_total'};
13813: for (my $i=0; $i<$total; $i++) {
13814: if ($env{'form.archive_overwrite_'.$i} == 1) {
13815: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13816: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13817: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13818: }
13819: }
13820: }
13821: my $numskip = scalar(@to_skip);
13822: my $numoverwrite = scalar(@to_overwrite);
13823: if (($numskip) && (!$numoverwrite)) {
13824: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
13825: } elsif ($dir eq '') {
13826: $error = &mt('Directory containing archive file unavailable.');
13827: } elsif (!$error) {
13828: my ($decompressed,$display);
13829: if (($numskip) || ($numoverwrite)) {
13830: my $tempdir = time.'_'.$$.int(rand(10000));
13831: mkdir("$dir/$tempdir",0755);
13832: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13833: ($decompressed,$display) =
13834: &decompress_uploaded_file($file,"$dir/$tempdir");
13835: foreach my $item (@to_skip) {
13836: if (($item ne '') && ($item !~ /\.\./)) {
13837: if (-f "$dir/$tempdir/$item") {
13838: unlink("$dir/$tempdir/$item");
13839: } elsif (-d "$dir/$tempdir/$item") {
13840: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13841: }
13842: }
13843: }
13844: foreach my $item (@to_overwrite) {
13845: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13846: if (($item ne '') && ($item !~ /\.\./)) {
13847: if (-f "$dir/$item") {
13848: unlink("$dir/$item");
13849: } elsif (-d "$dir/$item") {
13850: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13851: }
13852: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13853: }
13854: }
13855: }
13856: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13857: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13858: }
13859: }
13860: } else {
13861: ($decompressed,$display) =
13862: &decompress_uploaded_file($file,$dir);
13863: }
13864: if ($decompressed eq 'ok') {
13865: $output = '<p class="LC_info">'.
13866: &mt('Files extracted successfully from archive.').
13867: '</p>'."\n";
13868: my ($warning,$result,@contents);
13869: my ($newdirlistref,$newlisterror) =
13870: &Apache::lonnet::dirlist($currdir,$docudom,
13871: $docuname,1);
13872: my (%is_dir,%changes,@newitems);
13873: my $dirptr = 16384;
13874: if (ref($newdirlistref) eq 'ARRAY') {
13875: foreach my $dir_line (@{$newdirlistref}) {
13876: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13877: unless (($item =~ /^\.+$/) || ($item eq $file)) {
13878: push(@newitems,$item);
13879: if ($dirptr&$testdir) {
13880: $is_dir{$item} = 1;
13881: }
13882: $changes{$item} = 1;
13883: }
13884: }
13885: }
13886: if (keys(%changes) > 0) {
13887: foreach my $item (sort(@newitems)) {
13888: if ($changes{$item}) {
13889: push(@contents,$item);
13890: }
13891: }
13892: }
13893: if (@contents > 0) {
13894: my $wantform;
13895: unless ($env{'form.autoextract_camtasia'}) {
13896: $wantform = 1;
13897: }
13898: my (%children,%parent,%dirorder,%titles);
13899: my ($count,$datatable) = &get_extracted($docudom,$docuname,
13900: $currdir,\%is_dir,
13901: \%children,\%parent,
13902: \@contents,\%dirorder,
13903: \%titles,$wantform);
13904: if ($datatable ne '') {
13905: $output .= &archive_options_form('decompressed',$datatable,
13906: $count,$hiddenelem);
13907: my $startcount = 6;
13908: $output .= &archive_javascript($startcount,$count,
13909: \%titles,\%children);
13910: }
13911: if ($env{'form.autoextract_camtasia'}) {
13912: my $version = $env{'form.autoextract_camtasia'};
13913: my %displayed;
13914: my $total = 1;
13915: $env{'form.archive_directory'} = [];
13916: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13917: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13918: $path =~ s{/$}{};
13919: my $item;
13920: if ($path ne '') {
13921: $item = "$path/$titles{$i}";
13922: } else {
13923: $item = $titles{$i};
13924: }
13925: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13926: if ($item eq $contents[0]) {
13927: push(@{$env{'form.archive_directory'}},$i);
13928: $env{'form.archive_'.$i} = 'display';
13929: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13930: $displayed{'folder'} = $i;
13931: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13932: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13933: $env{'form.archive_'.$i} = 'display';
13934: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13935: $displayed{'web'} = $i;
13936: } else {
13937: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13938: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13939: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13940: push(@{$env{'form.archive_directory'}},$i);
13941: }
13942: $env{'form.archive_'.$i} = 'dependency';
13943: }
13944: $total ++;
13945: }
13946: for (my $i=1; $i<$total; $i++) {
13947: next if ($i == $displayed{'web'});
13948: next if ($i == $displayed{'folder'});
13949: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13950: }
13951: $env{'form.phase'} = 'decompress_cleanup';
13952: $env{'form.archivedelete'} = 1;
13953: $env{'form.archive_count'} = $total-1;
13954: $output .=
13955: &process_extracted_files('coursedocs',$docudom,
13956: $docuname,$destination,
13957: $dir_root,$hiddenelem);
13958: }
13959: } else {
13960: $warning = &mt('No new items extracted from archive file.');
13961: }
13962: } else {
13963: $output = $display;
13964: $error = &mt('An error occurred during extraction from the archive file.');
13965: }
13966: }
13967: }
13968: }
13969: if ($error) {
13970: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13971: $error.'</p>'."\n";
13972: }
13973: if ($warning) {
13974: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13975: }
13976: return $output;
13977: }
13978:
13979: sub get_extracted {
13980: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13981: $titles,$wantform) = @_;
13982: my $count = 0;
13983: my $depth = 0;
13984: my $datatable;
13985: my @hierarchy;
13986: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13987: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13988: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13989: foreach my $item (@{$contents}) {
13990: $count ++;
13991: @{$dirorder->{$count}} = @hierarchy;
13992: $titles->{$count} = $item;
13993: &archive_hierarchy($depth,$count,$parent,$children);
13994: if ($wantform) {
13995: $datatable .= &archive_row($is_dir->{$item},$item,
13996: $currdir,$depth,$count);
13997: }
13998: if ($is_dir->{$item}) {
13999: $depth ++;
14000: push(@hierarchy,$count);
14001: $parent->{$depth} = $count;
14002: $datatable .=
14003: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14004: \$depth,\$count,\@hierarchy,$dirorder,
14005: $children,$parent,$titles,$wantform);
14006: $depth --;
14007: pop(@hierarchy);
14008: }
14009: }
14010: return ($count,$datatable);
14011: }
14012:
14013: sub recurse_extracted_archive {
14014: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14015: $children,$parent,$titles,$wantform) = @_;
14016: my $result='';
14017: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14018: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14019: (ref($dirorder) eq 'HASH')) {
14020: return $result;
14021: }
14022: my $dirptr = 16384;
14023: my ($newdirlistref,$newlisterror) =
14024: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14025: if (ref($newdirlistref) eq 'ARRAY') {
14026: foreach my $dir_line (@{$newdirlistref}) {
14027: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14028: unless ($item =~ /^\.+$/) {
14029: $$count ++;
14030: @{$dirorder->{$$count}} = @{$hierarchy};
14031: $titles->{$$count} = $item;
14032: &archive_hierarchy($$depth,$$count,$parent,$children);
14033:
14034: my $is_dir;
14035: if ($dirptr&$testdir) {
14036: $is_dir = 1;
14037: }
14038: if ($wantform) {
14039: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14040: }
14041: if ($is_dir) {
14042: $$depth ++;
14043: push(@{$hierarchy},$$count);
14044: $parent->{$$depth} = $$count;
14045: $result .=
14046: &recurse_extracted_archive("$currdir/$item",$docudom,
14047: $docuname,$depth,$count,
14048: $hierarchy,$dirorder,$children,
14049: $parent,$titles,$wantform);
14050: $$depth --;
14051: pop(@{$hierarchy});
14052: }
14053: }
14054: }
14055: }
14056: return $result;
14057: }
14058:
14059: sub archive_hierarchy {
14060: my ($depth,$count,$parent,$children) =@_;
14061: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14062: if (exists($parent->{$depth})) {
14063: $children->{$parent->{$depth}} .= $count.':';
14064: }
14065: }
14066: return;
14067: }
14068:
14069: sub archive_row {
14070: my ($is_dir,$item,$currdir,$depth,$count) = @_;
14071: my ($name) = ($item =~ m{([^/]+)$});
14072: my %choices = &Apache::lonlocal::texthash (
14073: 'display' => 'Add as file',
14074: 'dependency' => 'Include as dependency',
14075: 'discard' => 'Discard',
14076: );
14077: if ($is_dir) {
14078: $choices{'display'} = &mt('Add as folder');
14079: }
14080: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14081: my $offset = 0;
14082: foreach my $action ('display','dependency','discard') {
14083: $offset ++;
14084: if ($action ne 'display') {
14085: $offset ++;
14086: }
14087: $output .= '<td><span class="LC_nobreak">'.
14088: '<label><input type="radio" name="archive_'.$count.
14089: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14090: my $text = $choices{$action};
14091: if ($is_dir) {
14092: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14093: if ($action eq 'display') {
14094: $text = &mt('Add as folder');
14095: }
14096: } else {
14097: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14098:
14099: }
14100: $output .= ' /> '.$choices{$action}.'</label></span>';
14101: if ($action eq 'dependency') {
14102: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14103: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
14104: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14105: '<option value=""></option>'."\n".
14106: '</select>'."\n".
14107: '</div>';
14108: } elsif ($action eq 'display') {
14109: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14110: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14111: '</div>';
14112: }
14113: $output .= '</td>';
14114: }
14115: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14116: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
14117: for (my $i=0; $i<$depth; $i++) {
14118: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14119: }
14120: if ($is_dir) {
14121: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
14122: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14123: } else {
14124: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14125: }
14126: $output .= ' '.$name.'</td>'."\n".
14127: &end_data_table_row();
14128: return $output;
14129: }
14130:
14131: sub archive_options_form {
14132: my ($form,$display,$count,$hiddenelem) = @_;
14133: my %lt = &Apache::lonlocal::texthash(
14134: perm => 'Permanently remove archive file?',
14135: hows => 'How should each extracted item be incorporated in the course?',
14136: cont => 'Content actions for all',
14137: addf => 'Add as folder/file',
14138: incd => 'Include as dependency for a displayed file',
14139: disc => 'Discard',
14140: no => 'No',
14141: yes => 'Yes',
14142: save => 'Save',
14143: );
14144: my $output = <<"END";
14145: <form name="$form" method="post" action="">
14146: <p><span class="LC_nobreak">$lt{'perm'}
14147: <label>
14148: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14149: </label>
14150:
14151: <label>
14152: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14153: </span>
14154: </p>
14155: <input type="hidden" name="phase" value="decompress_cleanup" />
14156: <br />$lt{'hows'}
14157: <div class="LC_columnSection">
14158: <fieldset>
14159: <legend>$lt{'cont'}</legend>
14160: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
14161: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14162: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14163: </fieldset>
14164: </div>
14165: END
14166: return $output.
14167: &start_data_table()."\n".
14168: $display."\n".
14169: &end_data_table()."\n".
14170: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14171: $hiddenelem.
14172: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14173: '</form>';
14174: }
14175:
14176: sub archive_javascript {
14177: my ($startcount,$numitems,$titles,$children) = @_;
14178: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14179: my $maintitle = $env{'form.comment'};
14180: my $scripttag = <<START;
14181: <script type="text/javascript">
14182: // <![CDATA[
14183:
14184: function checkAll(form,prefix) {
14185: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
14186: for (var i=0; i < form.elements.length; i++) {
14187: var id = form.elements[i].id;
14188: if ((id != '') && (id != undefined)) {
14189: if (idstr.test(id)) {
14190: if (form.elements[i].type == 'radio') {
14191: form.elements[i].checked = true;
14192: var nostart = i-$startcount;
14193: var offset = nostart%7;
14194: var count = (nostart-offset)/7;
14195: dependencyCheck(form,count,offset);
14196: }
14197: }
14198: }
14199: }
14200: }
14201:
14202: function propagateCheck(form,count) {
14203: if (count > 0) {
14204: var startelement = $startcount + ((count-1) * 7);
14205: for (var j=1; j<6; j++) {
14206: if ((j != 2) && (j != 4)) {
14207: var item = startelement + j;
14208: if (form.elements[item].type == 'radio') {
14209: if (form.elements[item].checked) {
14210: containerCheck(form,count,j);
14211: break;
14212: }
14213: }
14214: }
14215: }
14216: }
14217: }
14218:
14219: numitems = $numitems
14220: var titles = new Array(numitems);
14221: var parents = new Array(numitems);
14222: for (var i=0; i<numitems; i++) {
14223: parents[i] = new Array;
14224: }
14225: var maintitle = '$maintitle';
14226:
14227: START
14228:
14229: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14230: my @contents = split(/:/,$children->{$container});
14231: for (my $i=0; $i<@contents; $i ++) {
14232: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14233: }
14234: }
14235:
14236: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14237: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14238: }
14239:
14240: $scripttag .= <<END;
14241:
14242: function containerCheck(form,count,offset) {
14243: if (count > 0) {
14244: dependencyCheck(form,count,offset);
14245: var item = (offset+$startcount)+7*(count-1);
14246: form.elements[item].checked = true;
14247: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14248: if (parents[count].length > 0) {
14249: for (var j=0; j<parents[count].length; j++) {
14250: containerCheck(form,parents[count][j],offset);
14251: }
14252: }
14253: }
14254: }
14255: }
14256:
14257: function dependencyCheck(form,count,offset) {
14258: if (count > 0) {
14259: var chosen = (offset+$startcount)+7*(count-1);
14260: var depitem = $startcount + ((count-1) * 7) + 4;
14261: var currtype = form.elements[depitem].type;
14262: if (form.elements[chosen].value == 'dependency') {
14263: document.getElementById('arc_depon_'+count).style.display='block';
14264: form.elements[depitem].options.length = 0;
14265: form.elements[depitem].options[0] = new Option('Select','',true,true);
14266: for (var i=1; i<=numitems; i++) {
14267: if (i == count) {
14268: continue;
14269: }
14270: var startelement = $startcount + (i-1) * 7;
14271: for (var j=1; j<6; j++) {
14272: if ((j != 2) && (j!= 4)) {
14273: var item = startelement + j;
14274: if (form.elements[item].type == 'radio') {
14275: if (form.elements[item].checked) {
14276: if (form.elements[item].value == 'display') {
14277: var n = form.elements[depitem].options.length;
14278: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14279: }
14280: }
14281: }
14282: }
14283: }
14284: }
14285: } else {
14286: document.getElementById('arc_depon_'+count).style.display='none';
14287: form.elements[depitem].options.length = 0;
14288: form.elements[depitem].options[0] = new Option('Select','',true,true);
14289: }
14290: titleCheck(form,count,offset);
14291: }
14292: }
14293:
14294: function propagateSelect(form,count,offset) {
14295: if (count > 0) {
14296: var item = (1+offset+$startcount)+7*(count-1);
14297: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
14298: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14299: if (parents[count].length > 0) {
14300: for (var j=0; j<parents[count].length; j++) {
14301: containerSelect(form,parents[count][j],offset,picked);
14302: }
14303: }
14304: }
14305: }
14306: }
14307:
14308: function containerSelect(form,count,offset,picked) {
14309: if (count > 0) {
14310: var item = (offset+$startcount)+7*(count-1);
14311: if (form.elements[item].type == 'radio') {
14312: if (form.elements[item].value == 'dependency') {
14313: if (form.elements[item+1].type == 'select-one') {
14314: for (var i=0; i<form.elements[item+1].options.length; i++) {
14315: if (form.elements[item+1].options[i].value == picked) {
14316: form.elements[item+1].selectedIndex = i;
14317: break;
14318: }
14319: }
14320: }
14321: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14322: if (parents[count].length > 0) {
14323: for (var j=0; j<parents[count].length; j++) {
14324: containerSelect(form,parents[count][j],offset,picked);
14325: }
14326: }
14327: }
14328: }
14329: }
14330: }
14331: }
14332:
14333: function titleCheck(form,count,offset) {
14334: if (count > 0) {
14335: var chosen = (offset+$startcount)+7*(count-1);
14336: var depitem = $startcount + ((count-1) * 7) + 2;
14337: var currtype = form.elements[depitem].type;
14338: if (form.elements[chosen].value == 'display') {
14339: document.getElementById('arc_title_'+count).style.display='block';
14340: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14341: document.getElementById('archive_title_'+count).value=maintitle;
14342: }
14343: } else {
14344: document.getElementById('arc_title_'+count).style.display='none';
14345: if (currtype == 'text') {
14346: document.getElementById('archive_title_'+count).value='';
14347: }
14348: }
14349: }
14350: return;
14351: }
14352:
14353: // ]]>
14354: </script>
14355: END
14356: return $scripttag;
14357: }
14358:
14359: sub process_extracted_files {
14360: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14361: my $numitems = $env{'form.archive_count'};
14362: return if ((!$numitems) || ($numitems =~ /\D/));
14363: my @ids=&Apache::lonnet::current_machine_ids();
14364: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14365: %folders,%containers,%mapinner,%prompttofetch);
14366: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14367: if (grep(/^\Q$docuhome\E$/,@ids)) {
14368: $prefix = &LONCAPA::propath($docudom,$docuname);
14369: $pathtocheck = "$dir_root/$destination";
14370: $dir = $dir_root;
14371: $ishome = 1;
14372: } else {
14373: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14374: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14375: $dir = "$dir_root/$docudom/$docuname";
14376: }
14377: my $currdir = "$dir_root/$destination";
14378: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14379: if ($env{'form.folderpath'}) {
14380: my @items = split('&',$env{'form.folderpath'});
14381: $folders{'0'} = $items[-2];
14382: if ($env{'form.folderpath'} =~ /\:1$/) {
14383: $containers{'0'}='page';
14384: } else {
14385: $containers{'0'}='sequence';
14386: }
14387: }
14388: my @archdirs = &get_env_multiple('form.archive_directory');
14389: if ($numitems) {
14390: for (my $i=1; $i<=$numitems; $i++) {
14391: my $path = $env{'form.archive_content_'.$i};
14392: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14393: my $item = $1;
14394: $toplevelitems{$item} = $i;
14395: if (grep(/^\Q$i\E$/,@archdirs)) {
14396: $is_dir{$item} = 1;
14397: }
14398: }
14399: }
14400: }
14401: my ($output,%children,%parent,%titles,%dirorder,$result);
14402: if (keys(%toplevelitems) > 0) {
14403: my @contents = sort(keys(%toplevelitems));
14404: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14405: \%parent,\@contents,\%dirorder,\%titles);
14406: }
14407: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14408: if ($numitems) {
14409: for (my $i=1; $i<=$numitems; $i++) {
14410: next if ($env{'form.archive_'.$i} eq 'dependency');
14411: my $path = $env{'form.archive_content_'.$i};
14412: if ($path =~ /^\Q$pathtocheck\E/) {
14413: if ($env{'form.archive_'.$i} eq 'discard') {
14414: if ($prefix ne '' && $path ne '') {
14415: if (-e $prefix.$path) {
14416: if ((@archdirs > 0) &&
14417: (grep(/^\Q$i\E$/,@archdirs))) {
14418: $todeletedir{$prefix.$path} = 1;
14419: } else {
14420: $todelete{$prefix.$path} = 1;
14421: }
14422: }
14423: }
14424: } elsif ($env{'form.archive_'.$i} eq 'display') {
14425: my ($docstitle,$title,$url,$outer);
14426: ($title) = ($path =~ m{/([^/]+)$});
14427: $docstitle = $env{'form.archive_title_'.$i};
14428: if ($docstitle eq '') {
14429: $docstitle = $title;
14430: }
14431: $outer = 0;
14432: if (ref($dirorder{$i}) eq 'ARRAY') {
14433: if (@{$dirorder{$i}} > 0) {
14434: foreach my $item (reverse(@{$dirorder{$i}})) {
14435: if ($env{'form.archive_'.$item} eq 'display') {
14436: $outer = $item;
14437: last;
14438: }
14439: }
14440: }
14441: }
14442: my ($errtext,$fatal) =
14443: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14444: '/'.$folders{$outer}.'.'.
14445: $containers{$outer});
14446: next if ($fatal);
14447: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14448: if ($context eq 'coursedocs') {
14449: $mapinner{$i} = time;
14450: $folders{$i} = 'default_'.$mapinner{$i};
14451: $containers{$i} = 'sequence';
14452: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14453: $folders{$i}.'.'.$containers{$i};
14454: my $newidx = &LONCAPA::map::getresidx();
14455: $LONCAPA::map::resources[$newidx]=
14456: $docstitle.':'.$url.':false:normal:res';
14457: push(@LONCAPA::map::order,$newidx);
14458: my ($outtext,$errtext) =
14459: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14460: $docuname.'/'.$folders{$outer}.
14461: '.'.$containers{$outer},1,1);
14462: $newseqid{$i} = $newidx;
14463: unless ($errtext) {
14464: $result .= '<li>'.&mt('Folder: [_1] added to course',
14465: &HTML::Entities::encode($docstitle,'<>&"')).
14466: '</li>'."\n";
14467: }
14468: }
14469: } else {
14470: if ($context eq 'coursedocs') {
14471: my $newidx=&LONCAPA::map::getresidx();
14472: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14473: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14474: $title;
14475: if (($outer !~ /\D/) &&
14476: (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14477: ($newidx !~ /\D/)) {
14478: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14479: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14480: }
14481: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14482: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14483: }
14484: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14485: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14486: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14487: unless ($ishome) {
14488: my $fetch = "$newdest{$i}/$title";
14489: $fetch =~ s/^\Q$prefix$dir\E//;
14490: $prompttofetch{$fetch} = 1;
14491: }
14492: }
14493: }
14494: $LONCAPA::map::resources[$newidx]=
14495: $docstitle.':'.$url.':false:normal:res';
14496: push(@LONCAPA::map::order, $newidx);
14497: my ($outtext,$errtext)=
14498: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14499: $docuname.'/'.$folders{$outer}.
14500: '.'.$containers{$outer},1,1);
14501: unless ($errtext) {
14502: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14503: $result .= '<li>'.&mt('File: [_1] added to course',
14504: &HTML::Entities::encode($docstitle,'<>&"')).
14505: '</li>'."\n";
14506: }
14507: }
14508: } else {
14509: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14510: &HTML::Entities::encode($path,'<>&"')).'<br />';
14511: }
14512: }
14513: }
14514: }
14515: } else {
14516: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14517: &HTML::Entities::encode($path,'<>&"')).'<br />';
14518: }
14519: }
14520: for (my $i=1; $i<=$numitems; $i++) {
14521: next unless ($env{'form.archive_'.$i} eq 'dependency');
14522: my $path = $env{'form.archive_content_'.$i};
14523: if ($path =~ /^\Q$pathtocheck\E/) {
14524: my ($title) = ($path =~ m{/([^/]+)$});
14525: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14526: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14527: if (ref($dirorder{$i}) eq 'ARRAY') {
14528: my ($itemidx,$fullpath,$relpath);
14529: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14530: my $container = $dirorder{$referrer{$i}}->[-1];
14531: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14532: if ($dirorder{$i}->[$j] eq $container) {
14533: $itemidx = $j;
14534: }
14535: }
14536: }
14537: if ($itemidx eq '') {
14538: $itemidx = 0;
14539: }
14540: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14541: if ($mapinner{$referrer{$i}}) {
14542: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14543: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14544: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14545: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14546: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14547: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14548: if (!-e $fullpath) {
14549: mkdir($fullpath,0755);
14550: }
14551: }
14552: } else {
14553: last;
14554: }
14555: }
14556: }
14557: } elsif ($newdest{$referrer{$i}}) {
14558: $fullpath = $newdest{$referrer{$i}};
14559: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14560: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14561: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14562: last;
14563: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14564: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14565: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14566: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14567: if (!-e $fullpath) {
14568: mkdir($fullpath,0755);
14569: }
14570: }
14571: } else {
14572: last;
14573: }
14574: }
14575: }
14576: if ($fullpath ne '') {
14577: if (-e "$prefix$path") {
14578: unless (rename("$prefix$path","$fullpath/$title")) {
14579: $warning .= &mt('Failed to rename dependency').'<br />';
14580: }
14581: }
14582: if (-e "$fullpath/$title") {
14583: my $showpath;
14584: if ($relpath ne '') {
14585: $showpath = "$relpath/$title";
14586: } else {
14587: $showpath = "/$title";
14588: }
14589: $result .= '<li>'.&mt('[_1] included as a dependency',
14590: &HTML::Entities::encode($showpath,'<>&"')).
14591: '</li>'."\n";
14592: unless ($ishome) {
14593: my $fetch = "$fullpath/$title";
14594: $fetch =~ s/^\Q$prefix$dir\E//;
14595: $prompttofetch{$fetch} = 1;
14596: }
14597: }
14598: }
14599: }
14600: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14601: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14602: &HTML::Entities::encode($path,'<>&"'),
14603: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14604: '<br />';
14605: }
14606: } else {
14607: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14608: &HTML::Entities::encode($path)).'<br />';
14609: }
14610: }
14611: if (keys(%todelete)) {
14612: foreach my $key (keys(%todelete)) {
14613: unlink($key);
14614: }
14615: }
14616: if (keys(%todeletedir)) {
14617: foreach my $key (keys(%todeletedir)) {
14618: rmdir($key);
14619: }
14620: }
14621: foreach my $dir (sort(keys(%is_dir))) {
14622: if (($pathtocheck ne '') && ($dir ne '')) {
14623: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14624: }
14625: }
14626: if ($result ne '') {
14627: $output .= '<ul>'."\n".
14628: $result."\n".
14629: '</ul>';
14630: }
14631: unless ($ishome) {
14632: my $replicationfail;
14633: foreach my $item (keys(%prompttofetch)) {
14634: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14635: unless ($fetchresult eq 'ok') {
14636: $replicationfail .= '<li>'.$item.'</li>'."\n";
14637: }
14638: }
14639: if ($replicationfail) {
14640: $output .= '<p class="LC_error">'.
14641: &mt('Course home server failed to retrieve:').'<ul>'.
14642: $replicationfail.
14643: '</ul></p>';
14644: }
14645: }
14646: } else {
14647: $warning = &mt('No items found in archive.');
14648: }
14649: if ($error) {
14650: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14651: $error.'</p>'."\n";
14652: }
14653: if ($warning) {
14654: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14655: }
14656: return $output;
14657: }
14658:
14659: sub cleanup_empty_dirs {
14660: my ($path) = @_;
14661: if (($path ne '') && (-d $path)) {
14662: if (opendir(my $dirh,$path)) {
14663: my @dircontents = grep(!/^\./,readdir($dirh));
14664: my $numitems = 0;
14665: foreach my $item (@dircontents) {
14666: if (-d "$path/$item") {
14667: &cleanup_empty_dirs("$path/$item");
14668: if (-e "$path/$item") {
14669: $numitems ++;
14670: }
14671: } else {
14672: $numitems ++;
14673: }
14674: }
14675: if ($numitems == 0) {
14676: rmdir($path);
14677: }
14678: closedir($dirh);
14679: }
14680: }
14681: return;
14682: }
14683:
14684: =pod
14685:
14686: =item * &get_folder_hierarchy()
14687:
14688: Provides hierarchy of names of folders/sub-folders containing the current
14689: item,
14690:
14691: Inputs: 3
14692: - $navmap - navmaps object
14693:
14694: - $map - url for map (either the trigger itself, or map containing
14695: the resource, which is the trigger).
14696:
14697: - $showitem - 1 => show title for map itself; 0 => do not show.
14698:
14699: Outputs: 1 @pathitems - array of folder/subfolder names.
14700:
14701: =cut
14702:
14703: sub get_folder_hierarchy {
14704: my ($navmap,$map,$showitem) = @_;
14705: my @pathitems;
14706: if (ref($navmap)) {
14707: my $mapres = $navmap->getResourceByUrl($map);
14708: if (ref($mapres)) {
14709: my $pcslist = $mapres->map_hierarchy();
14710: if ($pcslist ne '') {
14711: my @pcs = split(/,/,$pcslist);
14712: foreach my $pc (@pcs) {
14713: if ($pc == 1) {
14714: push(@pathitems,&mt('Main Content'));
14715: } else {
14716: my $res = $navmap->getByMapPc($pc);
14717: if (ref($res)) {
14718: my $title = $res->compTitle();
14719: $title =~ s/\W+/_/g;
14720: if ($title ne '') {
14721: push(@pathitems,$title);
14722: }
14723: }
14724: }
14725: }
14726: }
14727: if ($showitem) {
14728: if ($mapres->{ID} eq '0.0') {
14729: push(@pathitems,&mt('Main Content'));
14730: } else {
14731: my $maptitle = $mapres->compTitle();
14732: $maptitle =~ s/\W+/_/g;
14733: if ($maptitle ne '') {
14734: push(@pathitems,$maptitle);
14735: }
14736: }
14737: }
14738: }
14739: }
14740: return @pathitems;
14741: }
14742:
14743: =pod
14744:
14745: =item * &get_turnedin_filepath()
14746:
14747: Determines path in a user's portfolio file for storage of files uploaded
14748: to a specific essayresponse or dropbox item.
14749:
14750: Inputs: 3 required + 1 optional.
14751: $symb is symb for resource, $uname and $udom are for current user (required).
14752: $caller is optional (can be "submission", if routine is called when storing
14753: an upoaded file when "Submit Answer" button was pressed).
14754:
14755: Returns array containing $path and $multiresp.
14756: $path is path in portfolio. $multiresp is 1 if this resource contains more
14757: than one file upload item. Callers of routine should append partid as a
14758: subdirectory to $path in cases where $multiresp is 1.
14759:
14760: Called by: homework/essayresponse.pm and homework/structuretags.pm
14761:
14762: =cut
14763:
14764: sub get_turnedin_filepath {
14765: my ($symb,$uname,$udom,$caller) = @_;
14766: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14767: my $turnindir;
14768: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14769: $turnindir = $userhash{'turnindir'};
14770: my ($path,$multiresp);
14771: if ($turnindir eq '') {
14772: if ($caller eq 'submission') {
14773: $turnindir = &mt('turned in');
14774: $turnindir =~ s/\W+/_/g;
14775: my %newhash = (
14776: 'turnindir' => $turnindir,
14777: );
14778: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14779: }
14780: }
14781: if ($turnindir ne '') {
14782: $path = '/'.$turnindir.'/';
14783: my ($multipart,$turnin,@pathitems);
14784: my $navmap = Apache::lonnavmaps::navmap->new();
14785: if (defined($navmap)) {
14786: my $mapres = $navmap->getResourceByUrl($map);
14787: if (ref($mapres)) {
14788: my $pcslist = $mapres->map_hierarchy();
14789: if ($pcslist ne '') {
14790: foreach my $pc (split(/,/,$pcslist)) {
14791: my $res = $navmap->getByMapPc($pc);
14792: if (ref($res)) {
14793: my $title = $res->compTitle();
14794: $title =~ s/\W+/_/g;
14795: if ($title ne '') {
14796: if (($pc > 1) && (length($title) > 12)) {
14797: $title = substr($title,0,12);
14798: }
14799: push(@pathitems,$title);
14800: }
14801: }
14802: }
14803: }
14804: my $maptitle = $mapres->compTitle();
14805: $maptitle =~ s/\W+/_/g;
14806: if ($maptitle ne '') {
14807: if (length($maptitle) > 12) {
14808: $maptitle = substr($maptitle,0,12);
14809: }
14810: push(@pathitems,$maptitle);
14811: }
14812: unless ($env{'request.state'} eq 'construct') {
14813: my $res = $navmap->getBySymb($symb);
14814: if (ref($res)) {
14815: my $partlist = $res->parts();
14816: my $totaluploads = 0;
14817: if (ref($partlist) eq 'ARRAY') {
14818: foreach my $part (@{$partlist}) {
14819: my @types = $res->responseType($part);
14820: my @ids = $res->responseIds($part);
14821: for (my $i=0; $i < scalar(@ids); $i++) {
14822: if ($types[$i] eq 'essay') {
14823: my $partid = $part.'_'.$ids[$i];
14824: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14825: $totaluploads ++;
14826: }
14827: }
14828: }
14829: }
14830: if ($totaluploads > 1) {
14831: $multiresp = 1;
14832: }
14833: }
14834: }
14835: }
14836: } else {
14837: return;
14838: }
14839: } else {
14840: return;
14841: }
14842: my $restitle=&Apache::lonnet::gettitle($symb);
14843: $restitle =~ s/\W+/_/g;
14844: if ($restitle eq '') {
14845: $restitle = ($resurl =~ m{/[^/]+$});
14846: if ($restitle eq '') {
14847: $restitle = time;
14848: }
14849: }
14850: if (length($restitle) > 12) {
14851: $restitle = substr($restitle,0,12);
14852: }
14853: push(@pathitems,$restitle);
14854: $path .= join('/',@pathitems);
14855: }
14856: return ($path,$multiresp);
14857: }
14858:
14859: =pod
14860:
14861: =back
14862:
14863: =head1 CSV Upload/Handling functions
14864:
14865: =over 4
14866:
14867: =item * &upfile_store($r)
14868:
14869: Store uploaded file, $r should be the HTTP Request object,
14870: needs $env{'form.upfile'}
14871: returns $datatoken to be put into hidden field
14872:
14873: =cut
14874:
14875: sub upfile_store {
14876: my $r=shift;
14877: $env{'form.upfile'}=~s/\r/\n/gs;
14878: $env{'form.upfile'}=~s/\f/\n/gs;
14879: $env{'form.upfile'}=~s/\n+/\n/gs;
14880: $env{'form.upfile'}=~s/\n+$//gs;
14881:
14882: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14883: '_enroll_'.$env{'request.course.id'}.'_'.
14884: time.'_'.$$);
14885: return if ($datatoken eq '');
14886:
14887: {
14888: my $datafile = $r->dir_config('lonDaemons').
14889: '/tmp/'.$datatoken.'.tmp';
14890: if ( open(my $fh,'>',$datafile) ) {
14891: print $fh $env{'form.upfile'};
14892: close($fh);
14893: }
14894: }
14895: return $datatoken;
14896: }
14897:
14898: =pod
14899:
14900: =item * &load_tmp_file($r,$datatoken)
14901:
14902: Load uploaded file from tmp, $r should be the HTTP Request object,
14903: $datatoken is the name to assign to the temporary file.
14904: sets $env{'form.upfile'} to the contents of the file
14905:
14906: =cut
14907:
14908: sub load_tmp_file {
14909: my ($r,$datatoken) = @_;
14910: return if ($datatoken eq '');
14911: my @studentdata=();
14912: {
14913: my $studentfile = $r->dir_config('lonDaemons').
14914: '/tmp/'.$datatoken.'.tmp';
14915: if ( open(my $fh,'<',$studentfile) ) {
14916: @studentdata=<$fh>;
14917: close($fh);
14918: }
14919: }
14920: $env{'form.upfile'}=join('',@studentdata);
14921: }
14922:
14923: sub valid_datatoken {
14924: my ($datatoken) = @_;
14925: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14926: return $datatoken;
14927: }
14928: return;
14929: }
14930:
14931: =pod
14932:
14933: =item * &upfile_record_sep()
14934:
14935: Separate uploaded file into records
14936: returns array of records,
14937: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14938:
14939: =cut
14940:
14941: sub upfile_record_sep {
14942: if ($env{'form.upfiletype'} eq 'xml') {
14943: } else {
14944: my @records;
14945: foreach my $line (split(/\n/,$env{'form.upfile'})) {
14946: if ($line=~/^\s*$/) { next; }
14947: push(@records,$line);
14948: }
14949: return @records;
14950: }
14951: }
14952:
14953: =pod
14954:
14955: =item * &record_sep($record)
14956:
14957: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14958:
14959: =cut
14960:
14961: sub takeleft {
14962: my $index=shift;
14963: return substr('0000'.$index,-4,4);
14964: }
14965:
14966: sub record_sep {
14967: my $record=shift;
14968: my %components=();
14969: if ($env{'form.upfiletype'} eq 'xml') {
14970: } elsif ($env{'form.upfiletype'} eq 'space') {
14971: my $i=0;
14972: foreach my $field (split(/\s+/,$record)) {
14973: $field=~s/^(\"|\')//;
14974: $field=~s/(\"|\')$//;
14975: $components{&takeleft($i)}=$field;
14976: $i++;
14977: }
14978: } elsif ($env{'form.upfiletype'} eq 'tab') {
14979: my $i=0;
14980: foreach my $field (split(/\t/,$record)) {
14981: $field=~s/^(\"|\')//;
14982: $field=~s/(\"|\')$//;
14983: $components{&takeleft($i)}=$field;
14984: $i++;
14985: }
14986: } else {
14987: my $separator=',';
14988: if ($env{'form.upfiletype'} eq 'semisv') {
14989: $separator=';';
14990: }
14991: my $i=0;
14992: # the character we are looking for to indicate the end of a quote or a record
14993: my $looking_for=$separator;
14994: # do not add the characters to the fields
14995: my $ignore=0;
14996: # we just encountered a separator (or the beginning of the record)
14997: my $just_found_separator=1;
14998: # store the field we are working on here
14999: my $field='';
15000: # work our way through all characters in record
15001: foreach my $character ($record=~/(.)/g) {
15002: if ($character eq $looking_for) {
15003: if ($character ne $separator) {
15004: # Found the end of a quote, again looking for separator
15005: $looking_for=$separator;
15006: $ignore=1;
15007: } else {
15008: # Found a separator, store away what we got
15009: $components{&takeleft($i)}=$field;
15010: $i++;
15011: $just_found_separator=1;
15012: $ignore=0;
15013: $field='';
15014: }
15015: next;
15016: }
15017: # single or double quotation marks after a separator indicate beginning of a quote
15018: # we are now looking for the end of the quote and need to ignore separators
15019: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
15020: $looking_for=$character;
15021: next;
15022: }
15023: # ignore would be true after we reached the end of a quote
15024: if ($ignore) { next; }
15025: if (($just_found_separator) && ($character=~/\s/)) { next; }
15026: $field.=$character;
15027: $just_found_separator=0;
15028: }
15029: # catch the very last entry, since we never encountered the separator
15030: $components{&takeleft($i)}=$field;
15031: }
15032: return %components;
15033: }
15034:
15035: ######################################################
15036: ######################################################
15037:
15038: =pod
15039:
15040: =item * &upfile_select_html()
15041:
15042: Return HTML code to select a file from the users machine and specify
15043: the file type.
15044:
15045: =cut
15046:
15047: ######################################################
15048: ######################################################
15049: sub upfile_select_html {
15050: my %Types = (
15051: csv => &mt('CSV (comma separated values, spreadsheet)'),
15052: semisv => &mt('Semicolon separated values'),
15053: space => &mt('Space separated'),
15054: tab => &mt('Tabulator separated'),
15055: # xml => &mt('HTML/XML'),
15056: );
15057: my $Str = '<input type="file" name="upfile" size="50" />'.
15058: '<br />'.&mt('Type').': <select name="upfiletype">';
15059: foreach my $type (sort(keys(%Types))) {
15060: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15061: }
15062: $Str .= "</select>\n";
15063: return $Str;
15064: }
15065:
15066: sub get_samples {
15067: my ($records,$toget) = @_;
15068: my @samples=({});
15069: my $got=0;
15070: foreach my $rec (@$records) {
15071: my %temp = &record_sep($rec);
15072: if (! grep(/\S/, values(%temp))) { next; }
15073: if (%temp) {
15074: $samples[$got]=\%temp;
15075: $got++;
15076: if ($got == $toget) { last; }
15077: }
15078: }
15079: return \@samples;
15080: }
15081:
15082: ######################################################
15083: ######################################################
15084:
15085: =pod
15086:
15087: =item * &csv_print_samples($r,$records)
15088:
15089: Prints a table of sample values from each column uploaded $r is an
15090: Apache Request ref, $records is an arrayref from
15091: &Apache::loncommon::upfile_record_sep
15092:
15093: =cut
15094:
15095: ######################################################
15096: ######################################################
15097: sub csv_print_samples {
15098: my ($r,$records) = @_;
15099: my $samples = &get_samples($records,5);
15100:
15101: $r->print(&mt('Samples').'<br />'.&start_data_table().
15102: &start_data_table_header_row());
15103: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15104: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15105: $r->print(&end_data_table_header_row());
15106: foreach my $hash (@$samples) {
15107: $r->print(&start_data_table_row());
15108: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15109: $r->print('<td>');
15110: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15111: $r->print('</td>');
15112: }
15113: $r->print(&end_data_table_row());
15114: }
15115: $r->print(&end_data_table().'<br />'."\n");
15116: }
15117:
15118: ######################################################
15119: ######################################################
15120:
15121: =pod
15122:
15123: =item * &csv_print_select_table($r,$records,$d)
15124:
15125: Prints a table to create associations between values and table columns.
15126:
15127: $r is an Apache Request ref,
15128: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15129: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15130:
15131: =cut
15132:
15133: ######################################################
15134: ######################################################
15135: sub csv_print_select_table {
15136: my ($r,$records,$d) = @_;
15137: my $i=0;
15138: my $samples = &get_samples($records,1);
15139: $r->print(&mt('Associate columns with student attributes.')."\n".
15140: &start_data_table().&start_data_table_header_row().
15141: '<th>'.&mt('Attribute').'</th>'.
15142: '<th>'.&mt('Column').'</th>'.
15143: &end_data_table_header_row()."\n");
15144: foreach my $array_ref (@$d) {
15145: my ($value,$display,$defaultcol)=@{ $array_ref };
15146: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
15147:
15148: $r->print('<td><select name="f'.$i.'"'.
15149: ' onchange="javascript:flip(this.form,'.$i.');">');
15150: $r->print('<option value="none"></option>');
15151: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15152: $r->print('<option value="'.$sample.'"'.
15153: ($sample eq $defaultcol ? ' selected="selected" ' : '').
15154: '>'.&mt('Column [_1]',($sample+1)).'</option>');
15155: }
15156: $r->print('</select></td>'.&end_data_table_row()."\n");
15157: $i++;
15158: }
15159: $r->print(&end_data_table());
15160: $i--;
15161: return $i;
15162: }
15163:
15164: ######################################################
15165: ######################################################
15166:
15167: =pod
15168:
15169: =item * &csv_samples_select_table($r,$records,$d)
15170:
15171: Prints a table of sample values from the upload and can make associate samples to internal names.
15172:
15173: $r is an Apache Request ref,
15174: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15175: $d is an array of 2 element arrays (internal name, displayed name)
15176:
15177: =cut
15178:
15179: ######################################################
15180: ######################################################
15181: sub csv_samples_select_table {
15182: my ($r,$records,$d) = @_;
15183: my $i=0;
15184: #
15185: my $max_samples = 5;
15186: my $samples = &get_samples($records,$max_samples);
15187: $r->print(&start_data_table().
15188: &start_data_table_header_row().'<th>'.
15189: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15190: &end_data_table_header_row());
15191:
15192: foreach my $key (sort(keys(%{ $samples->[0] }))) {
15193: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15194: ' onchange="javascript:flip(this.form,'.$i.');">');
15195: foreach my $option (@$d) {
15196: my ($value,$display,$defaultcol)=@{ $option };
15197: $r->print('<option value="'.$value.'"'.
15198: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15199: $display.'</option>');
15200: }
15201: $r->print('</select></td><td>');
15202: foreach my $line (0..($max_samples-1)) {
15203: if (defined($samples->[$line]{$key})) {
15204: $r->print($samples->[$line]{$key}."<br />\n");
15205: }
15206: }
15207: $r->print('</td>'.&end_data_table_row());
15208: $i++;
15209: }
15210: $r->print(&end_data_table());
15211: $i--;
15212: return($i);
15213: }
15214:
15215: ######################################################
15216: ######################################################
15217:
15218: =pod
15219:
15220: =item * &clean_excel_name($name)
15221:
15222: Returns a replacement for $name which does not contain any illegal characters.
15223:
15224: =cut
15225:
15226: ######################################################
15227: ######################################################
15228: sub clean_excel_name {
15229: my ($name) = @_;
15230: $name =~ s/[:\*\?\/\\]//g;
15231: if (length($name) > 31) {
15232: $name = substr($name,0,31);
15233: }
15234: return $name;
15235: }
15236:
15237: =pod
15238:
15239: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15240:
15241: Returns either 1 or undef
15242:
15243: 1 if the part is to be hidden, undef if it is to be shown
15244:
15245: Arguments are:
15246:
15247: $id the id of the part to be checked
15248: $symb, optional the symb of the resource to check
15249: $udom, optional the domain of the user to check for
15250: $uname, optional the username of the user to check for
15251:
15252: =cut
15253:
15254: sub check_if_partid_hidden {
15255: my ($id,$symb,$udom,$uname) = @_;
15256: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15257: $symb,$udom,$uname);
15258: my $truth=1;
15259: #if the string starts with !, then the list is the list to show not hide
15260: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15261: my @hiddenlist=split(/,/,$hiddenparts);
15262: foreach my $checkid (@hiddenlist) {
15263: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15264: }
15265: return !$truth;
15266: }
15267:
15268:
15269: ############################################################
15270: ############################################################
15271:
15272: =pod
15273:
15274: =back
15275:
15276: =head1 cgi-bin script and graphing routines
15277:
15278: =over 4
15279:
15280: =item * &get_cgi_id()
15281:
15282: Inputs: none
15283:
15284: Returns an id which can be used to pass environment variables
15285: to various cgi-bin scripts. These environment variables will
15286: be removed from the users environment after a given time by
15287: the routine &Apache::lonnet::transfer_profile_to_env.
15288:
15289: =cut
15290:
15291: ############################################################
15292: ############################################################
15293: my $uniq=0;
15294: sub get_cgi_id {
15295: $uniq=($uniq+1)%100000;
15296: return (time.'_'.$$.'_'.$uniq);
15297: }
15298:
15299: ############################################################
15300: ############################################################
15301:
15302: =pod
15303:
15304: =item * &DrawBarGraph()
15305:
15306: Facilitates the plotting of data in a (stacked) bar graph.
15307: Puts plot definition data into the users environment in order for
15308: graph.png to plot it. Returns an <img> tag for the plot.
15309: The bars on the plot are labeled '1','2',...,'n'.
15310:
15311: Inputs:
15312:
15313: =over 4
15314:
15315: =item $Title: string, the title of the plot
15316:
15317: =item $xlabel: string, text describing the X-axis of the plot
15318:
15319: =item $ylabel: string, text describing the Y-axis of the plot
15320:
15321: =item $Max: scalar, the maximum Y value to use in the plot
15322: If $Max is < any data point, the graph will not be rendered.
15323:
15324: =item $colors: array ref holding the colors to be used for the data sets when
15325: they are plotted. If undefined, default values will be used.
15326:
15327: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15328:
15329: =item @Values: An array of array references. Each array reference holds data
15330: to be plotted in a stacked bar chart.
15331:
15332: =item If the final element of @Values is a hash reference the key/value
15333: pairs will be added to the graph definition.
15334:
15335: =back
15336:
15337: Returns:
15338:
15339: An <img> tag which references graph.png and the appropriate identifying
15340: information for the plot.
15341:
15342: =cut
15343:
15344: ############################################################
15345: ############################################################
15346: sub DrawBarGraph {
15347: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15348: #
15349: if (! defined($colors)) {
15350: $colors = ['#33ff00',
15351: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15352: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15353: ];
15354: }
15355: my $extra_settings = {};
15356: if (ref($Values[-1]) eq 'HASH') {
15357: $extra_settings = pop(@Values);
15358: }
15359: #
15360: my $identifier = &get_cgi_id();
15361: my $id = 'cgi.'.$identifier;
15362: if (! @Values || ref($Values[0]) ne 'ARRAY') {
15363: return '';
15364: }
15365: #
15366: my @Labels;
15367: if (defined($labels)) {
15368: @Labels = @$labels;
15369: } else {
15370: for (my $i=0;$i<@{$Values[0]};$i++) {
15371: push(@Labels,$i+1);
15372: }
15373: }
15374: #
15375: my $NumBars = scalar(@{$Values[0]});
15376: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15377: my %ValuesHash;
15378: my $NumSets=1;
15379: foreach my $array (@Values) {
15380: next if (! ref($array));
15381: $ValuesHash{$id.'.data.'.$NumSets++} =
15382: join(',',@$array);
15383: }
15384: #
15385: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15386: if ($NumBars < 3) {
15387: $width = 120+$NumBars*32;
15388: $xskip = 1;
15389: $bar_width = 30;
15390: } elsif ($NumBars < 5) {
15391: $width = 120+$NumBars*20;
15392: $xskip = 1;
15393: $bar_width = 20;
15394: } elsif ($NumBars < 10) {
15395: $width = 120+$NumBars*15;
15396: $xskip = 1;
15397: $bar_width = 15;
15398: } elsif ($NumBars <= 25) {
15399: $width = 120+$NumBars*11;
15400: $xskip = 5;
15401: $bar_width = 8;
15402: } elsif ($NumBars <= 50) {
15403: $width = 120+$NumBars*8;
15404: $xskip = 5;
15405: $bar_width = 4;
15406: } else {
15407: $width = 120+$NumBars*8;
15408: $xskip = 5;
15409: $bar_width = 4;
15410: }
15411: #
15412: $Max = 1 if ($Max < 1);
15413: if ( int($Max) < $Max ) {
15414: $Max++;
15415: $Max = int($Max);
15416: }
15417: $Title = '' if (! defined($Title));
15418: $xlabel = '' if (! defined($xlabel));
15419: $ylabel = '' if (! defined($ylabel));
15420: $ValuesHash{$id.'.title'} = &escape($Title);
15421: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
15422: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
15423: $ValuesHash{$id.'.y_max_value'} = $Max;
15424: $ValuesHash{$id.'.NumBars'} = $NumBars;
15425: $ValuesHash{$id.'.NumSets'} = $NumSets;
15426: $ValuesHash{$id.'.PlotType'} = 'bar';
15427: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15428: $ValuesHash{$id.'.height'} = $height;
15429: $ValuesHash{$id.'.width'} = $width;
15430: $ValuesHash{$id.'.xskip'} = $xskip;
15431: $ValuesHash{$id.'.bar_width'} = $bar_width;
15432: $ValuesHash{$id.'.labels'} = join(',',@Labels);
15433: #
15434: # Deal with other parameters
15435: while (my ($key,$value) = each(%$extra_settings)) {
15436: $ValuesHash{$id.'.'.$key} = $value;
15437: }
15438: #
15439: &Apache::lonnet::appenv(\%ValuesHash);
15440: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15441: }
15442:
15443: ############################################################
15444: ############################################################
15445:
15446: =pod
15447:
15448: =item * &DrawXYGraph()
15449:
15450: Facilitates the plotting of data in an XY graph.
15451: Puts plot definition data into the users environment in order for
15452: graph.png to plot it. Returns an <img> tag for the plot.
15453:
15454: Inputs:
15455:
15456: =over 4
15457:
15458: =item $Title: string, the title of the plot
15459:
15460: =item $xlabel: string, text describing the X-axis of the plot
15461:
15462: =item $ylabel: string, text describing the Y-axis of the plot
15463:
15464: =item $Max: scalar, the maximum Y value to use in the plot
15465: If $Max is < any data point, the graph will not be rendered.
15466:
15467: =item $colors: Array ref containing the hex color codes for the data to be
15468: plotted in. If undefined, default values will be used.
15469:
15470: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15471:
15472: =item $Ydata: Array ref containing Array refs.
15473: Each of the contained arrays will be plotted as a separate curve.
15474:
15475: =item %Values: hash indicating or overriding any default values which are
15476: passed to graph.png.
15477: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15478:
15479: =back
15480:
15481: Returns:
15482:
15483: An <img> tag which references graph.png and the appropriate identifying
15484: information for the plot.
15485:
15486: =cut
15487:
15488: ############################################################
15489: ############################################################
15490: sub DrawXYGraph {
15491: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15492: #
15493: # Create the identifier for the graph
15494: my $identifier = &get_cgi_id();
15495: my $id = 'cgi.'.$identifier;
15496: #
15497: $Title = '' if (! defined($Title));
15498: $xlabel = '' if (! defined($xlabel));
15499: $ylabel = '' if (! defined($ylabel));
15500: my %ValuesHash =
15501: (
15502: $id.'.title' => &escape($Title),
15503: $id.'.xlabel' => &escape($xlabel),
15504: $id.'.ylabel' => &escape($ylabel),
15505: $id.'.y_max_value'=> $Max,
15506: $id.'.labels' => join(',',@$Xlabels),
15507: $id.'.PlotType' => 'XY',
15508: );
15509: #
15510: if (defined($colors) && ref($colors) eq 'ARRAY') {
15511: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15512: }
15513: #
15514: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15515: return '';
15516: }
15517: my $NumSets=1;
15518: foreach my $array (@{$Ydata}){
15519: next if (! ref($array));
15520: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15521: }
15522: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15523: #
15524: # Deal with other parameters
15525: while (my ($key,$value) = each(%Values)) {
15526: $ValuesHash{$id.'.'.$key} = $value;
15527: }
15528: #
15529: &Apache::lonnet::appenv(\%ValuesHash);
15530: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15531: }
15532:
15533: ############################################################
15534: ############################################################
15535:
15536: =pod
15537:
15538: =item * &DrawXYYGraph()
15539:
15540: Facilitates the plotting of data in an XY graph with two Y axes.
15541: Puts plot definition data into the users environment in order for
15542: graph.png to plot it. Returns an <img> tag for the plot.
15543:
15544: Inputs:
15545:
15546: =over 4
15547:
15548: =item $Title: string, the title of the plot
15549:
15550: =item $xlabel: string, text describing the X-axis of the plot
15551:
15552: =item $ylabel: string, text describing the Y-axis of the plot
15553:
15554: =item $colors: Array ref containing the hex color codes for the data to be
15555: plotted in. If undefined, default values will be used.
15556:
15557: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15558:
15559: =item $Ydata1: The first data set
15560:
15561: =item $Min1: The minimum value of the left Y-axis
15562:
15563: =item $Max1: The maximum value of the left Y-axis
15564:
15565: =item $Ydata2: The second data set
15566:
15567: =item $Min2: The minimum value of the right Y-axis
15568:
15569: =item $Max2: The maximum value of the left Y-axis
15570:
15571: =item %Values: hash indicating or overriding any default values which are
15572: passed to graph.png.
15573: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15574:
15575: =back
15576:
15577: Returns:
15578:
15579: An <img> tag which references graph.png and the appropriate identifying
15580: information for the plot.
15581:
15582: =cut
15583:
15584: ############################################################
15585: ############################################################
15586: sub DrawXYYGraph {
15587: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15588: $Ydata2,$Min2,$Max2,%Values)=@_;
15589: #
15590: # Create the identifier for the graph
15591: my $identifier = &get_cgi_id();
15592: my $id = 'cgi.'.$identifier;
15593: #
15594: $Title = '' if (! defined($Title));
15595: $xlabel = '' if (! defined($xlabel));
15596: $ylabel = '' if (! defined($ylabel));
15597: my %ValuesHash =
15598: (
15599: $id.'.title' => &escape($Title),
15600: $id.'.xlabel' => &escape($xlabel),
15601: $id.'.ylabel' => &escape($ylabel),
15602: $id.'.labels' => join(',',@$Xlabels),
15603: $id.'.PlotType' => 'XY',
15604: $id.'.NumSets' => 2,
15605: $id.'.two_axes' => 1,
15606: $id.'.y1_max_value' => $Max1,
15607: $id.'.y1_min_value' => $Min1,
15608: $id.'.y2_max_value' => $Max2,
15609: $id.'.y2_min_value' => $Min2,
15610: );
15611: #
15612: if (defined($colors) && ref($colors) eq 'ARRAY') {
15613: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15614: }
15615: #
15616: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15617: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15618: return '';
15619: }
15620: my $NumSets=1;
15621: foreach my $array ($Ydata1,$Ydata2){
15622: next if (! ref($array));
15623: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15624: }
15625: #
15626: # Deal with other parameters
15627: while (my ($key,$value) = each(%Values)) {
15628: $ValuesHash{$id.'.'.$key} = $value;
15629: }
15630: #
15631: &Apache::lonnet::appenv(\%ValuesHash);
15632: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15633: }
15634:
15635: ############################################################
15636: ############################################################
15637:
15638: =pod
15639:
15640: =back
15641:
15642: =head1 Statistics helper routines?
15643:
15644: Bad place for them but what the hell.
15645:
15646: =over 4
15647:
15648: =item * &chartlink()
15649:
15650: Returns a link to the chart for a specific student.
15651:
15652: Inputs:
15653:
15654: =over 4
15655:
15656: =item $linktext: The text of the link
15657:
15658: =item $sname: The students username
15659:
15660: =item $sdomain: The students domain
15661:
15662: =back
15663:
15664: =back
15665:
15666: =cut
15667:
15668: ############################################################
15669: ############################################################
15670: sub chartlink {
15671: my ($linktext, $sname, $sdomain) = @_;
15672: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15673: '&SelectedStudent='.&escape($sname.':'.$sdomain).
15674: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
15675: '">'.$linktext.'</a>';
15676: }
15677:
15678: #######################################################
15679: #######################################################
15680:
15681: =pod
15682:
15683: =head1 Course Environment Routines
15684:
15685: =over 4
15686:
15687: =item * &restore_course_settings()
15688:
15689: =item * &store_course_settings()
15690:
15691: Restores/Store indicated form parameters from the course environment.
15692: Will not overwrite existing values of the form parameters.
15693:
15694: Inputs:
15695: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15696:
15697: a hash ref describing the data to be stored. For example:
15698:
15699: %Save_Parameters = ('Status' => 'scalar',
15700: 'chartoutputmode' => 'scalar',
15701: 'chartoutputdata' => 'scalar',
15702: 'Section' => 'array',
15703: 'Group' => 'array',
15704: 'StudentData' => 'array',
15705: 'Maps' => 'array');
15706:
15707: Returns: both routines return nothing
15708:
15709: =back
15710:
15711: =cut
15712:
15713: #######################################################
15714: #######################################################
15715: sub store_course_settings {
15716: return &store_settings($env{'request.course.id'},@_);
15717: }
15718:
15719: sub store_settings {
15720: # save to the environment
15721: # appenv the same items, just to be safe
15722: my $udom = $env{'user.domain'};
15723: my $uname = $env{'user.name'};
15724: my ($context,$prefix,$Settings) = @_;
15725: my %SaveHash;
15726: my %AppHash;
15727: while (my ($setting,$type) = each(%$Settings)) {
15728: my $basename = join('.','internal',$context,$prefix,$setting);
15729: my $envname = 'environment.'.$basename;
15730: if (exists($env{'form.'.$setting})) {
15731: # Save this value away
15732: if ($type eq 'scalar' &&
15733: (! exists($env{$envname}) ||
15734: $env{$envname} ne $env{'form.'.$setting})) {
15735: $SaveHash{$basename} = $env{'form.'.$setting};
15736: $AppHash{$envname} = $env{'form.'.$setting};
15737: } elsif ($type eq 'array') {
15738: my $stored_form;
15739: if (ref($env{'form.'.$setting})) {
15740: $stored_form = join(',',
15741: map {
15742: &escape($_);
15743: } sort(@{$env{'form.'.$setting}}));
15744: } else {
15745: $stored_form =
15746: &escape($env{'form.'.$setting});
15747: }
15748: # Determine if the array contents are the same.
15749: if ($stored_form ne $env{$envname}) {
15750: $SaveHash{$basename} = $stored_form;
15751: $AppHash{$envname} = $stored_form;
15752: }
15753: }
15754: }
15755: }
15756: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15757: $udom,$uname);
15758: if ($put_result !~ /^(ok|delayed)/) {
15759: &Apache::lonnet::logthis('unable to save form parameters, '.
15760: 'got error:'.$put_result);
15761: }
15762: # Make sure these settings stick around in this session, too
15763: &Apache::lonnet::appenv(\%AppHash);
15764: return;
15765: }
15766:
15767: sub restore_course_settings {
15768: return &restore_settings($env{'request.course.id'},@_);
15769: }
15770:
15771: sub restore_settings {
15772: my ($context,$prefix,$Settings) = @_;
15773: while (my ($setting,$type) = each(%$Settings)) {
15774: next if (exists($env{'form.'.$setting}));
15775: my $envname = 'environment.internal.'.$context.'.'.$prefix.
15776: '.'.$setting;
15777: if (exists($env{$envname})) {
15778: if ($type eq 'scalar') {
15779: $env{'form.'.$setting} = $env{$envname};
15780: } elsif ($type eq 'array') {
15781: $env{'form.'.$setting} = [
15782: map {
15783: &unescape($_);
15784: } split(',',$env{$envname})
15785: ];
15786: }
15787: }
15788: }
15789: }
15790:
15791: #######################################################
15792: #######################################################
15793:
15794: =pod
15795:
15796: =head1 Domain E-mail Routines
15797:
15798: =over 4
15799:
15800: =item * &build_recipient_list()
15801:
15802: Build recipient lists for following types of e-mail:
15803: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15804: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15805: module change checking, student/employee ID conflict checks, as
15806: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15807: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15808:
15809: Inputs:
15810: defmail (scalar - email address of default recipient),
15811: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15812: requestsmail, updatesmail, or idconflictsmail).
15813:
15814: defdom (domain for which to retrieve configuration settings),
15815:
15816: origmail (scalar - email address of recipient from loncapa.conf,
15817: i.e., predates configuration by DC via domainprefs.pm
15818:
15819: $requname username of requester (if mailing type is helpdeskmail)
15820:
15821: $requdom domain of requester (if mailing type is helpdeskmail)
15822:
15823: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15824:
15825:
15826: Returns: comma separated list of addresses to which to send e-mail.
15827:
15828: =back
15829:
15830: =cut
15831:
15832: ############################################################
15833: ############################################################
15834: sub build_recipient_list {
15835: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15836: my @recipients;
15837: my ($otheremails,$lastresort,$allbcc,$addtext);
15838: my %domconfig =
15839: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15840: if (ref($domconfig{'contacts'}) eq 'HASH') {
15841: if (exists($domconfig{'contacts'}{$mailing})) {
15842: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15843: my @contacts = ('adminemail','supportemail');
15844: foreach my $item (@contacts) {
15845: if ($domconfig{'contacts'}{$mailing}{$item}) {
15846: my $addr = $domconfig{'contacts'}{$item};
15847: if (!grep(/^\Q$addr\E$/,@recipients)) {
15848: push(@recipients,$addr);
15849: }
15850: }
15851: }
15852: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15853: if ($mailing eq 'helpdeskmail') {
15854: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15855: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15856: my @ok_bccs;
15857: foreach my $bcc (@bccs) {
15858: $bcc =~ s/^\s+//g;
15859: $bcc =~ s/\s+$//g;
15860: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15861: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15862: push(@ok_bccs,$bcc);
15863: }
15864: }
15865: }
15866: if (@ok_bccs > 0) {
15867: $allbcc = join(', ',@ok_bccs);
15868: }
15869: }
15870: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15871: }
15872: }
15873: } elsif ($origmail ne '') {
15874: $lastresort = $origmail;
15875: }
15876: if ($mailing eq 'helpdeskmail') {
15877: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15878: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15879: my ($inststatus,$inststatus_checked);
15880: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15881: ($env{'user.domain'} ne 'public')) {
15882: $inststatus_checked = 1;
15883: $inststatus = $env{'environment.inststatus'};
15884: }
15885: unless ($inststatus_checked) {
15886: if (($requname ne '') && ($requdom ne '')) {
15887: if (($requname =~ /^$match_username$/) &&
15888: ($requdom =~ /^$match_domain$/) &&
15889: (&Apache::lonnet::domain($requdom))) {
15890: my $requhome = &Apache::lonnet::homeserver($requname,
15891: $requdom);
15892: unless ($requhome eq 'no_host') {
15893: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15894: $inststatus = $userenv{'inststatus'};
15895: $inststatus_checked = 1;
15896: }
15897: }
15898: }
15899: }
15900: unless ($inststatus_checked) {
15901: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15902: my %srch = (srchby => 'email',
15903: srchdomain => $defdom,
15904: srchterm => $reqemail,
15905: srchtype => 'exact');
15906: my %srch_results = &Apache::lonnet::usersearch(\%srch);
15907: foreach my $uname (keys(%srch_results)) {
15908: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15909: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15910: $inststatus_checked = 1;
15911: last;
15912: }
15913: }
15914: unless ($inststatus_checked) {
15915: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15916: if ($dirsrchres eq 'ok') {
15917: foreach my $uname (keys(%srch_results)) {
15918: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15919: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15920: $inststatus_checked = 1;
15921: last;
15922: }
15923: }
15924: }
15925: }
15926: }
15927: }
15928: if ($inststatus ne '') {
15929: foreach my $status (split(/\:/,$inststatus)) {
15930: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15931: my @contacts = ('adminemail','supportemail');
15932: foreach my $item (@contacts) {
15933: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15934: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15935: if (!grep(/^\Q$addr\E$/,@recipients)) {
15936: push(@recipients,$addr);
15937: }
15938: }
15939: }
15940: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15941: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15942: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15943: my @ok_bccs;
15944: foreach my $bcc (@bccs) {
15945: $bcc =~ s/^\s+//g;
15946: $bcc =~ s/\s+$//g;
15947: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15948: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15949: push(@ok_bccs,$bcc);
15950: }
15951: }
15952: }
15953: if (@ok_bccs > 0) {
15954: $allbcc = join(', ',@ok_bccs);
15955: }
15956: }
15957: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15958: last;
15959: }
15960: }
15961: }
15962: }
15963: }
15964: } elsif ($origmail ne '') {
15965: $lastresort = $origmail;
15966: }
15967: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15968: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15969: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15970: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15971: my %what = (
15972: perlvar => 1,
15973: );
15974: my $primary = &Apache::lonnet::domain($defdom,'primary');
15975: if ($primary) {
15976: my $gotaddr;
15977: my ($result,$returnhash) =
15978: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15979: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15980: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15981: $lastresort = $returnhash->{'lonSupportEMail'};
15982: $gotaddr = 1;
15983: }
15984: }
15985: unless ($gotaddr) {
15986: my $uintdom = &Apache::lonnet::internet_dom($primary);
15987: my $intdom = &Apache::lonnet::internet_dom($lonhost);
15988: unless ($uintdom eq $intdom) {
15989: my %domconfig =
15990: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15991: if (ref($domconfig{'contacts'}) eq 'HASH') {
15992: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15993: my @contacts = ('adminemail','supportemail');
15994: foreach my $item (@contacts) {
15995: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15996: my $addr = $domconfig{'contacts'}{$item};
15997: if (!grep(/^\Q$addr\E$/,@recipients)) {
15998: push(@recipients,$addr);
15999: }
16000: }
16001: }
16002: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16003: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16004: }
16005: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16006: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16007: my @ok_bccs;
16008: foreach my $bcc (@bccs) {
16009: $bcc =~ s/^\s+//g;
16010: $bcc =~ s/\s+$//g;
16011: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16012: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16013: push(@ok_bccs,$bcc);
16014: }
16015: }
16016: }
16017: if (@ok_bccs > 0) {
16018: $allbcc = join(', ',@ok_bccs);
16019: }
16020: }
16021: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16022: }
16023: }
16024: }
16025: }
16026: }
16027: }
16028: }
16029: if (defined($defmail)) {
16030: if ($defmail ne '') {
16031: push(@recipients,$defmail);
16032: }
16033: }
16034: if ($otheremails) {
16035: my @others;
16036: if ($otheremails =~ /,/) {
16037: @others = split(/,/,$otheremails);
16038: } else {
16039: push(@others,$otheremails);
16040: }
16041: foreach my $addr (@others) {
16042: if (!grep(/^\Q$addr\E$/,@recipients)) {
16043: push(@recipients,$addr);
16044: }
16045: }
16046: }
16047: if ($mailing eq 'helpdeskmail') {
16048: if ((!@recipients) && ($lastresort ne '')) {
16049: push(@recipients,$lastresort);
16050: }
16051: } elsif ($lastresort ne '') {
16052: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16053: push(@recipients,$lastresort);
16054: }
16055: }
16056: my $recipientlist = join(',',@recipients);
16057: if (wantarray) {
16058: return ($recipientlist,$allbcc,$addtext);
16059: } else {
16060: return $recipientlist;
16061: }
16062: }
16063:
16064: ############################################################
16065: ############################################################
16066:
16067: =pod
16068:
16069: =over 4
16070:
16071: =item * &mime_email()
16072:
16073: Sends an email with a possible attachment
16074:
16075: Inputs:
16076:
16077: =over 4
16078:
16079: from - Sender's email address
16080:
16081: replyto - Reply-To email address
16082:
16083: to - Email address of recipient
16084:
16085: subject - Subject of email
16086:
16087: body - Body of email
16088:
16089: cc_string - Carbon copy email address
16090:
16091: bcc - Blind carbon copy email address
16092:
16093: attachment_path - Path of file to be attached
16094:
16095: file_name - Name of file to be attached
16096:
16097: attachment_text - The body of an attachment of type "TEXT"
16098:
16099: =back
16100:
16101: =back
16102:
16103: =cut
16104:
16105: ############################################################
16106: ############################################################
16107:
16108: sub mime_email {
16109: my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path,
16110: $file_name,$attachment_text) = @_;
16111:
16112: my $msg = MIME::Lite->new(
16113: From => $from,
16114: To => $to,
16115: Subject => $subject,
16116: Type =>'TEXT',
16117: Data => $body,
16118: );
16119: if ($replyto ne '') {
16120: $msg->add("Reply-To" => $replyto);
16121: }
16122: if ($cc_string ne '') {
16123: $msg->add("Cc" => $cc_string);
16124: }
16125: if ($bcc ne '') {
16126: $msg->add("Bcc" => $bcc);
16127: }
16128: $msg->attr("content-type" => "text/plain");
16129: $msg->attr("content-type.charset" => "UTF-8");
16130: # Attach file if given
16131: if ($attachment_path) {
16132: unless ($file_name) {
16133: if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16134: }
16135: my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16136: $msg->attach(Type => $type,
16137: Path => $attachment_path,
16138: Filename => $file_name
16139: );
16140: # Otherwise attach text if given
16141: } elsif ($attachment_text) {
16142: $msg->attach(Type => 'TEXT',
16143: Data => $attachment_text);
16144: }
16145: # Send it
16146: $msg->send('sendmail');
16147: }
16148:
16149: ############################################################
16150: ############################################################
16151:
16152: =pod
16153:
16154: =head1 Course Catalog Routines
16155:
16156: =over 4
16157:
16158: =item * &gather_categories()
16159:
16160: Converts category definitions - keys of categories hash stored in
16161: coursecategories in configuration.db on the primary library server in a
16162: domain - to an array. Also generates javascript and idx hash used to
16163: generate Domain Coordinator interface for editing Course Categories.
16164:
16165: Inputs:
16166:
16167: categories (reference to hash of category definitions).
16168:
16169: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16170: categories and subcategories).
16171:
16172: idx (reference to hash of counters used in Domain Coordinator interface for
16173: editing Course Categories).
16174:
16175: jsarray (reference to array of categories used to create Javascript arrays for
16176: Domain Coordinator interface for editing Course Categories).
16177:
16178: Returns: nothing
16179:
16180: Side effects: populates cats, idx and jsarray.
16181:
16182: =cut
16183:
16184: sub gather_categories {
16185: my ($categories,$cats,$idx,$jsarray) = @_;
16186: my %counters;
16187: my $num = 0;
16188: foreach my $item (keys(%{$categories})) {
16189: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16190: if ($container eq '' && $depth == 0) {
16191: $cats->[$depth][$categories->{$item}] = $cat;
16192: } else {
16193: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16194: }
16195: my ($escitem,$tail) = split(/:/,$item,2);
16196: if ($counters{$tail} eq '') {
16197: $counters{$tail} = $num;
16198: $num ++;
16199: }
16200: if (ref($idx) eq 'HASH') {
16201: $idx->{$item} = $counters{$tail};
16202: }
16203: if (ref($jsarray) eq 'ARRAY') {
16204: push(@{$jsarray->[$counters{$tail}]},$item);
16205: }
16206: }
16207: return;
16208: }
16209:
16210: =pod
16211:
16212: =item * &extract_categories()
16213:
16214: Used to generate breadcrumb trails for course categories.
16215:
16216: Inputs:
16217:
16218: categories (reference to hash of category definitions).
16219:
16220: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16221: categories and subcategories).
16222:
16223: trails (reference to array of breacrumb trails for each category).
16224:
16225: allitems (reference to hash - key is category key
16226: (format: escaped(name):escaped(parent category):depth in hierarchy).
16227:
16228: idx (reference to hash of counters used in Domain Coordinator interface for
16229: editing Course Categories).
16230:
16231: jsarray (reference to array of categories used to create Javascript arrays for
16232: Domain Coordinator interface for editing Course Categories).
16233:
16234: subcats (reference to hash of arrays containing all subcategories within each
16235: category, -recursive)
16236:
16237: maxd (reference to hash used to hold max depth for all top-level categories).
16238:
16239: Returns: nothing
16240:
16241: Side effects: populates trails and allitems hash references.
16242:
16243: =cut
16244:
16245: sub extract_categories {
16246: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16247: if (ref($categories) eq 'HASH') {
16248: &gather_categories($categories,$cats,$idx,$jsarray);
16249: if (ref($cats->[0]) eq 'ARRAY') {
16250: for (my $i=0; $i<@{$cats->[0]}; $i++) {
16251: my $name = $cats->[0][$i];
16252: my $item = &escape($name).'::0';
16253: my $trailstr;
16254: if ($name eq 'instcode') {
16255: $trailstr = &mt('Official courses (with institutional codes)');
16256: } elsif ($name eq 'communities') {
16257: $trailstr = &mt('Communities');
16258: } elsif ($name eq 'placement') {
16259: $trailstr = &mt('Placement Tests');
16260: } else {
16261: $trailstr = $name;
16262: }
16263: if ($allitems->{$item} eq '') {
16264: push(@{$trails},$trailstr);
16265: $allitems->{$item} = scalar(@{$trails})-1;
16266: }
16267: my @parents = ($name);
16268: if (ref($cats->[1]{$name}) eq 'ARRAY') {
16269: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16270: my $category = $cats->[1]{$name}[$j];
16271: if (ref($subcats) eq 'HASH') {
16272: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16273: }
16274: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16275: }
16276: } else {
16277: if (ref($subcats) eq 'HASH') {
16278: $subcats->{$item} = [];
16279: }
16280: if (ref($maxd) eq 'HASH') {
16281: $maxd->{$name} = 1;
16282: }
16283: }
16284: }
16285: }
16286: }
16287: return;
16288: }
16289:
16290: =pod
16291:
16292: =item * &recurse_categories()
16293:
16294: Recursively used to generate breadcrumb trails for course categories.
16295:
16296: Inputs:
16297:
16298: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16299: categories and subcategories).
16300:
16301: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16302:
16303: category (current course category, for which breadcrumb trail is being generated).
16304:
16305: trails (reference to array of breadcrumb trails for each category).
16306:
16307: allitems (reference to hash - key is category key
16308: (format: escaped(name):escaped(parent category):depth in hierarchy).
16309:
16310: parents (array containing containers directories for current category,
16311: back to top level).
16312:
16313: Returns: nothing
16314:
16315: Side effects: populates trails and allitems hash references
16316:
16317: =cut
16318:
16319: sub recurse_categories {
16320: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16321: my $shallower = $depth - 1;
16322: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16323: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16324: my $name = $cats->[$depth]{$category}[$k];
16325: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16326: my $trailstr = join(' » ',(@{$parents},$category));
16327: if ($allitems->{$item} eq '') {
16328: push(@{$trails},$trailstr);
16329: $allitems->{$item} = scalar(@{$trails})-1;
16330: }
16331: my $deeper = $depth+1;
16332: push(@{$parents},$category);
16333: if (ref($subcats) eq 'HASH') {
16334: my $subcat = &escape($name).':'.$category.':'.$depth;
16335: for (my $j=@{$parents}; $j>=0; $j--) {
16336: my $higher;
16337: if ($j > 0) {
16338: $higher = &escape($parents->[$j]).':'.
16339: &escape($parents->[$j-1]).':'.$j;
16340: } else {
16341: $higher = &escape($parents->[$j]).'::'.$j;
16342: }
16343: push(@{$subcats->{$higher}},$subcat);
16344: }
16345: }
16346: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16347: $subcats,$maxd);
16348: pop(@{$parents});
16349: }
16350: } else {
16351: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16352: my $trailstr = join(' » ',(@{$parents},$category));
16353: if ($allitems->{$item} eq '') {
16354: push(@{$trails},$trailstr);
16355: $allitems->{$item} = scalar(@{$trails})-1;
16356: }
16357: if (ref($maxd) eq 'HASH') {
16358: if ($depth > $maxd->{$parents->[0]}) {
16359: $maxd->{$parents->[0]} = $depth;
16360: }
16361: }
16362: }
16363: return;
16364: }
16365:
16366: =pod
16367:
16368: =item * &assign_categories_table()
16369:
16370: Create a datatable for display of hierarchical categories in a domain,
16371: with checkboxes to allow a course to be categorized.
16372:
16373: Inputs:
16374:
16375: cathash - reference to hash of categories defined for the domain (from
16376: configuration.db)
16377:
16378: currcat - scalar with an & separated list of categories assigned to a course.
16379:
16380: type - scalar contains course type (Course or Community).
16381:
16382: disabled - scalar (optional) contains disabled="disabled" if input elements are
16383: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16384:
16385: Returns: $output (markup to be displayed)
16386:
16387: =cut
16388:
16389: sub assign_categories_table {
16390: my ($cathash,$currcat,$type,$disabled) = @_;
16391: my $output;
16392: if (ref($cathash) eq 'HASH') {
16393: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16394: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16395: $maxdepth = scalar(@cats);
16396: if (@cats > 0) {
16397: my $itemcount = 0;
16398: if (ref($cats[0]) eq 'ARRAY') {
16399: my @currcategories;
16400: if ($currcat ne '') {
16401: @currcategories = split('&',$currcat);
16402: }
16403: my $table;
16404: for (my $i=0; $i<@{$cats[0]}; $i++) {
16405: my $parent = $cats[0][$i];
16406: next if ($parent eq 'instcode');
16407: if ($type eq 'Community') {
16408: next unless ($parent eq 'communities');
16409: } elsif ($type eq 'Placement') {
16410: next unless ($parent eq 'placement');
16411: } else {
16412: next if (($parent eq 'communities') || ($parent eq 'placement'));
16413: }
16414: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16415: my $item = &escape($parent).'::0';
16416: my $checked = '';
16417: if (@currcategories > 0) {
16418: if (grep(/^\Q$item\E$/,@currcategories)) {
16419: $checked = ' checked="checked"';
16420: }
16421: }
16422: my $parent_title = $parent;
16423: if ($parent eq 'communities') {
16424: $parent_title = &mt('Communities');
16425: } elsif ($parent eq 'placement') {
16426: $parent_title = &mt('Placement Tests');
16427: }
16428: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16429: '<input type="checkbox" name="usecategory" value="'.
16430: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16431: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16432: my $depth = 1;
16433: push(@path,$parent);
16434: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16435: pop(@path);
16436: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16437: $itemcount ++;
16438: }
16439: if ($itemcount) {
16440: $output = &Apache::loncommon::start_data_table().
16441: $table.
16442: &Apache::loncommon::end_data_table();
16443: }
16444: }
16445: }
16446: }
16447: return $output;
16448: }
16449:
16450: =pod
16451:
16452: =item * &assign_category_rows()
16453:
16454: Create a datatable row for display of nested categories in a domain,
16455: with checkboxes to allow a course to be categorized,called recursively.
16456:
16457: Inputs:
16458:
16459: itemcount - track row number for alternating colors
16460:
16461: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16462: categories and subcategories.
16463:
16464: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16465:
16466: parent - parent of current category item
16467:
16468: path - Array containing all categories back up through the hierarchy from the
16469: current category to the top level.
16470:
16471: currcategories - reference to array of current categories assigned to the course
16472:
16473: disabled - scalar (optional) contains disabled="disabled" if input elements are
16474: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16475:
16476: Returns: $output (markup to be displayed).
16477:
16478: =cut
16479:
16480: sub assign_category_rows {
16481: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16482: my ($text,$name,$item,$chgstr);
16483: if (ref($cats) eq 'ARRAY') {
16484: my $maxdepth = scalar(@{$cats});
16485: if (ref($cats->[$depth]) eq 'HASH') {
16486: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16487: my $numchildren = @{$cats->[$depth]{$parent}};
16488: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16489: $text .= '<td><table class="LC_data_table">';
16490: for (my $j=0; $j<$numchildren; $j++) {
16491: $name = $cats->[$depth]{$parent}[$j];
16492: $item = &escape($name).':'.&escape($parent).':'.$depth;
16493: my $deeper = $depth+1;
16494: my $checked = '';
16495: if (ref($currcategories) eq 'ARRAY') {
16496: if (@{$currcategories} > 0) {
16497: if (grep(/^\Q$item\E$/,@{$currcategories})) {
16498: $checked = ' checked="checked"';
16499: }
16500: }
16501: }
16502: $text .= '<tr><td><span class="LC_nobreak"><label>'.
16503: '<input type="checkbox" name="usecategory" value="'.
16504: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16505: '<input type="hidden" name="catname" value="'.$name.'" />'.
16506: '</td><td>';
16507: if (ref($path) eq 'ARRAY') {
16508: push(@{$path},$name);
16509: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16510: pop(@{$path});
16511: }
16512: $text .= '</td></tr>';
16513: }
16514: $text .= '</table></td>';
16515: }
16516: }
16517: }
16518: return $text;
16519: }
16520:
16521: =pod
16522:
16523: =back
16524:
16525: =cut
16526:
16527: ############################################################
16528: ############################################################
16529:
16530:
16531: sub commit_customrole {
16532: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
16533: my $result = &Apache::lonnet::assigncustomrole(
16534: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context);
16535: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16536: ($start?', '.&mt('starting').' '.localtime($start):'').
16537: ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16538: if (wantarray) {
16539: return ($output,$result);
16540: } else {
16541: return $output;
16542: }
16543: }
16544:
16545: sub commit_standardrole {
16546: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
16547: my ($output,$logmsg,$linefeed,$result);
16548: if ($context eq 'auto') {
16549: $linefeed = "\n";
16550: } else {
16551: $linefeed = "<br />\n";
16552: }
16553: if ($three eq 'st') {
16554: $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16555: $one,$two,$sec,$context,$credits);
16556: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
16557: ($result eq 'unknown_course') || ($result eq 'refused')) {
16558: $output = $logmsg.' '.&mt('Error: ').$result."\n";
16559: } else {
16560: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16561: ($start?', '.&mt('starting').' '.localtime($start):'').
16562: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16563: if ($context eq 'auto') {
16564: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16565: } else {
16566: $output .= '<b>'.$result.'</b>'.$linefeed.
16567: &mt('Add to classlist').': <b>ok</b>';
16568: }
16569: $output .= $linefeed;
16570: }
16571: } else {
16572: $output = &mt('Assigning').' '.$three.' in '.$url.
16573: ($start?', '.&mt('starting').' '.localtime($start):'').
16574: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16575: $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16576: if ($context eq 'auto') {
16577: $output .= $result.$linefeed;
16578: } else {
16579: $output .= '<b>'.$result.'</b>'.$linefeed;
16580: }
16581: }
16582: if (wantarray) {
16583: return ($output,$result);
16584: } else {
16585: return $output;
16586: }
16587: }
16588:
16589: sub commit_studentrole {
16590: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16591: $credits) = @_;
16592: my ($result,$linefeed,$oldsecurl,$newsecurl);
16593: if ($context eq 'auto') {
16594: $linefeed = "\n";
16595: } else {
16596: $linefeed = '<br />'."\n";
16597: }
16598: if (defined($one) && defined($two)) {
16599: my $cid=$one.'_'.$two;
16600: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16601: my $secchange = 0;
16602: my $expire_role_result;
16603: my $modify_section_result;
16604: if ($oldsec ne '-1') {
16605: if ($oldsec ne $sec) {
16606: $secchange = 1;
16607: my $now = time;
16608: my $uurl='/'.$cid;
16609: $uurl=~s/\_/\//g;
16610: if ($oldsec) {
16611: $uurl.='/'.$oldsec;
16612: }
16613: $oldsecurl = $uurl;
16614: $expire_role_result =
16615: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
16616: if ($env{'request.course.sec'} ne '') {
16617: if ($expire_role_result eq 'refused') {
16618: my @roles = ('st');
16619: my @statuses = ('previous');
16620: my @roledoms = ($one);
16621: my $withsec = 1;
16622: my %roleshash =
16623: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16624: \@statuses,\@roles,\@roledoms,$withsec);
16625: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16626: my ($oldstart,$oldend) =
16627: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16628: if ($oldend > 0 && $oldend <= $now) {
16629: $expire_role_result = 'ok';
16630: }
16631: }
16632: }
16633: }
16634: $result = $expire_role_result;
16635: }
16636: }
16637: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16638: $modify_section_result =
16639: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16640: undef,undef,undef,$sec,
16641: $end,$start,'','',$cid,
16642: '',$context,$credits);
16643: if ($modify_section_result =~ /^ok/) {
16644: if ($secchange == 1) {
16645: if ($sec eq '') {
16646: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16647: } else {
16648: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16649: }
16650: } elsif ($oldsec eq '-1') {
16651: if ($sec eq '') {
16652: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16653: } else {
16654: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16655: }
16656: } else {
16657: if ($sec eq '') {
16658: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16659: } else {
16660: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16661: }
16662: }
16663: } else {
16664: if ($secchange) {
16665: $$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;
16666: } else {
16667: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16668: }
16669: }
16670: $result = $modify_section_result;
16671: } elsif ($secchange == 1) {
16672: if ($oldsec eq '') {
16673: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16674: } else {
16675: $$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;
16676: }
16677: if ($expire_role_result eq 'refused') {
16678: my $newsecurl = '/'.$cid;
16679: $newsecurl =~ s/\_/\//g;
16680: if ($sec ne '') {
16681: $newsecurl.='/'.$sec;
16682: }
16683: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16684: if ($sec eq '') {
16685: $$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;
16686: } else {
16687: $$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;
16688: }
16689: }
16690: }
16691: }
16692: } else {
16693: $$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;
16694: $result = "error: incomplete course id\n";
16695: }
16696: return $result;
16697: }
16698:
16699: sub show_role_extent {
16700: my ($scope,$context,$role) = @_;
16701: $scope =~ s{^/}{};
16702: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16703: push(@courseroles,'co');
16704: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16705: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16706: $scope =~ s{/}{_};
16707: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16708: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16709: my ($audom,$auname) = split(/\//,$scope);
16710: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16711: &Apache::loncommon::plainname($auname,$audom).'</span>');
16712: } else {
16713: $scope =~ s{/$}{};
16714: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16715: &Apache::lonnet::domain($scope,'description').'</span>');
16716: }
16717: }
16718:
16719: ############################################################
16720: ############################################################
16721:
16722: sub check_clone {
16723: my ($args,$linefeed) = @_;
16724: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16725: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16726: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16727: my $clonetitle;
16728: my @clonemsg;
16729: my $can_clone = 0;
16730: my $lctype = lc($args->{'crstype'});
16731: if ($lctype ne 'community') {
16732: $lctype = 'course';
16733: }
16734: if ($clonehome eq 'no_host') {
16735: if ($args->{'crstype'} eq 'Community') {
16736: push(@clonemsg,({
16737: mt => 'No new community created.',
16738: args => [],
16739: },
16740: {
16741: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16742: args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16743: }));
16744: } else {
16745: push(@clonemsg,({
16746: mt => 'No new course created.',
16747: args => [],
16748: },
16749: {
16750: mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16751: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16752: }));
16753: }
16754: } else {
16755: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16756: $clonetitle = $clonedesc{'description'};
16757: if ($args->{'crstype'} eq 'Community') {
16758: if ($clonedesc{'type'} ne 'Community') {
16759: push(@clonemsg,({
16760: mt => 'No new community created.',
16761: args => [],
16762: },
16763: {
16764: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16765: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16766: }));
16767: return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16768: }
16769: }
16770: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16771: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16772: $can_clone = 1;
16773: } else {
16774: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16775: $args->{'clonedomain'},$args->{'clonecourse'});
16776: if ($clonehash{'cloners'} eq '') {
16777: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16778: if ($domdefs{'canclone'}) {
16779: unless ($domdefs{'canclone'} eq 'none') {
16780: if ($domdefs{'canclone'} eq 'domain') {
16781: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16782: $can_clone = 1;
16783: }
16784: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16785: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16786: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16787: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16788: $can_clone = 1;
16789: }
16790: }
16791: }
16792: }
16793: } else {
16794: my @cloners = split(/,/,$clonehash{'cloners'});
16795: if (grep(/^\*$/,@cloners)) {
16796: $can_clone = 1;
16797: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16798: $can_clone = 1;
16799: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16800: $can_clone = 1;
16801: }
16802: unless ($can_clone) {
16803: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16804: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16805: my (%gotdomdefaults,%gotcodedefaults);
16806: foreach my $cloner (@cloners) {
16807: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16808: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16809: my (%codedefaults,@code_order);
16810: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16811: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16812: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16813: }
16814: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16815: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16816: }
16817: } else {
16818: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16819: \%codedefaults,
16820: \@code_order);
16821: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16822: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16823: }
16824: if (@code_order > 0) {
16825: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16826: $cloner,$clonehash{'internal.coursecode'},
16827: $args->{'crscode'})) {
16828: $can_clone = 1;
16829: last;
16830: }
16831: }
16832: }
16833: }
16834: }
16835: }
16836: }
16837: unless ($can_clone) {
16838: my $ccrole = 'cc';
16839: if ($args->{'crstype'} eq 'Community') {
16840: $ccrole = 'co';
16841: }
16842: my %roleshash =
16843: &Apache::lonnet::get_my_roles($args->{'ccuname'},
16844: $args->{'ccdomain'},
16845: 'userroles',['active'],[$ccrole],
16846: [$args->{'clonedomain'}]);
16847: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16848: $can_clone = 1;
16849: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16850: $args->{'ccuname'},$args->{'ccdomain'})) {
16851: $can_clone = 1;
16852: }
16853: }
16854: unless ($can_clone) {
16855: if ($args->{'crstype'} eq 'Community') {
16856: push(@clonemsg,({
16857: mt => 'No new community created.',
16858: args => [],
16859: },
16860: {
16861: 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]).',
16862: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16863: }));
16864: } else {
16865: push(@clonemsg,({
16866: mt => 'No new course created.',
16867: args => [],
16868: },
16869: {
16870: 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]).',
16871: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16872: }));
16873: }
16874: }
16875: }
16876: }
16877: return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16878: }
16879:
16880: sub construct_course {
16881: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16882: $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16883: my ($outcome,$msgref,$clonemsgref);
16884: my $linefeed = '<br />'."\n";
16885: if ($context eq 'auto') {
16886: $linefeed = "\n";
16887: }
16888:
16889: #
16890: # Are we cloning?
16891: #
16892: my ($can_clone,$cloneid,$clonehome,$clonetitle);
16893: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16894: ($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16895: if (!$can_clone) {
16896: return (0,$outcome,$clonemsgref);
16897: }
16898: }
16899:
16900: #
16901: # Open course
16902: #
16903: my $showncrstype;
16904: if ($args->{'crstype'} eq 'Placement') {
16905: $showncrstype = 'placement test';
16906: } else {
16907: $showncrstype = lc($args->{'crstype'});
16908: }
16909: my %cenv=();
16910: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16911: $args->{'cdescr'},
16912: $args->{'curl'},
16913: $args->{'course_home'},
16914: $args->{'nonstandard'},
16915: $args->{'crscode'},
16916: $args->{'ccuname'}.':'.
16917: $args->{'ccdomain'},
16918: $args->{'crstype'},
16919: $cnum,$context,$category,
16920: $callercontext);
16921:
16922: # Note: The testing routines depend on this being output; see
16923: # Utils::Course. This needs to at least be output as a comment
16924: # if anyone ever decides to not show this, and Utils::Course::new
16925: # will need to be suitably modified.
16926: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16927: $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16928: } else {
16929: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16930: }
16931: if ($$courseid =~ /^error:/) {
16932: return (0,$outcome,$clonemsgref);
16933: }
16934:
16935: #
16936: # Check if created correctly
16937: #
16938: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16939: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16940: if ($crsuhome eq 'no_host') {
16941: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16942: $outcome .= &mt_user($user_lh,
16943: 'Course creation failed, unrecognized course home server.');
16944: } else {
16945: $outcome .= &mt('Course creation failed, unrecognized course home server.');
16946: }
16947: $outcome .= $linefeed;
16948: return (0,$outcome,$clonemsgref);
16949: }
16950: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16951:
16952: #
16953: # Do the cloning
16954: #
16955: my @clonemsg;
16956: if ($can_clone && $cloneid) {
16957: push(@clonemsg,
16958: {
16959: mt => 'Created [_1] by cloning from [_2]',
16960: args => [$showncrstype,$clonetitle],
16961: });
16962: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16963: # Copy all files
16964: my @info =
16965: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16966: $args->{'dateshift'},$args->{'crscode'},
16967: $args->{'ccuname'}.':'.$args->{'ccdomain'},
16968: $args->{'tinyurls'});
16969: if (@info) {
16970: push(@clonemsg,@info);
16971: }
16972: # Restore URL
16973: $cenv{'url'}=$oldcenv{'url'};
16974: # Restore title
16975: $cenv{'description'}=$oldcenv{'description'};
16976: # Restore creation date, creator and creation context.
16977: $cenv{'internal.created'}=$oldcenv{'internal.created'};
16978: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16979: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16980: # Mark as cloned
16981: $cenv{'clonedfrom'}=$cloneid;
16982: # Need to clone grading mode
16983: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16984: $cenv{'grading'}=$newenv{'grading'};
16985: # Do not clone these environment entries
16986: &Apache::lonnet::del('environment',
16987: ['default_enrollment_start_date',
16988: 'default_enrollment_end_date',
16989: 'question.email',
16990: 'policy.email',
16991: 'comment.email',
16992: 'pch.users.denied',
16993: 'plc.users.denied',
16994: 'hidefromcat',
16995: 'checkforpriv',
16996: 'categories'],
16997: $$crsudom,$$crsunum);
16998: if ($args->{'textbook'}) {
16999: $cenv{'internal.textbook'} = $args->{'textbook'};
17000: }
17001: }
17002:
17003: #
17004: # Set environment (will override cloned, if existing)
17005: #
17006: my @sections = ();
17007: my @xlists = ();
17008: if ($args->{'crstype'}) {
17009: $cenv{'type'}=$args->{'crstype'};
17010: }
17011: if ($args->{'lti'}) {
17012: $cenv{'internal.lti'}=$args->{'lti'};
17013: }
17014: if ($args->{'crsid'}) {
17015: $cenv{'courseid'}=$args->{'crsid'};
17016: }
17017: if ($args->{'crscode'}) {
17018: $cenv{'internal.coursecode'}=$args->{'crscode'};
17019: }
17020: if ($args->{'crsquota'} ne '') {
17021: $cenv{'internal.coursequota'}=$args->{'crsquota'};
17022: } else {
17023: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17024: }
17025: if ($args->{'ccuname'}) {
17026: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17027: ':'.$args->{'ccdomain'};
17028: } else {
17029: $cenv{'internal.courseowner'} = $args->{'curruser'};
17030: }
17031: if ($args->{'defaultcredits'}) {
17032: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17033: }
17034: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17035: if ($args->{'crssections'}) {
17036: $cenv{'internal.sectionnums'} = '';
17037: if ($args->{'crssections'} =~ m/,/) {
17038: @sections = split/,/,$args->{'crssections'};
17039: } else {
17040: $sections[0] = $args->{'crssections'};
17041: }
17042: if (@sections > 0) {
17043: foreach my $item (@sections) {
17044: my ($sec,$gp) = split/:/,$item;
17045: my $class = $args->{'crscode'}.$sec;
17046: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17047: $cenv{'internal.sectionnums'} .= $item.',';
17048: unless ($addcheck eq 'ok') {
17049: push(@badclasses,$class);
17050: }
17051: }
17052: $cenv{'internal.sectionnums'} =~ s/,$//;
17053: }
17054: }
17055: # do not hide course coordinator from staff listing,
17056: # even if privileged
17057: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17058: # add course coordinator's domain to domains to check for privileged users
17059: # if different to course domain
17060: if ($$crsudom ne $args->{'ccdomain'}) {
17061: $cenv{'checkforpriv'} = $args->{'ccdomain'};
17062: }
17063: # add crosslistings
17064: if ($args->{'crsxlist'}) {
17065: $cenv{'internal.crosslistings'}='';
17066: if ($args->{'crsxlist'} =~ m/,/) {
17067: @xlists = split/,/,$args->{'crsxlist'};
17068: } else {
17069: $xlists[0] = $args->{'crsxlist'};
17070: }
17071: if (@xlists > 0) {
17072: foreach my $item (@xlists) {
17073: my ($xl,$gp) = split/:/,$item;
17074: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17075: $cenv{'internal.crosslistings'} .= $item.',';
17076: unless ($addcheck eq 'ok') {
17077: push(@badclasses,$xl);
17078: }
17079: }
17080: $cenv{'internal.crosslistings'} =~ s/,$//;
17081: }
17082: }
17083: if ($args->{'autoadds'}) {
17084: $cenv{'internal.autoadds'}=$args->{'autoadds'};
17085: }
17086: if ($args->{'autodrops'}) {
17087: $cenv{'internal.autodrops'}=$args->{'autodrops'};
17088: }
17089: # check for notification of enrollment changes
17090: my @notified = ();
17091: if ($args->{'notify_owner'}) {
17092: if ($args->{'ccuname'} ne '') {
17093: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17094: }
17095: }
17096: if ($args->{'notify_dc'}) {
17097: if ($uname ne '') {
17098: push(@notified,$uname.':'.$udom);
17099: }
17100: }
17101: if (@notified > 0) {
17102: my $notifylist;
17103: if (@notified > 1) {
17104: $notifylist = join(',',@notified);
17105: } else {
17106: $notifylist = $notified[0];
17107: }
17108: $cenv{'internal.notifylist'} = $notifylist;
17109: }
17110: if (@badclasses > 0) {
17111: my %lt=&Apache::lonlocal::texthash(
17112: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17113: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17114: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17115: );
17116: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17117: &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'};
17118: if ($context eq 'auto') {
17119: $outcome .= $badclass_msg.$linefeed;
17120: } else {
17121: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17122: }
17123: foreach my $item (@badclasses) {
17124: if ($context eq 'auto') {
17125: $outcome .= " - $item\n";
17126: } else {
17127: $outcome .= "<li>$item</li>\n";
17128: }
17129: }
17130: if ($context eq 'auto') {
17131: $outcome .= $linefeed;
17132: } else {
17133: $outcome .= "</ul><br /><br /></div>\n";
17134: }
17135: }
17136: if ($args->{'no_end_date'}) {
17137: $args->{'endaccess'} = 0;
17138: }
17139: $cenv{'internal.autostart'}=$args->{'enrollstart'};
17140: $cenv{'internal.autoend'}=$args->{'enrollend'};
17141: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17142: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17143: if ($args->{'showphotos'}) {
17144: $cenv{'internal.showphotos'}=$args->{'showphotos'};
17145: }
17146: $cenv{'internal.authtype'} = $args->{'authtype'};
17147: $cenv{'internal.autharg'} = $args->{'autharg'};
17148: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17149: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
17150: 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');
17151: if ($context eq 'auto') {
17152: $outcome .= $krb_msg;
17153: } else {
17154: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17155: }
17156: $outcome .= $linefeed;
17157: }
17158: }
17159: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17160: if ($args->{'setpolicy'}) {
17161: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17162: }
17163: if ($args->{'setcontent'}) {
17164: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17165: }
17166: if ($args->{'setcomment'}) {
17167: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17168: }
17169: }
17170: if ($args->{'reshome'}) {
17171: $cenv{'reshome'}=$args->{'reshome'}.'/';
17172: $cenv{'reshome'}=~s/\/+$/\//;
17173: }
17174: #
17175: # course has keyed access
17176: #
17177: if ($args->{'setkeys'}) {
17178: $cenv{'keyaccess'}='yes';
17179: }
17180: # if specified, key authority is not course, but user
17181: # only active if keyaccess is yes
17182: if ($args->{'keyauth'}) {
17183: my ($user,$domain) = split(':',$args->{'keyauth'});
17184: $user = &LONCAPA::clean_username($user);
17185: $domain = &LONCAPA::clean_username($domain);
17186: if ($user ne '' && $domain ne '') {
17187: $cenv{'keyauth'}=$user.':'.$domain;
17188: }
17189: }
17190:
17191: #
17192: # generate and store uniquecode (available to course requester), if course should have one.
17193: #
17194: if ($args->{'uniquecode'}) {
17195: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17196: if ($code) {
17197: $cenv{'internal.uniquecode'} = $code;
17198: my %crsinfo =
17199: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17200: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17201: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17202: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17203: }
17204: if (ref($coderef)) {
17205: $$coderef = $code;
17206: }
17207: }
17208: }
17209:
17210: if ($args->{'disresdis'}) {
17211: $cenv{'pch.roles.denied'}='st';
17212: }
17213: if ($args->{'disablechat'}) {
17214: $cenv{'plc.roles.denied'}='st';
17215: }
17216:
17217: # Record we've not yet viewed the Course Initialization Helper for this
17218: # course
17219: $cenv{'course.helper.not.run'} = 1;
17220: #
17221: # Use new Randomseed
17222: #
17223: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17224: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17225: #
17226: # The encryption code and receipt prefix for this course
17227: #
17228: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17229: $cenv{'internal.encpref'}=100+int(9*rand(99));
17230: #
17231: # By default, use standard grading
17232: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17233:
17234: $outcome .= $linefeed.&mt('Setting environment').': '.
17235: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17236: #
17237: # Open all assignments
17238: #
17239: if ($args->{'openall'}) {
17240: my $opendate = time;
17241: if ($args->{'openallfrom'} =~ /^\d+$/) {
17242: $opendate = $args->{'openallfrom'};
17243: }
17244: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17245: my %storecontent = ($storeunder => $opendate,
17246: $storeunder.'.type' => 'date_start');
17247: $outcome .= &mt('All assignments open starting [_1]',
17248: &Apache::lonlocal::locallocaltime($opendate)).': '.
17249: &Apache::lonnet::cput
17250: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17251: }
17252: #
17253: # Set first page
17254: #
17255: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17256: || ($cloneid)) {
17257: $outcome .= &mt('Setting first resource').': ';
17258:
17259: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17260: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17261:
17262: $outcome .= ($fatal?$errtext:'read ok').' - ';
17263: my $title; my $url;
17264: if ($args->{'firstres'} eq 'syl') {
17265: $title=&mt('Syllabus');
17266: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17267: } else {
17268: $title=&mt('Table of Contents');
17269: $url='/adm/navmaps';
17270: }
17271:
17272: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17273: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17274:
17275: if ($errtext) { $fatal=2; }
17276: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17277: }
17278:
17279: #
17280: # Set params for Placement Tests
17281: #
17282: if ($args->{'crstype'} eq 'Placement') {
17283: my %storecontent;
17284: my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17285: my %defaults = (
17286: buttonshide => { value => 'yes',
17287: type => 'string_yesno',},
17288: type => { value => 'randomizetry',
17289: type => 'string_questiontype',},
17290: maxtries => { value => 1,
17291: type => 'int_pos',},
17292: problemstatus => { value => 'no',
17293: type => 'string_problemstatus',},
17294: );
17295: foreach my $key (keys(%defaults)) {
17296: $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17297: $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17298: }
17299: &Apache::lonnet::cput
17300: ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
17301: }
17302:
17303: return (1,$outcome,\@clonemsg);
17304: }
17305:
17306: sub make_unique_code {
17307: my ($cdom,$cnum) = @_;
17308: # get lock on uniquecodes db
17309: my $lockhash = {
17310: $cnum."\0".'uniquecodes' => $env{'user.name'}.
17311: ':'.$env{'user.domain'},
17312: };
17313: my $tries = 0;
17314: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17315: my ($code,$error);
17316:
17317: while (($gotlock ne 'ok') && ($tries<3)) {
17318: $tries ++;
17319: sleep 1;
17320: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17321: }
17322: if ($gotlock eq 'ok') {
17323: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17324: my $gotcode;
17325: my $attempts = 0;
17326: while ((!$gotcode) && ($attempts < 100)) {
17327: $code = &generate_code();
17328: if (!exists($currcodes{$code})) {
17329: $gotcode = 1;
17330: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17331: $error = 'nostore';
17332: }
17333: }
17334: $attempts ++;
17335: }
17336: my @del_lock = ($cnum."\0".'uniquecodes');
17337: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17338: } else {
17339: $error = 'nolock';
17340: }
17341: return ($code,$error);
17342: }
17343:
17344: sub generate_code {
17345: my $code;
17346: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17347: for (my $i=0; $i<6; $i++) {
17348: my $lettnum = int (rand 2);
17349: my $item = '';
17350: if ($lettnum) {
17351: $item = $letts[int( rand(18) )];
17352: } else {
17353: $item = 1+int( rand(8) );
17354: }
17355: $code .= $item;
17356: }
17357: return $code;
17358: }
17359:
17360: ############################################################
17361: ############################################################
17362:
17363: # Community, Course and Placement Test
17364: sub course_type {
17365: my ($cid) = @_;
17366: if (!defined($cid)) {
17367: $cid = $env{'request.course.id'};
17368: }
17369: if (defined($env{'course.'.$cid.'.type'})) {
17370: return $env{'course.'.$cid.'.type'};
17371: } else {
17372: return 'Course';
17373: }
17374: }
17375:
17376: sub group_term {
17377: my $crstype = &course_type();
17378: my %names = (
17379: 'Course' => 'group',
17380: 'Community' => 'group',
17381: 'Placement' => 'group',
17382: );
17383: return $names{$crstype};
17384: }
17385:
17386: sub course_types {
17387: my @types = ('official','unofficial','community','textbook','placement','lti');
17388: my %typename = (
17389: official => 'Official course',
17390: unofficial => 'Unofficial course',
17391: community => 'Community',
17392: textbook => 'Textbook course',
17393: placement => 'Placement test',
17394: lti => 'LTI provider',
17395: );
17396: return (\@types,\%typename);
17397: }
17398:
17399: sub icon {
17400: my ($file)=@_;
17401: my $curfext = lc((split(/\./,$file))[-1]);
17402: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17403: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17404: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17405: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17406: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17407: $curfext.".gif") {
17408: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17409: $curfext.".gif";
17410: }
17411: }
17412: return &lonhttpdurl($iconname);
17413: }
17414:
17415: sub lonhttpdurl {
17416: #
17417: # Had been used for "small fry" static images on separate port 8080.
17418: # Modify here if lightweight http functionality desired again.
17419: # Currently eliminated due to increasing firewall issues.
17420: #
17421: my ($url)=@_;
17422: return $url;
17423: }
17424:
17425: sub connection_aborted {
17426: my ($r)=@_;
17427: $r->print(" ");$r->rflush();
17428: my $c = $r->connection;
17429: return $c->aborted();
17430: }
17431:
17432: # Escapes strings that may have embedded 's that will be put into
17433: # strings as 'strings'.
17434: sub escape_single {
17435: my ($input) = @_;
17436: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
17437: $input =~ s/\'/\\\'/g; # Esacpe the 's....
17438: return $input;
17439: }
17440:
17441: # Same as escape_single, but escape's "'s This
17442: # can be used for "strings"
17443: sub escape_double {
17444: my ($input) = @_;
17445: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
17446: $input =~ s/\"/\\\"/g; # Esacpe the "s....
17447: return $input;
17448: }
17449:
17450: # Escapes the last element of a full URL.
17451: sub escape_url {
17452: my ($url) = @_;
17453: my @urlslices = split(/\//, $url,-1);
17454: my $lastitem = &escape(pop(@urlslices));
17455: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17456: }
17457:
17458: sub compare_arrays {
17459: my ($arrayref1,$arrayref2) = @_;
17460: my (@difference,%count);
17461: @difference = ();
17462: %count = ();
17463: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17464: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17465: foreach my $element (keys(%count)) {
17466: if ($count{$element} == 1) {
17467: push(@difference,$element);
17468: }
17469: }
17470: }
17471: return @difference;
17472: }
17473:
17474: sub lon_status_items {
17475: my %defaults = (
17476: E => 100,
17477: W => 4,
17478: N => 1,
17479: U => 5,
17480: threshold => 200,
17481: sysmail => 2500,
17482: );
17483: my %names = (
17484: E => 'Errors',
17485: W => 'Warnings',
17486: N => 'Notices',
17487: U => 'Unsent',
17488: );
17489: return (\%defaults,\%names);
17490: }
17491:
17492: # -------------------------------------------------------- Initialize user login
17493: sub init_user_environment {
17494: my ($r, $username, $domain, $authhost, $form, $args) = @_;
17495: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17496:
17497: my $public=($username eq 'public' && $domain eq 'public');
17498:
17499: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17500: my $now=time;
17501:
17502: if ($public) {
17503: my $max_public=100;
17504: my $oldest;
17505: my $oldest_time=0;
17506: for(my $next=1;$next<=$max_public;$next++) {
17507: if (-e $lonids."/publicuser_$next.id") {
17508: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17509: if ($mtime<$oldest_time || !$oldest_time) {
17510: $oldest_time=$mtime;
17511: $oldest=$next;
17512: }
17513: } else {
17514: $cookie="publicuser_$next";
17515: last;
17516: }
17517: }
17518: if (!$cookie) { $cookie="publicuser_$oldest"; }
17519: } else {
17520: # See if old ID present, if so, remove if this isn't a robot,
17521: # killing any existing non-robot sessions
17522: if (!$args->{'robot'}) {
17523: opendir(DIR,$lonids);
17524: while ($filename=readdir(DIR)) {
17525: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17526: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17527: &GDBM_READER(),0640)) {
17528: my $linkedfile;
17529: if (exists($oldenv{'user.linkedenv'})) {
17530: $linkedfile = $oldenv{'user.linkedenv'};
17531: }
17532: untie(%oldenv);
17533: if (unlink("$lonids/$filename")) {
17534: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17535: if (-l "$lonids/$linkedfile.id") {
17536: unlink("$lonids/$linkedfile.id");
17537: }
17538: }
17539: }
17540: } else {
17541: unlink($lonids.'/'.$filename);
17542: }
17543: }
17544: }
17545: closedir(DIR);
17546: # If there is a undeleted lockfile for the user's paste buffer remove it.
17547: my $namespace = 'nohist_courseeditor';
17548: my $lockingkey = 'paste'."\0".'locked_num';
17549: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17550: $domain,$username);
17551: if (exists($lockhash{$lockingkey})) {
17552: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17553: unless ($delresult eq 'ok') {
17554: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17555: }
17556: }
17557: }
17558: # Give them a new cookie
17559: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17560: : $now.$$.int(rand(10000)));
17561: $cookie="$username\_$id\_$domain\_$authhost";
17562:
17563: # Initialize roles
17564:
17565: ($userroles,$firstaccenv,$timerintenv) =
17566: &Apache::lonnet::rolesinit($domain,$username,$authhost);
17567: }
17568: # ------------------------------------ Check browser type and MathML capability
17569:
17570: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17571: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17572:
17573: # ------------------------------------------------------------- Get environment
17574:
17575: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17576: my ($tmp) = keys(%userenv);
17577: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17578: undef(%userenv);
17579: }
17580: if (($userenv{'interface'}) && (!$form->{'interface'})) {
17581: $form->{'interface'}=$userenv{'interface'};
17582: }
17583: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17584:
17585: # --------------- Do not trust query string to be put directly into environment
17586: foreach my $option ('interface','localpath','localres') {
17587: $form->{$option}=~s/[\n\r\=]//gs;
17588: }
17589: # --------------------------------------------------------- Write first profile
17590:
17591: {
17592: my $ip = &Apache::lonnet::get_requestor_ip($r);
17593: my %initial_env =
17594: ("user.name" => $username,
17595: "user.domain" => $domain,
17596: "user.home" => $authhost,
17597: "browser.type" => $clientbrowser,
17598: "browser.version" => $clientversion,
17599: "browser.mathml" => $clientmathml,
17600: "browser.unicode" => $clientunicode,
17601: "browser.os" => $clientos,
17602: "browser.mobile" => $clientmobile,
17603: "browser.info" => $clientinfo,
17604: "browser.osversion" => $clientosversion,
17605: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
17606: "request.course.fn" => '',
17607: "request.course.uri" => '',
17608: "request.course.sec" => '',
17609: "request.role" => 'cm',
17610: "request.role.adv" => $env{'user.adv'},
17611: "request.host" => $ip,);
17612:
17613: if ($form->{'localpath'}) {
17614: $initial_env{"browser.localpath"} = $form->{'localpath'};
17615: $initial_env{"browser.localres"} = $form->{'localres'};
17616: }
17617:
17618: if ($form->{'interface'}) {
17619: $form->{'interface'}=~s/\W//gs;
17620: $initial_env{"browser.interface"} = $form->{'interface'};
17621: $env{'browser.interface'}=$form->{'interface'};
17622: }
17623:
17624: if ($form->{'iptoken'}) {
17625: my $lonhost = $r->dir_config('lonHostID');
17626: $initial_env{"user.noloadbalance"} = $lonhost;
17627: $env{'user.noloadbalance'} = $lonhost;
17628: }
17629:
17630: if ($form->{'noloadbalance'}) {
17631: my @hosts = &Apache::lonnet::current_machine_ids();
17632: my $hosthere = $form->{'noloadbalance'};
17633: if (grep(/^\Q$hosthere\E$/,@hosts)) {
17634: $initial_env{"user.noloadbalance"} = $hosthere;
17635: $env{'user.noloadbalance'} = $hosthere;
17636: }
17637: }
17638:
17639: unless ($domain eq 'public') {
17640: my %is_adv = ( is_adv => $env{'user.adv'} );
17641: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17642:
17643: foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17644: $userenv{'availabletools.'.$tool} =
17645: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17646: undef,\%userenv,\%domdef,\%is_adv);
17647: }
17648:
17649: foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17650: $userenv{'canrequest.'.$crstype} =
17651: &Apache::lonnet::usertools_access($username,$domain,$crstype,
17652: 'reload','requestcourses',
17653: \%userenv,\%domdef,\%is_adv);
17654: }
17655:
17656: $userenv{'canrequest.author'} =
17657: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17658: 'reload','requestauthor',
17659: \%userenv,\%domdef,\%is_adv);
17660: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17661: $domain,$username);
17662: my $reqstatus = $reqauthor{'author_status'};
17663: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
17664: if (ref($reqauthor{'author'}) eq 'HASH') {
17665: $userenv{'requestauthorqueued'} = $reqstatus.':'.
17666: $reqauthor{'author'}{'timestamp'};
17667: }
17668: }
17669: my ($types,$typename) = &course_types();
17670: if (ref($types) eq 'ARRAY') {
17671: my @options = ('approval','validate','autolimit');
17672: my $optregex = join('|',@options);
17673: my (%willtrust,%trustchecked);
17674: foreach my $type (@{$types}) {
17675: my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17676: if ($dom_str ne '') {
17677: my $updatedstr = '';
17678: my @possdomains = split(',',$dom_str);
17679: foreach my $entry (@possdomains) {
17680: my ($extdom,$extopt) = split(':',$entry);
17681: unless ($trustchecked{$extdom}) {
17682: $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17683: $trustchecked{$extdom} = 1;
17684: }
17685: if ($willtrust{$extdom}) {
17686: $updatedstr .= $entry.',';
17687: }
17688: }
17689: $updatedstr =~ s/,$//;
17690: if ($updatedstr) {
17691: $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17692: } else {
17693: delete($userenv{'reqcrsotherdom.'.$type});
17694: }
17695: }
17696: }
17697: }
17698: }
17699: $env{'user.environment'} = "$lonids/$cookie.id";
17700:
17701: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17702: &GDBM_WRCREAT(),0640)) {
17703: &_add_to_env(\%disk_env,\%initial_env);
17704: &_add_to_env(\%disk_env,\%userenv,'environment.');
17705: &_add_to_env(\%disk_env,$userroles);
17706: if (ref($firstaccenv) eq 'HASH') {
17707: &_add_to_env(\%disk_env,$firstaccenv);
17708: }
17709: if (ref($timerintenv) eq 'HASH') {
17710: &_add_to_env(\%disk_env,$timerintenv);
17711: }
17712: if (ref($args->{'extra_env'})) {
17713: &_add_to_env(\%disk_env,$args->{'extra_env'});
17714: }
17715: untie(%disk_env);
17716: } else {
17717: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17718: 'Could not create environment storage in lonauth: '.$!.'</span>');
17719: return 'error: '.$!;
17720: }
17721: }
17722: $env{'request.role'}='cm';
17723: $env{'request.role.adv'}=$env{'user.adv'};
17724: $env{'browser.type'}=$clientbrowser;
17725:
17726: return $cookie;
17727:
17728: }
17729:
17730: sub _add_to_env {
17731: my ($idf,$env_data,$prefix) = @_;
17732: if (ref($env_data) eq 'HASH') {
17733: while (my ($key,$value) = each(%$env_data)) {
17734: $idf->{$prefix.$key} = $value;
17735: $env{$prefix.$key} = $value;
17736: }
17737: }
17738: }
17739:
17740: # --- Get the symbolic name of a problem and the url
17741: sub get_symb {
17742: my ($request,$silent) = @_;
17743: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17744: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17745: if ($symb eq '') {
17746: if (!$silent) {
17747: if (ref($request)) {
17748: $request->print("Unable to handle ambiguous references:$url:.");
17749: }
17750: return ();
17751: }
17752: }
17753: &Apache::lonenc::check_decrypt(\$symb);
17754: return ($symb);
17755: }
17756:
17757: # --------------------------------------------------------------Get annotation
17758:
17759: sub get_annotation {
17760: my ($symb,$enc) = @_;
17761:
17762: my $key = $symb;
17763: if (!$enc) {
17764: $key =
17765: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17766: }
17767: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17768: return $annotation{$key};
17769: }
17770:
17771: sub clean_symb {
17772: my ($symb,$delete_enc) = @_;
17773:
17774: &Apache::lonenc::check_decrypt(\$symb);
17775: my $enc = $env{'request.enc'};
17776: if ($delete_enc) {
17777: delete($env{'request.enc'});
17778: }
17779:
17780: return ($symb,$enc);
17781: }
17782:
17783: ############################################################
17784: ############################################################
17785:
17786: =pod
17787:
17788: =head1 Routines for building display used to search for courses
17789:
17790:
17791: =over 4
17792:
17793: =item * &build_filters()
17794:
17795: Create markup for a table used to set filters to use when selecting
17796: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
17797: and quotacheck.pl
17798:
17799:
17800: Inputs:
17801:
17802: filterlist - anonymous array of fields to include as potential filters
17803:
17804: crstype - course type
17805:
17806: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17807: to pop-open a course selector (will contain "extra element").
17808:
17809: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17810:
17811: filter - anonymous hash of criteria and their values
17812:
17813: action - form action
17814:
17815: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17816:
17817: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17818:
17819: cloneruname - username of owner of new course who wants to clone
17820:
17821: clonerudom - domain of owner of new course who wants to clone
17822:
17823: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
17824:
17825: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17826:
17827: codedom - domain
17828:
17829: formname - value of form element named "form".
17830:
17831: fixeddom - domain, if fixed.
17832:
17833: prevphase - value to assign to form element named "phase" when going back to the previous screen
17834:
17835: cnameelement - name of form element in form on opener page which will receive title of selected course
17836:
17837: cnumelement - name of form element in form on opener page which will receive courseID of selected course
17838:
17839: cdomelement - name of form element in form on opener page which will receive domain of selected course
17840:
17841: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17842:
17843: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17844:
17845: clonewarning - warning message about missing information for intended course owner when DC creates a course
17846:
17847:
17848: Returns: $output - HTML for display of search criteria, and hidden form elements.
17849:
17850:
17851: Side Effects: None
17852:
17853: =cut
17854:
17855: # ---------------------------------------------- search for courses based on last activity etc.
17856:
17857: sub build_filters {
17858: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17859: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17860: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17861: $cnameelement,$cnumelement,$cdomelement,$setroles,
17862: $clonetext,$clonewarning) = @_;
17863: my ($list,$jscript);
17864: my $onchange = 'javascript:updateFilters(this)';
17865: my ($domainselectform,$sincefilterform,$createdfilterform,
17866: $ownerdomselectform,$persondomselectform,$instcodeform,
17867: $typeselectform,$instcodetitle);
17868: if ($formname eq '') {
17869: $formname = $caller;
17870: }
17871: foreach my $item (@{$filterlist}) {
17872: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17873: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17874: if ($item eq 'domainfilter') {
17875: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17876: } elsif ($item eq 'coursefilter') {
17877: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17878: } elsif ($item eq 'ownerfilter') {
17879: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17880: } elsif ($item eq 'ownerdomfilter') {
17881: $filter->{'ownerdomfilter'} =
17882: &LONCAPA::clean_domain($filter->{$item});
17883: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17884: 'ownerdomfilter',1);
17885: } elsif ($item eq 'personfilter') {
17886: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17887: } elsif ($item eq 'persondomfilter') {
17888: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17889: 'persondomfilter',1);
17890: } else {
17891: $filter->{$item} =~ s/\W//g;
17892: }
17893: if (!$filter->{$item}) {
17894: $filter->{$item} = '';
17895: }
17896: }
17897: if ($item eq 'domainfilter') {
17898: my $allow_blank = 1;
17899: if ($formname eq 'portform') {
17900: $allow_blank=0;
17901: } elsif ($formname eq 'studentform') {
17902: $allow_blank=0;
17903: }
17904: if ($fixeddom) {
17905: $domainselectform = '<input type="hidden" name="domainfilter"'.
17906: ' value="'.$codedom.'" />'.
17907: &Apache::lonnet::domain($codedom,'description');
17908: } else {
17909: $domainselectform = &select_dom_form($filter->{$item},
17910: 'domainfilter',
17911: $allow_blank,'',$onchange);
17912: }
17913: } else {
17914: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17915: }
17916: }
17917:
17918: # last course activity filter and selection
17919: $sincefilterform = &timebased_select_form('sincefilter',$filter);
17920:
17921: # course created filter and selection
17922: if (exists($filter->{'createdfilter'})) {
17923: $createdfilterform = &timebased_select_form('createdfilter',$filter);
17924: }
17925:
17926: my $prefix = $crstype;
17927: if ($crstype eq 'Placement') {
17928: $prefix = 'Placement Test'
17929: }
17930: my %lt = &Apache::lonlocal::texthash(
17931: 'cac' => "$prefix Activity",
17932: 'ccr' => "$prefix Created",
17933: 'cde' => "$prefix Title",
17934: 'cdo' => "$prefix Domain",
17935: 'ins' => 'Institutional Code',
17936: 'inc' => 'Institutional Categorization',
17937: 'cow' => "$prefix Owner/Co-owner",
17938: 'cop' => "$prefix Personnel Includes",
17939: 'cog' => 'Type',
17940: );
17941:
17942: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17943: my $typeval = 'Course';
17944: if ($crstype eq 'Community') {
17945: $typeval = 'Community';
17946: } elsif ($crstype eq 'Placement') {
17947: $typeval = 'Placement';
17948: }
17949: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17950: } else {
17951: $typeselectform = '<select name="type" size="1"';
17952: if ($onchange) {
17953: $typeselectform .= ' onchange="'.$onchange.'"';
17954: }
17955: $typeselectform .= '>'."\n";
17956: foreach my $posstype ('Course','Community','Placement') {
17957: my $shown;
17958: if ($posstype eq 'Placement') {
17959: $shown = &mt('Placement Test');
17960: } else {
17961: $shown = &mt($posstype);
17962: }
17963: $typeselectform.='<option value="'.$posstype.'"'.
17964: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17965: }
17966: $typeselectform.="</select>";
17967: }
17968:
17969: my ($cloneableonlyform,$cloneabletitle);
17970: if (exists($filter->{'cloneableonly'})) {
17971: my $cloneableon = '';
17972: my $cloneableoff = ' checked="checked"';
17973: if ($filter->{'cloneableonly'}) {
17974: $cloneableon = $cloneableoff;
17975: $cloneableoff = '';
17976: }
17977: $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>';
17978: if ($formname eq 'ccrs') {
17979: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17980: } else {
17981: $cloneabletitle = &mt('Cloneable by you');
17982: }
17983: }
17984: my $officialjs;
17985: if ($crstype eq 'Course') {
17986: if (exists($filter->{'instcodefilter'})) {
17987: # if (($fixeddom) || ($formname eq 'requestcrs') ||
17988: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17989: if ($codedom) {
17990: $officialjs = 1;
17991: ($instcodeform,$jscript,$$numtitlesref) =
17992: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17993: $officialjs,$codetitlesref);
17994: if ($jscript) {
17995: $jscript = '<script type="text/javascript">'."\n".
17996: '// <![CDATA['."\n".
17997: $jscript."\n".
17998: '// ]]>'."\n".
17999: '</script>'."\n";
18000: }
18001: }
18002: if ($instcodeform eq '') {
18003: $instcodeform =
18004: '<input type="text" name="instcodefilter" size="10" value="'.
18005: $list->{'instcodefilter'}.'" />';
18006: $instcodetitle = $lt{'ins'};
18007: } else {
18008: $instcodetitle = $lt{'inc'};
18009: }
18010: if ($fixeddom) {
18011: $instcodetitle .= '<br />('.$codedom.')';
18012: }
18013: }
18014: }
18015: my $output = qq|
18016: <form method="post" name="filterpicker" action="$action">
18017: <input type="hidden" name="form" value="$formname" />
18018: |;
18019: if ($formname eq 'modifycourse') {
18020: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18021: '<input type="hidden" name="prevphase" value="'.
18022: $prevphase.'" />'."\n";
18023: } elsif ($formname eq 'quotacheck') {
18024: $output .= qq|
18025: <input type="hidden" name="sortby" value="" />
18026: <input type="hidden" name="sortorder" value="" />
18027: |;
18028: } else {
18029: my $name_input;
18030: if ($cnameelement ne '') {
18031: $name_input = '<input type="hidden" name="cnameelement" value="'.
18032: $cnameelement.'" />';
18033: }
18034: $output .= qq|
18035: <input type="hidden" name="cnumelement" value="$cnumelement" />
18036: <input type="hidden" name="cdomelement" value="$cdomelement" />
18037: $name_input
18038: $roleelement
18039: $multelement
18040: $typeelement
18041: |;
18042: if ($formname eq 'portform') {
18043: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18044: }
18045: }
18046: if ($fixeddom) {
18047: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18048: }
18049: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18050: if ($sincefilterform) {
18051: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18052: .$sincefilterform
18053: .&Apache::lonhtmlcommon::row_closure();
18054: }
18055: if ($createdfilterform) {
18056: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18057: .$createdfilterform
18058: .&Apache::lonhtmlcommon::row_closure();
18059: }
18060: if ($domainselectform) {
18061: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18062: .$domainselectform
18063: .&Apache::lonhtmlcommon::row_closure();
18064: }
18065: if ($typeselectform) {
18066: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18067: $output .= $typeselectform;
18068: } else {
18069: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18070: .$typeselectform
18071: .&Apache::lonhtmlcommon::row_closure();
18072: }
18073: }
18074: if ($instcodeform) {
18075: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18076: .$instcodeform
18077: .&Apache::lonhtmlcommon::row_closure();
18078: }
18079: if (exists($filter->{'ownerfilter'})) {
18080: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18081: '<table><tr><td>'.&mt('Username').'<br />'.
18082: '<input type="text" name="ownerfilter" size="20" value="'.
18083: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18084: $ownerdomselectform.'</td></tr></table>'.
18085: &Apache::lonhtmlcommon::row_closure();
18086: }
18087: if (exists($filter->{'personfilter'})) {
18088: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18089: '<table><tr><td>'.&mt('Username').'<br />'.
18090: '<input type="text" name="personfilter" size="20" value="'.
18091: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18092: $persondomselectform.'</td></tr></table>'.
18093: &Apache::lonhtmlcommon::row_closure();
18094: }
18095: if (exists($filter->{'coursefilter'})) {
18096: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18097: .'<input type="text" name="coursefilter" size="25" value="'
18098: .$list->{'coursefilter'}.'" />'
18099: .&Apache::lonhtmlcommon::row_closure();
18100: }
18101: if ($cloneableonlyform) {
18102: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18103: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18104: }
18105: if (exists($filter->{'descriptfilter'})) {
18106: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18107: .'<input type="text" name="descriptfilter" size="40" value="'
18108: .$list->{'descriptfilter'}.'" />'
18109: .&Apache::lonhtmlcommon::row_closure(1);
18110: }
18111: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18112: '<input type="hidden" name="updater" value="" />'."\n".
18113: '<input type="submit" name="gosearch" value="'.
18114: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18115: return $jscript.$clonewarning.$output;
18116: }
18117:
18118: =pod
18119:
18120: =item * &timebased_select_form()
18121:
18122: Create markup for a dropdown list used to select a time-based
18123: filter e.g., Course Activity, Course Created, when searching for courses
18124: or communities
18125:
18126: Inputs:
18127:
18128: item - name of form element (sincefilter or createdfilter)
18129:
18130: filter - anonymous hash of criteria and their values
18131:
18132: Returns: HTML for a select box contained a blank, then six time selections,
18133: with value set in incoming form variables currently selected.
18134:
18135: Side Effects: None
18136:
18137: =cut
18138:
18139: sub timebased_select_form {
18140: my ($item,$filter) = @_;
18141: if (ref($filter) eq 'HASH') {
18142: $filter->{$item} =~ s/[^\d-]//g;
18143: if (!$filter->{$item}) { $filter->{$item}=-1; }
18144: return &select_form(
18145: $filter->{$item},
18146: $item,
18147: { '-1' => '',
18148: '86400' => &mt('today'),
18149: '604800' => &mt('last week'),
18150: '2592000' => &mt('last month'),
18151: '7776000' => &mt('last three months'),
18152: '15552000' => &mt('last six months'),
18153: '31104000' => &mt('last year'),
18154: 'select_form_order' =>
18155: ['-1','86400','604800','2592000','7776000',
18156: '15552000','31104000']});
18157: }
18158: }
18159:
18160: =pod
18161:
18162: =item * &js_changer()
18163:
18164: Create script tag containing Javascript used to submit course search form
18165: when course type or domain is changed, and also to hide 'Searching ...' on
18166: page load completion for page showing search result.
18167:
18168: Inputs: None
18169:
18170: Returns: markup containing updateFilters() and hideSearching() javascript functions.
18171:
18172: Side Effects: None
18173:
18174: =cut
18175:
18176: sub js_changer {
18177: return <<ENDJS;
18178: <script type="text/javascript">
18179: // <![CDATA[
18180: function updateFilters(caller) {
18181: if (typeof(caller) != "undefined") {
18182: document.filterpicker.updater.value = caller.name;
18183: }
18184: document.filterpicker.submit();
18185: }
18186:
18187: function hideSearching() {
18188: if (document.getElementById('searching')) {
18189: document.getElementById('searching').style.display = 'none';
18190: }
18191: return;
18192: }
18193:
18194: // ]]>
18195: </script>
18196:
18197: ENDJS
18198: }
18199:
18200: =pod
18201:
18202: =item * &search_courses()
18203:
18204: Process selected filters form course search form and pass to lonnet::courseiddump
18205: to retrieve a hash for which keys are courseIDs which match the selected filters.
18206:
18207: Inputs:
18208:
18209: dom - domain being searched
18210:
18211: type - course type ('Course' or 'Community' or '.' if any).
18212:
18213: filter - anonymous hash of criteria and their values
18214:
18215: numtitles - for institutional codes - number of categories
18216:
18217: cloneruname - optional username of new course owner
18218:
18219: clonerudom - optional domain of new course owner
18220:
18221: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
18222: (used when DC is using course creation form)
18223:
18224: codetitles - reference to array of titles of components in institutional codes (official courses).
18225:
18226: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18227: (and so can clone automatically)
18228:
18229: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18230:
18231: reqinstcode - institutional code of new course, where search_courses is used to identify potential
18232: courses to clone
18233:
18234: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18235:
18236:
18237: Side Effects: None
18238:
18239: =cut
18240:
18241:
18242: sub search_courses {
18243: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18244: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18245: my (%courses,%showcourses,$cloner);
18246: if (($filter->{'ownerfilter'} ne '') ||
18247: ($filter->{'ownerdomfilter'} ne '')) {
18248: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18249: $filter->{'ownerdomfilter'};
18250: }
18251: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18252: if (!$filter->{$item}) {
18253: $filter->{$item}='.';
18254: }
18255: }
18256: my $now = time;
18257: my $timefilter =
18258: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18259: my ($createdbefore,$createdafter);
18260: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18261: $createdbefore = $now;
18262: $createdafter = $now-$filter->{'createdfilter'};
18263: }
18264: my ($instcodefilter,$regexpok);
18265: if ($numtitles) {
18266: if ($env{'form.official'} eq 'on') {
18267: $instcodefilter =
18268: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18269: $regexpok = 1;
18270: } elsif ($env{'form.official'} eq 'off') {
18271: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18272: unless ($instcodefilter eq '') {
18273: $regexpok = -1;
18274: }
18275: }
18276: } else {
18277: $instcodefilter = $filter->{'instcodefilter'};
18278: }
18279: if ($instcodefilter eq '') { $instcodefilter = '.'; }
18280: if ($type eq '') { $type = '.'; }
18281:
18282: if (($clonerudom ne '') && ($cloneruname ne '')) {
18283: $cloner = $cloneruname.':'.$clonerudom;
18284: }
18285: %courses = &Apache::lonnet::courseiddump($dom,
18286: $filter->{'descriptfilter'},
18287: $timefilter,
18288: $instcodefilter,
18289: $filter->{'combownerfilter'},
18290: $filter->{'coursefilter'},
18291: undef,undef,$type,$regexpok,undef,undef,
18292: undef,undef,$cloner,$cc_clone,
18293: $filter->{'cloneableonly'},
18294: $createdbefore,$createdafter,undef,
18295: $domcloner,undef,$reqcrsdom,$reqinstcode);
18296: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18297: my $ccrole;
18298: if ($type eq 'Community') {
18299: $ccrole = 'co';
18300: } else {
18301: $ccrole = 'cc';
18302: }
18303: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18304: $filter->{'persondomfilter'},
18305: 'userroles',undef,
18306: [$ccrole,'in','ad','ep','ta','cr'],
18307: $dom);
18308: foreach my $role (keys(%rolehash)) {
18309: my ($cnum,$cdom,$courserole) = split(':',$role);
18310: my $cid = $cdom.'_'.$cnum;
18311: if (exists($courses{$cid})) {
18312: if (ref($courses{$cid}) eq 'HASH') {
18313: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18314: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18315: push(@{$courses{$cid}{roles}},$courserole);
18316: }
18317: } else {
18318: $courses{$cid}{roles} = [$courserole];
18319: }
18320: $showcourses{$cid} = $courses{$cid};
18321: }
18322: }
18323: }
18324: %courses = %showcourses;
18325: }
18326: return %courses;
18327: }
18328:
18329: =pod
18330:
18331: =back
18332:
18333: =head1 Routines for version requirements for current course.
18334:
18335: =over 4
18336:
18337: =item * &check_release_required()
18338:
18339: Compares required LON-CAPA version with version on server, and
18340: if required version is newer looks for a server with the required version.
18341:
18342: Looks first at servers in user's owen domain; if none suitable, looks at
18343: servers in course's domain are permitted to host sessions for user's domain.
18344:
18345: Inputs:
18346:
18347: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18348:
18349: $courseid - Course ID of current course
18350:
18351: $rolecode - User's current role in course (for switchserver query string).
18352:
18353: $required - LON-CAPA version needed by course (format: Major.Minor).
18354:
18355:
18356: Returns:
18357:
18358: $switchserver - query string tp append to /adm/switchserver call (if
18359: current server's LON-CAPA version is too old.
18360:
18361: $warning - Message is displayed if no suitable server could be found.
18362:
18363: =cut
18364:
18365: sub check_release_required {
18366: my ($loncaparev,$courseid,$rolecode,$required) = @_;
18367: my ($switchserver,$warning);
18368: if ($required ne '') {
18369: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18370: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18371: if ($reqdmajor ne '' && $reqdminor ne '') {
18372: my $otherserver;
18373: if (($major eq '' && $minor eq '') ||
18374: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18375: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18376: my $switchlcrev =
18377: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18378: $userdomserver);
18379: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18380: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18381: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18382: my $cdom = $env{'course.'.$courseid.'.domain'};
18383: if ($cdom ne $env{'user.domain'}) {
18384: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18385: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18386: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18387: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18388: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18389: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18390: my $canhost =
18391: &Apache::lonnet::can_host_session($env{'user.domain'},
18392: $coursedomserver,
18393: $remoterev,
18394: $udomdefaults{'remotesessions'},
18395: $defdomdefaults{'hostedsessions'});
18396:
18397: if ($canhost) {
18398: $otherserver = $coursedomserver;
18399: } else {
18400: $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.");
18401: }
18402: } else {
18403: $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).");
18404: }
18405: } else {
18406: $otherserver = $userdomserver;
18407: }
18408: }
18409: if ($otherserver ne '') {
18410: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
18411: }
18412: }
18413: }
18414: return ($switchserver,$warning);
18415: }
18416:
18417: =pod
18418:
18419: =item * &check_release_result()
18420:
18421: Inputs:
18422:
18423: $switchwarning - Warning message if no suitable server found to host session.
18424:
18425: $switchserver - query string to append to /adm/switchserver containing lonHostID
18426: and current role.
18427:
18428: Returns: HTML to display with information about requirement to switch server.
18429: Either displaying warning with link to Roles/Courses screen or
18430: display link to switchserver.
18431:
18432: =cut
18433:
18434: sub check_release_result {
18435: my ($switchwarning,$switchserver) = @_;
18436: my $output = &start_page('Selected course unavailable on this server').
18437: '<p class="LC_warning">';
18438: if ($switchwarning) {
18439: $output .= $switchwarning.'<br /><a href="/adm/roles">';
18440: if (&show_course()) {
18441: $output .= &mt('Display courses');
18442: } else {
18443: $output .= &mt('Display roles');
18444: }
18445: $output .= '</a>';
18446: } elsif ($switchserver) {
18447: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18448: '<br />'.
18449: '<a href="/adm/switchserver?'.$switchserver.'">'.
18450: &mt('Switch Server').
18451: '</a>';
18452: }
18453: $output .= '</p>'.&end_page();
18454: return $output;
18455: }
18456:
18457: =pod
18458:
18459: =item * &needs_coursereinit()
18460:
18461: Determine if course contents stored for user's session needs to be
18462: refreshed, because content has changed since "Big Hash" last tied.
18463:
18464: Check for change is made if time last checked is more than 10 minutes ago
18465: (by default).
18466:
18467: Inputs:
18468:
18469: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18470:
18471: $interval (optional) - Time which may elapse (in s) between last check for content
18472: change in current course. (default: 600 s).
18473:
18474: Returns: an array; first element is:
18475:
18476: =over 4
18477:
18478: 'switch' - if content updates mean user's session
18479: needs to be switched to a server running a newer LON-CAPA version
18480:
18481: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18482: on current server hosting user's session
18483:
18484: '' - if no action required.
18485:
18486: =back
18487:
18488: If first item element is 'switch':
18489:
18490: second item is $switchwarning - Warning message if no suitable server found to host session.
18491:
18492: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18493: and current role.
18494:
18495: otherwise: no other elements returned.
18496:
18497: =back
18498:
18499: =cut
18500:
18501: sub needs_coursereinit {
18502: my ($loncaparev,$interval) = @_;
18503: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18504: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18505: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18506: my $now = time;
18507: if ($interval eq '') {
18508: $interval = 600;
18509: }
18510: if (($now-$env{'request.course.timechecked'})>$interval) {
18511: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18512: my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18513: if ($blocked) {
18514: return ();
18515: }
18516: my $update;
18517: my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18518: my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18519: if ($lastmainchange > $env{'request.course.tied'}) {
18520: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18521: if ($needswitch) {
18522: return ('switch',$switchwarning,$switchserver);
18523: }
18524: $update = 'main';
18525: }
18526: if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18527: if ($update) {
18528: $update = 'both';
18529: } else {
18530: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18531: if ($needswitch) {
18532: return ('switch',$switchwarning,$switchserver);
18533: } else {
18534: $update = 'supp';
18535: }
18536: }
18537: return ($update);
18538: }
18539: }
18540: return ();
18541: }
18542:
18543: sub switch_for_update {
18544: my ($loncaparev,$cdom,$cnum) = @_;
18545: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18546: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18547: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18548: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18549: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18550: $curr_reqd_hash{'internal.releaserequired'}});
18551: my ($switchserver,$switchwarning) =
18552: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18553: $curr_reqd_hash{'internal.releaserequired'});
18554: if ($switchwarning ne '' || $switchserver ne '') {
18555: return ('switch',$switchwarning,$switchserver);
18556: }
18557: }
18558: }
18559: return ();
18560: }
18561:
18562: sub update_content_constraints {
18563: my ($cdom,$cnum,$chome,$cid) = @_;
18564: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18565: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18566: my (%checkresponsetypes,%checkcrsrestypes);
18567: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18568: my ($item,$name,$value) = split(/:/,$key);
18569: if ($item eq 'resourcetag') {
18570: if ($name eq 'responsetype') {
18571: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18572: }
18573: } elsif ($item eq 'course') {
18574: if ($name eq 'courserestype') {
18575: $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18576: }
18577: }
18578: }
18579: my $navmap = Apache::lonnavmaps::navmap->new();
18580: if (defined($navmap)) {
18581: my (%allresponses,%allcrsrestypes);
18582: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18583: if ($res->is_tool()) {
18584: if ($allcrsrestypes{'exttool'}) {
18585: $allcrsrestypes{'exttool'} ++;
18586: } else {
18587: $allcrsrestypes{'exttool'} = 1;
18588: }
18589: next;
18590: }
18591: my %responses = $res->responseTypes();
18592: foreach my $key (keys(%responses)) {
18593: next unless(exists($checkresponsetypes{$key}));
18594: $allresponses{$key} += $responses{$key};
18595: }
18596: }
18597: foreach my $key (keys(%allresponses)) {
18598: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18599: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18600: ($reqdmajor,$reqdminor) = ($major,$minor);
18601: }
18602: }
18603: foreach my $key (keys(%allcrsrestypes)) {
18604: my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18605: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18606: ($reqdmajor,$reqdminor) = ($major,$minor);
18607: }
18608: }
18609: undef($navmap);
18610: }
18611: if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18612: my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18613: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18614: ($reqdmajor,$reqdminor) = ($major,$minor);
18615: }
18616: }
18617: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18618: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18619: }
18620: return;
18621: }
18622:
18623: sub allmaps_incourse {
18624: my ($cdom,$cnum,$chome,$cid) = @_;
18625: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18626: $cid = $env{'request.course.id'};
18627: $cdom = $env{'course.'.$cid.'.domain'};
18628: $cnum = $env{'course.'.$cid.'.num'};
18629: $chome = $env{'course.'.$cid.'.home'};
18630: }
18631: my %allmaps = ();
18632: my $lastchange =
18633: &Apache::lonnet::get_coursechange($cdom,$cnum);
18634: if ($lastchange > $env{'request.course.tied'}) {
18635: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18636: unless ($ferr) {
18637: &update_content_constraints($cdom,$cnum,$chome,$cid);
18638: }
18639: }
18640: my $navmap = Apache::lonnavmaps::navmap->new();
18641: if (defined($navmap)) {
18642: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18643: $allmaps{$res->src()} = 1;
18644: }
18645: }
18646: return \%allmaps;
18647: }
18648:
18649: sub parse_supplemental_title {
18650: my ($title) = @_;
18651:
18652: my ($foldertitle,$renametitle);
18653: if ($title =~ /&&&/) {
18654: $title = &HTML::Entites::decode($title);
18655: }
18656: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18657: $renametitle=$4;
18658: my ($time,$uname,$udom) = ($1,$2,$3);
18659: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18660: my $name = &plainname($uname,$udom);
18661: $name = &HTML::Entities::encode($name,'"<>&\'');
18662: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18663: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18664: if ($foldertitle ne '') {
18665: $title .= ': <br />'.$foldertitle;
18666: }
18667: }
18668: if (wantarray) {
18669: return ($title,$foldertitle,$renametitle);
18670: }
18671: return $title;
18672: }
18673:
18674: sub get_supplemental {
18675: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18676: my $hashid=$cnum.':'.$cdom;
18677: my ($supplemental,$cached,$set_httprefs);
18678: unless ($ignorecache) {
18679: ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18680: }
18681: unless (defined($cached)) {
18682: my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18683: unless ($chome eq 'no_host') {
18684: my @order = @LONCAPA::map::order;
18685: my @resources = @LONCAPA::map::resources;
18686: my @resparms = @LONCAPA::map::resparms;
18687: my @zombies = @LONCAPA::map::zombies;
18688: my ($errors,%ids,%hidden);
18689: $errors =
18690: &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18691: $errors,$possdel,\%ids,\%hidden);
18692: @LONCAPA::map::order = @order;
18693: @LONCAPA::map::resources = @resources;
18694: @LONCAPA::map::resparms = @resparms;
18695: @LONCAPA::map::zombies = @zombies;
18696: $set_httprefs = 1;
18697: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18698: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18699: }
18700: $supplemental = {
18701: ids => \%ids,
18702: hidden => \%hidden,
18703: };
18704: &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18705: }
18706: }
18707: return ($supplemental,$set_httprefs);
18708: }
18709:
18710: sub recurse_supplemental {
18711: my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18712: if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18713: my $mapnum;
18714: if ($suppmap eq 'supplemental.sequence') {
18715: $mapnum = 0;
18716: } else {
18717: ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18718: }
18719: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18720: if ($fatal) {
18721: $errors ++;
18722: } else {
18723: my @order = @LONCAPA::map::order;
18724: if (@order > 0) {
18725: my @resources = @LONCAPA::map::resources;
18726: my @resparms = @LONCAPA::map::resparms;
18727: foreach my $idx (@order) {
18728: my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18729: if (($src ne '') && ($status eq 'res')) {
18730: my $id = $mapnum.':'.$idx;
18731: push(@{$suppids->{$src}},$id);
18732: if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18733: $hiddensupp->{$id} = 1;
18734: }
18735: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18736: $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18737: $hiddensupp,$hiddensupp->{$id});
18738: } else {
18739: my $allowed;
18740: if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18741: $allowed = 1;
18742: } elsif ($possdel) {
18743: foreach my $item (@{$suppids->{$src}}) {
18744: next if ($item eq $id);
18745: unless ($hiddensupp->{$item}) {
18746: $allowed = 1;
18747: last;
18748: }
18749: }
18750: if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18751: &Apache::lonnet::delenv('httpref.'.$src);
18752: }
18753: }
18754: if ($allowed && (!exists($env{'httpref.'.$src}))) {
18755: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18756: }
18757: }
18758: }
18759: }
18760: }
18761: }
18762: }
18763: return $errors;
18764: }
18765:
18766: sub set_supp_httprefs {
18767: my ($cnum,$cdom,$supplemental,$possdel) = @_;
18768: if (ref($supplemental) eq 'HASH') {
18769: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18770: foreach my $src (keys(%{$supplemental->{'ids'}})) {
18771: next if ($src =~ /\.sequence$/);
18772: if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18773: my $allowed;
18774: if ($env{'request.role.adv'}) {
18775: $allowed = 1;
18776: } else {
18777: foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18778: unless ($supplemental->{'hidden'}->{$id}) {
18779: $allowed = 1;
18780: last;
18781: }
18782: }
18783: }
18784: if (exists($env{'httpref.'.$src})) {
18785: if ($possdel) {
18786: unless ($allowed) {
18787: &Apache::lonnet::delenv('httpref.'.$src);
18788: }
18789: }
18790: } elsif ($allowed) {
18791: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18792: }
18793: }
18794: }
18795: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18796: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18797: }
18798: }
18799: }
18800: }
18801:
18802: sub get_supp_parameter {
18803: my ($resparm,$name)=@_;
18804: return if ($resparm eq '');
18805: my $value=undef;
18806: my $ptype=undef;
18807: foreach (split('&&&',$resparm)) {
18808: my ($thistype,$thisname,$thisvalue)=split('___',$_);
18809: if ($thisname eq $name) {
18810: $value=$thisvalue;
18811: $ptype=$thistype;
18812: }
18813: }
18814: return $value;
18815: }
18816:
18817: sub symb_to_docspath {
18818: my ($symb,$navmapref) = @_;
18819: return unless ($symb && ref($navmapref));
18820: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18821: if ($resurl=~/\.(sequence|page)$/) {
18822: $mapurl=$resurl;
18823: } elsif ($resurl eq 'adm/navmaps') {
18824: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18825: }
18826: my $mapresobj;
18827: unless (ref($$navmapref)) {
18828: $$navmapref = Apache::lonnavmaps::navmap->new();
18829: }
18830: if (ref($$navmapref)) {
18831: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18832: }
18833: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18834: my $type=$2;
18835: my $path;
18836: if (ref($mapresobj)) {
18837: my $pcslist = $mapresobj->map_hierarchy();
18838: if ($pcslist ne '') {
18839: foreach my $pc (split(/,/,$pcslist)) {
18840: next if ($pc <= 1);
18841: my $res = $$navmapref->getByMapPc($pc);
18842: if (ref($res)) {
18843: my $thisurl = $res->src();
18844: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18845: my $thistitle = $res->title();
18846: $path .= '&'.
18847: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18848: &escape($thistitle).
18849: ':'.$res->randompick().
18850: ':'.$res->randomout().
18851: ':'.$res->encrypted().
18852: ':'.$res->randomorder().
18853: ':'.$res->is_page();
18854: }
18855: }
18856: }
18857: $path =~ s/^\&//;
18858: my $maptitle = $mapresobj->title();
18859: if ($mapurl eq 'default') {
18860: $maptitle = 'Main Content';
18861: }
18862: $path .= (($path ne '')? '&' : '').
18863: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18864: &escape($maptitle).
18865: ':'.$mapresobj->randompick().
18866: ':'.$mapresobj->randomout().
18867: ':'.$mapresobj->encrypted().
18868: ':'.$mapresobj->randomorder().
18869: ':'.$mapresobj->is_page();
18870: } else {
18871: my $maptitle = &Apache::lonnet::gettitle($mapurl);
18872: my $ispage = (($type eq 'page')? 1 : '');
18873: if ($mapurl eq 'default') {
18874: $maptitle = 'Main Content';
18875: }
18876: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18877: &escape($maptitle).':::::'.$ispage;
18878: }
18879: unless ($mapurl eq 'default') {
18880: $path = 'default&'.
18881: &escape('Main Content').
18882: ':::::&'.$path;
18883: }
18884: return $path;
18885: }
18886:
18887: sub validate_folderpath {
18888: my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18889: if ($env{'form.folderpath'} ne '') {
18890: my @items = split(/\&/,$env{'form.folderpath'});
18891: my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18892: for (my $i=0; $i<@items; $i++) {
18893: my $odd = $i%2;
18894: if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18895: $badpath = 1;
18896: } elsif ($odd && $supplementalflag) {
18897: my $idx = $i-1;
18898: if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18899: my $esc_name = $1;
18900: if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18901: $supppath .= '&'.$esc_name;
18902: $changed = 1;
18903: } else {
18904: $supppath .= '&'.$items[$i];
18905: }
18906: } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18907: $changed = 1;
18908: my $is_hidden;
18909: unless ($got_supp) {
18910: my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18911: if (ref($supplemental) eq 'HASH') {
18912: if (ref($supplemental->{'hidden'}) eq 'HASH') {
18913: %supphidden = %{$supplemental->{'hidden'}};
18914: }
18915: if (ref($supplemental->{'ids'}) eq 'HASH') {
18916: %suppids = %{$supplemental->{'ids'}};
18917: }
18918: }
18919: $got_supp = 1;
18920: }
18921: if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18922: my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18923: if ($supphidden{$mapid}) {
18924: $is_hidden = 1;
18925: }
18926: }
18927: $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18928: } else {
18929: $supppath .= '&'.$items[$i];
18930: }
18931: } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18932: $badpath = 1;
18933: } elsif ($supplementalflag) {
18934: $supppath .= '&'.$items[$i];
18935: }
18936: last if ($badpath);
18937: }
18938: if ($badpath) {
18939: delete($env{'form.folderpath'});
18940: } elsif ($changed && $supplementalflag) {
18941: $supppath =~ s/^\&//;
18942: $env{'form.folderpath'} = $supppath;
18943: }
18944: }
18945: return;
18946: }
18947:
18948: sub captcha_display {
18949: my ($context,$lonhost,$defdom) = @_;
18950: my ($output,$error);
18951: my ($captcha,$pubkey,$privkey,$version) =
18952: &get_captcha_config($context,$lonhost,$defdom);
18953: if ($captcha eq 'original') {
18954: $output = &create_captcha();
18955: unless ($output) {
18956: $error = 'captcha';
18957: }
18958: } elsif ($captcha eq 'recaptcha') {
18959: $output = &create_recaptcha($pubkey,$version);
18960: unless ($output) {
18961: $error = 'recaptcha';
18962: }
18963: }
18964: return ($output,$error,$captcha,$version);
18965: }
18966:
18967: sub captcha_response {
18968: my ($context,$lonhost,$defdom) = @_;
18969: my ($captcha_chk,$captcha_error);
18970: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18971: if ($captcha eq 'original') {
18972: ($captcha_chk,$captcha_error) = &check_captcha();
18973: } elsif ($captcha eq 'recaptcha') {
18974: $captcha_chk = &check_recaptcha($privkey,$version);
18975: } else {
18976: $captcha_chk = 1;
18977: }
18978: return ($captcha_chk,$captcha_error);
18979: }
18980:
18981: sub get_captcha_config {
18982: my ($context,$lonhost,$dom_in_effect) = @_;
18983: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18984: my $hostname = &Apache::lonnet::hostname($lonhost);
18985: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18986: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18987: if ($context eq 'usercreation') {
18988: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18989: if (ref($domconfig{$context}) eq 'HASH') {
18990: $hashtocheck = $domconfig{$context}{'cancreate'};
18991: if (ref($hashtocheck) eq 'HASH') {
18992: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18993: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18994: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18995: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18996: }
18997: if ($privkey && $pubkey) {
18998: $captcha = 'recaptcha';
18999: $version = $hashtocheck->{'recaptchaversion'};
19000: if ($version ne '2') {
19001: $version = 1;
19002: }
19003: } else {
19004: $captcha = 'original';
19005: }
19006: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19007: $captcha = 'original';
19008: }
19009: }
19010: } else {
19011: $captcha = 'captcha';
19012: }
19013: } elsif ($context eq 'login') {
19014: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19015: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19016: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19017: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19018: if ($privkey && $pubkey) {
19019: $captcha = 'recaptcha';
19020: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19021: if ($version ne '2') {
19022: $version = 1;
19023: }
19024: } else {
19025: $captcha = 'original';
19026: }
19027: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19028: $captcha = 'original';
19029: }
19030: } elsif ($context eq 'passwords') {
19031: if ($dom_in_effect) {
19032: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19033: if ($passwdconf{'captcha'} eq 'recaptcha') {
19034: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19035: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19036: $privkey = $passwdconf{'recaptchakeys'}{'private'};
19037: }
19038: if ($privkey && $pubkey) {
19039: $captcha = 'recaptcha';
19040: $version = $passwdconf{'recaptchaversion'};
19041: if ($version ne '2') {
19042: $version = 1;
19043: }
19044: } else {
19045: $captcha = 'original';
19046: }
19047: } elsif ($passwdconf{'captcha'} ne 'notused') {
19048: $captcha = 'original';
19049: }
19050: }
19051: }
19052: return ($captcha,$pubkey,$privkey,$version);
19053: }
19054:
19055: sub create_captcha {
19056: my %captcha_params = &captcha_settings();
19057: my ($output,$maxtries,$tries) = ('',10,0);
19058: while ($tries < $maxtries) {
19059: $tries ++;
19060: my $captcha = Authen::Captcha->new (
19061: output_folder => $captcha_params{'output_dir'},
19062: data_folder => $captcha_params{'db_dir'},
19063: );
19064: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19065:
19066: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19067: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19068: '<span class="LC_nobreak">'.
19069: &mt('Type in the letters/numbers shown below').' '.
19070: '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19071: '</span><br />'.
19072: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19073: last;
19074: }
19075: }
19076: if ($output eq '') {
19077: &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19078: }
19079: return $output;
19080: }
19081:
19082: sub captcha_settings {
19083: my %captcha_params = (
19084: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19085: www_output_dir => "/captchaspool",
19086: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19087: numchars => '5',
19088: );
19089: return %captcha_params;
19090: }
19091:
19092: sub check_captcha {
19093: my ($captcha_chk,$captcha_error);
19094: my $code = $env{'form.code'};
19095: my $md5sum = $env{'form.crypt'};
19096: my %captcha_params = &captcha_settings();
19097: my $captcha = Authen::Captcha->new(
19098: output_folder => $captcha_params{'output_dir'},
19099: data_folder => $captcha_params{'db_dir'},
19100: );
19101: $captcha_chk = $captcha->check_code($code,$md5sum);
19102: my %captcha_hash = (
19103: 0 => 'Code not checked (file error)',
19104: -1 => 'Failed: code expired',
19105: -2 => 'Failed: invalid code (not in database)',
19106: -3 => 'Failed: invalid code (code does not match crypt)',
19107: );
19108: if ($captcha_chk != 1) {
19109: $captcha_error = $captcha_hash{$captcha_chk}
19110: }
19111: return ($captcha_chk,$captcha_error);
19112: }
19113:
19114: sub create_recaptcha {
19115: my ($pubkey,$version) = @_;
19116: if ($version >= 2) {
19117: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19118: '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19119: } else {
19120: my $use_ssl;
19121: if ($ENV{'SERVER_PORT'} == 443) {
19122: $use_ssl = 1;
19123: }
19124: my $captcha = Captcha::reCAPTCHA->new;
19125: return $captcha->get_options_setter({theme => 'white'})."\n".
19126: $captcha->get_html($pubkey,undef,$use_ssl).
19127: &mt('If the text is hard to read, [_1] will replace them.',
19128: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19129: '<br /><br />';
19130: }
19131: }
19132:
19133: sub check_recaptcha {
19134: my ($privkey,$version) = @_;
19135: my $captcha_chk;
19136: my $ip = &Apache::lonnet::get_requestor_ip();
19137: if ($version >= 2) {
19138: my %info = (
19139: secret => $privkey,
19140: response => $env{'form.g-recaptcha-response'},
19141: remoteip => $ip,
19142: );
19143: my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19144: $request->content(join('&',map {
19145: my $name = escape($_);
19146: "$name=" . ( ref($info{$_}) eq 'ARRAY'
19147: ? join("&$name=", map {escape($_) } @{$info{$_}})
19148: : &escape($info{$_}) );
19149: } keys(%info)));
19150: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19151: if ($response->is_success) {
19152: my $data = JSON::DWIW->from_json($response->decoded_content);
19153: if (ref($data) eq 'HASH') {
19154: if ($data->{'success'}) {
19155: $captcha_chk = 1;
19156: }
19157: }
19158: }
19159: } else {
19160: my $captcha = Captcha::reCAPTCHA->new;
19161: my $captcha_result =
19162: $captcha->check_answer(
19163: $privkey,
19164: $ip,
19165: $env{'form.recaptcha_challenge_field'},
19166: $env{'form.recaptcha_response_field'},
19167: );
19168: if ($captcha_result->{is_valid}) {
19169: $captcha_chk = 1;
19170: }
19171: }
19172: return $captcha_chk;
19173: }
19174:
19175: sub emailusername_info {
19176: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19177: my %titles = &Apache::lonlocal::texthash (
19178: lastname => 'Last Name',
19179: firstname => 'First Name',
19180: institution => 'School/college/university',
19181: location => "School's city, state/province, country",
19182: web => "School's web address",
19183: officialemail => 'E-mail address at institution (if different)',
19184: id => 'Student/Employee ID',
19185: );
19186: return (\@fields,\%titles);
19187: }
19188:
19189: sub cleanup_html {
19190: my ($incoming) = @_;
19191: my $outgoing;
19192: if ($incoming ne '') {
19193: $outgoing = $incoming;
19194: $outgoing =~ s/;/;/g;
19195: $outgoing =~ s/\#/#/g;
19196: $outgoing =~ s/\&/&/g;
19197: $outgoing =~ s/</</g;
19198: $outgoing =~ s/>/>/g;
19199: $outgoing =~ s/\(/(/g;
19200: $outgoing =~ s/\)/)/g;
19201: $outgoing =~ s/"/"/g;
19202: $outgoing =~ s/'/'/g;
19203: $outgoing =~ s/\$/$/g;
19204: $outgoing =~ s{/}{/}g;
19205: $outgoing =~ s/=/=/g;
19206: $outgoing =~ s/\\/\/g
19207: }
19208: return $outgoing;
19209: }
19210:
19211: # Checks for critical messages and returns a redirect url if one exists.
19212: # $interval indicates how often to check for messages.
19213: # $context is the calling context -- roles, grades, contents, menu or flip.
19214: sub critical_redirect {
19215: my ($interval,$context) = @_;
19216: unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19217: return ();
19218: }
19219: if ((time-$env{'user.criticalcheck.time'})>$interval) {
19220: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19221: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19222: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19223: my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19224: if ($blocked) {
19225: my $checkrole = "cm./$cdom/$cnum";
19226: if ($env{'request.course.sec'} ne '') {
19227: $checkrole .= "/$env{'request.course.sec'}";
19228: }
19229: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19230: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19231: return;
19232: }
19233: }
19234: }
19235: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
19236: $env{'user.name'});
19237: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19238: my $redirecturl;
19239: if ($what[0]) {
19240: if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19241: $redirecturl='/adm/email?critical=display';
19242: my $url=&Apache::lonnet::absolute_url().$redirecturl;
19243: return (1, $url);
19244: }
19245: }
19246: }
19247: return ();
19248: }
19249:
19250: # Use:
19251: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19252: #
19253: ##################################################
19254: # password associated functions #
19255: ##################################################
19256: sub des_keys {
19257: # Make a new key for DES encryption.
19258: # Each key has two parts which are returned separately.
19259: # Please note: Each key must be passed through the &hex function
19260: # before it is output to the web browser. The hex versions cannot
19261: # be used to decrypt.
19262: my @hexstr=('0','1','2','3','4','5','6','7',
19263: '8','9','a','b','c','d','e','f');
19264: my $lkey='';
19265: for (0..7) {
19266: $lkey.=$hexstr[rand(15)];
19267: }
19268: my $ukey='';
19269: for (0..7) {
19270: $ukey.=$hexstr[rand(15)];
19271: }
19272: return ($lkey,$ukey);
19273: }
19274:
19275: sub des_decrypt {
19276: my ($key,$cyphertext) = @_;
19277: my $keybin=pack("H16",$key);
19278: my $cypher;
19279: if ($Crypt::DES::VERSION>=2.03) {
19280: $cypher=new Crypt::DES $keybin;
19281: } else {
19282: $cypher=new DES $keybin;
19283: }
19284: my $plaintext='';
19285: my $cypherlength = length($cyphertext);
19286: my $numchunks = int($cypherlength/32);
19287: for (my $j=0; $j<$numchunks; $j++) {
19288: my $start = $j*32;
19289: my $cypherblock = substr($cyphertext,$start,32);
19290: my $chunk =
19291: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19292: $chunk .=
19293: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19294: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19295: $plaintext .= $chunk;
19296: }
19297: return $plaintext;
19298: }
19299:
19300: sub get_requested_shorturls {
19301: my ($cdom,$cnum,$navmap) = @_;
19302: return unless (ref($navmap));
19303: my ($numnew,$errors);
19304: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19305: if (@toshorten) {
19306: my (%maps,%resources,%titles);
19307: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19308: 'shorturls',$cdom,$cnum);
19309: if (keys(%resources)) {
19310: my %tocreate;
19311: foreach my $item (sort {$a <=> $b} (@toshorten)) {
19312: my $symb = $resources{$item};
19313: if ($symb) {
19314: $tocreate{$cnum.'&'.$symb} = 1;
19315: }
19316: }
19317: if (keys(%tocreate)) {
19318: ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19319: \%tocreate);
19320: }
19321: }
19322: }
19323: return ($numnew,$errors);
19324: }
19325:
19326: sub make_short_symbs {
19327: my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19328: my ($numnew,@errors);
19329: if (ref($tocreateref) eq 'HASH') {
19330: my %tocreate = %{$tocreateref};
19331: if (keys(%tocreate)) {
19332: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19333: my $su = Short::URL->new(no_vowels => 1);
19334: my $init = '';
19335: my (%newunique,%addcourse,%courseonly,%failed);
19336: # get lock on tiny db
19337: my $now = time;
19338: if ($lockuser eq '') {
19339: $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19340: }
19341: my $lockhash = {
19342: "lock\0$now" => $lockuser,
19343: };
19344: my $tries = 0;
19345: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19346: my ($code,$error);
19347: while (($gotlock ne 'ok') && ($tries<3)) {
19348: $tries ++;
19349: sleep 1;
19350: $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19351: }
19352: if ($gotlock eq 'ok') {
19353: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19354: \%addcourse,\%courseonly,\%failed);
19355: if (keys(%failed)) {
19356: my $numfailed = scalar(keys(%failed));
19357: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19358: }
19359: if (keys(%newunique)) {
19360: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19361: if ($putres eq 'ok') {
19362: $numnew = scalar(keys(%newunique));
19363: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19364: unless ($newputres eq 'ok') {
19365: push(@errors,&mt('error: could not store course look-up of short URLs'));
19366: }
19367: } else {
19368: push(@errors,&mt('error: could not store unique six character URLs'));
19369: }
19370: }
19371: my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19372: unless ($dellockres eq 'ok') {
19373: push(@errors,&mt('error: could not release lockfile'));
19374: }
19375: } else {
19376: push(@errors,&mt('error: could not obtain lockfile'));
19377: }
19378: if (keys(%courseonly)) {
19379: my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19380: if ($result ne 'ok') {
19381: push(@errors,&mt('error: could not update course look-up of short URLs'));
19382: }
19383: }
19384: }
19385: }
19386: return ($numnew,\@errors);
19387: }
19388:
19389: sub shorten_symbs {
19390: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19391: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19392: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19393: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19394: my (%possibles,%collisions);
19395: foreach my $key (keys(%{$tocreate})) {
19396: my $num = String::CRC32::crc32($key);
19397: my $tiny = $su->encode($num,$init);
19398: if ($tiny) {
19399: $possibles{$tiny} = $key;
19400: }
19401: }
19402: if (!$init) {
19403: $init = 1;
19404: } else {
19405: $init ++;
19406: }
19407: if (keys(%possibles)) {
19408: my @posstiny = keys(%possibles);
19409: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19410: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19411: if (keys(%currtiny)) {
19412: foreach my $key (keys(%currtiny)) {
19413: next if ($currtiny{$key} eq '');
19414: if ($currtiny{$key} eq $possibles{$key}) {
19415: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19416: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19417: $courseonly->{$tsymb} = $key;
19418: }
19419: } else {
19420: $collisions{$possibles{$key}} = 1;
19421: }
19422: delete($possibles{$key});
19423: }
19424: }
19425: foreach my $key (keys(%possibles)) {
19426: $newunique->{$key} = $possibles{$key};
19427: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19428: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19429: $addcourse->{$tsymb} = $key;
19430: }
19431: }
19432: }
19433: if (keys(%collisions)) {
19434: if ($init <5) {
19435: if (!$init) {
19436: $init = 1;
19437: } else {
19438: $init ++;
19439: }
19440: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19441: $newunique,$addcourse,$courseonly,$failed);
19442: } else {
19443: foreach my $key (keys(%collisions)) {
19444: $failed->{$key} = 1;
19445: }
19446: }
19447: }
19448: return $init;
19449: }
19450:
19451: sub is_nonframeable {
19452: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19453: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19454: return if (($remprotocol eq '') || ($remhost eq ''));
19455:
19456: $remprotocol = lc($remprotocol);
19457: $remhost = lc($remhost);
19458: my $remport = 80;
19459: if ($remprotocol eq 'https') {
19460: $remport = 443;
19461: }
19462: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19463: if ($cached) {
19464: unless ($nocache) {
19465: if ($result) {
19466: return 1;
19467: } else {
19468: return 0;
19469: }
19470: }
19471: }
19472: my $uselink;
19473: my $request = new HTTP::Request('HEAD',$url);
19474: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19475: if ($response->is_success()) {
19476: my $secpolicy = lc($response->header('content-security-policy'));
19477: my $xframeop = lc($response->header('x-frame-options'));
19478: $secpolicy =~ s/^\s+|\s+$//g;
19479: $xframeop =~ s/^\s+|\s+$//g;
19480: if (($secpolicy ne '') || ($xframeop ne '')) {
19481: my $remotehost = $remprotocol.'://'.$remhost;
19482: my ($origin,$protocol,$port);
19483: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19484: $port = $ENV{'SERVER_PORT'};
19485: } else {
19486: $port = 80;
19487: }
19488: if ($absolute eq '') {
19489: $protocol = 'http:';
19490: if ($port == 443) {
19491: $protocol = 'https:';
19492: }
19493: $origin = $protocol.'//'.lc($hostname);
19494: } else {
19495: $origin = lc($absolute);
19496: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19497: }
19498: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19499: my $framepolicy = $1;
19500: $framepolicy =~ s/^\s+|\s+$//g;
19501: my @policies = split(/\s+/,$framepolicy);
19502: if (@policies) {
19503: if (grep(/^\Q'none'\E$/,@policies)) {
19504: $uselink = 1;
19505: } else {
19506: $uselink = 1;
19507: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19508: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19509: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19510: undef($uselink);
19511: }
19512: if ($uselink) {
19513: if (grep(/^\Q'self'\E$/,@policies)) {
19514: if (($origin ne '') && ($remotehost eq $origin)) {
19515: undef($uselink);
19516: }
19517: }
19518: }
19519: if ($uselink) {
19520: my @possok;
19521: if ($ip ne '') {
19522: push(@possok,$ip);
19523: }
19524: my $hoststr = '';
19525: foreach my $part (reverse(split(/\./,$hostname))) {
19526: if ($hoststr eq '') {
19527: $hoststr = $part;
19528: } else {
19529: $hoststr = "$part.$hoststr";
19530: }
19531: if ($hoststr eq $hostname) {
19532: push(@possok,$hostname);
19533: } else {
19534: push(@possok,"*.$hoststr");
19535: }
19536: }
19537: if (@possok) {
19538: foreach my $poss (@possok) {
19539: last if (!$uselink);
19540: foreach my $policy (@policies) {
19541: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19542: undef($uselink);
19543: last;
19544: }
19545: }
19546: }
19547: }
19548: }
19549: }
19550: }
19551: } elsif ($xframeop ne '') {
19552: $uselink = 1;
19553: my @policies = split(/\s*,\s*/,$xframeop);
19554: if (@policies) {
19555: unless (grep(/^deny$/,@policies)) {
19556: if ($origin ne '') {
19557: if (grep(/^sameorigin$/,@policies)) {
19558: if ($remotehost eq $origin) {
19559: undef($uselink);
19560: }
19561: }
19562: if ($uselink) {
19563: foreach my $policy (@policies) {
19564: if ($policy =~ /^allow-from\s*(.+)$/) {
19565: my $allowfrom = $1;
19566: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19567: undef($uselink);
19568: last;
19569: }
19570: }
19571: }
19572: }
19573: }
19574: }
19575: }
19576: }
19577: }
19578: }
19579: if ($nocache) {
19580: if ($cached) {
19581: my $devalidate;
19582: if ($uselink && !$result) {
19583: $devalidate = 1;
19584: } elsif (!$uselink && $result) {
19585: $devalidate = 1;
19586: }
19587: if ($devalidate) {
19588: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19589: }
19590: }
19591: } else {
19592: if ($uselink) {
19593: $result = 1;
19594: } else {
19595: $result = 0;
19596: }
19597: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19598: }
19599: return $uselink;
19600: }
19601:
19602: sub page_menu {
19603: my ($menucolls,$menunum) = @_;
19604: my %menu;
19605: foreach my $item (split(/;/,$menucolls)) {
19606: my ($num,$value) = split(/\%/,$item);
19607: if ($num eq $menunum) {
19608: my @entries = split(/\&/,$value);
19609: foreach my $entry (@entries) {
19610: my ($name,$fields) = split(/=/,$entry);
19611: if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19612: $menu{$name} = $fields;
19613: } else {
19614: my @shown;
19615: if ($fields =~ /,/) {
19616: @shown = split(/,/,$fields);
19617: } else {
19618: @shown = ($fields);
19619: }
19620: if (@shown) {
19621: foreach my $field (@shown) {
19622: next if ($field eq '');
19623: $menu{$field} = 1;
19624: }
19625: }
19626: }
19627: }
19628: }
19629: }
19630: return %menu;
19631: }
19632:
19633: 1;
19634: __END__;
19635:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>