File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1075.2.161.2.21:
download - view:
text,
annotated -
select for diffs
Wed Feb 28 01:21:29 2024 UTC (5 months, 3 weeks ago) by
raeburn
Branches:
version_2_11_4_msu
- For 2.11.4 (modified)
Include changes in 1.1230, 1.1231, 1.1416, 1.1417, 1.1418, 1.1419, 1.1420,
1.1421, 1.1422, 1.1423, 1.1425
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.161.2.21 2024/02/28 01:21:29 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::map();
75: use HTTP::Request;
76: use DateTime::TimeZone;
77: use DateTime::Locale;
78: use Encode();
79: use Authen::Captcha;
80: use Captcha::reCAPTCHA;
81: use JSON::DWIW;
82: use LWP::UserAgent;
83: use Crypt::DES;
84: use DynaLoader; # for Crypt::DES version
85: use File::Copy();
86: use File::Path();
87: use String::CRC32();
88: use Short::URL();
89:
90: # ---------------------------------------------- Designs
91: use vars qw(%defaultdesign);
92:
93: my $readit;
94:
95:
96: ##
97: ## Global Variables
98: ##
99:
100:
101: # ----------------------------------------------- SSI with retries:
102: #
103:
104: =pod
105:
106: =head1 Server Side include with retries:
107:
108: =over 4
109:
110: =item * &ssi_with_retries(resource,retries form)
111:
112: Performs an ssi with some number of retries. Retries continue either
113: until the result is ok or until the retry count supplied by the
114: caller is exhausted.
115:
116: Inputs:
117:
118: =over 4
119:
120: resource - Identifies the resource to insert.
121:
122: retries - Count of the number of retries allowed.
123:
124: form - Hash that identifies the rendering options.
125:
126: =back
127:
128: Returns:
129:
130: =over 4
131:
132: content - The content of the response. If retries were exhausted this is empty.
133:
134: response - The response from the last attempt (which may or may not have been successful.
135:
136: =back
137:
138: =back
139:
140: =cut
141:
142: sub ssi_with_retries {
143: my ($resource, $retries, %form) = @_;
144:
145:
146: my $ok = 0; # True if we got a good response.
147: my $content;
148: my $response;
149:
150: # Try to get the ssi done. within the retries count:
151:
152: do {
153: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
154: $ok = $response->is_success;
155: if (!$ok) {
156: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
157: }
158: $retries--;
159: } while (!$ok && ($retries > 0));
160:
161: if (!$ok) {
162: $content = ''; # On error return an empty content.
163: }
164: return ($content, $response);
165:
166: }
167:
168:
169:
170: # ----------------------------------------------- Filetypes/Languages/Copyright
171: my %language;
172: my %supported_language;
173: my %latex_language; # For choosing hyphenation in <transl..>
174: my %latex_language_bykey; # for choosing hyphenation from metadata
175: my %cprtag;
176: my %scprtag;
177: my %fe; my %fd; my %fm;
178: my %category_extensions;
179:
180: # ---------------------------------------------- Thesaurus variables
181: #
182: # %Keywords:
183: # A hash used by &keyword to determine if a word is considered a keyword.
184: # $thesaurus_db_file
185: # Scalar containing the full path to the thesaurus database.
186:
187: my %Keywords;
188: my $thesaurus_db_file;
189:
190: #
191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
192: # thesaurus.tab, and filecategories.tab.
193: #
194: BEGIN {
195: # Variable initialization
196: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
197: #
198: unless ($readit) {
199: # ------------------------------------------------------------------- languages
200: {
201: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
202: '/language.tab';
203: if ( open(my $fh,'<',$langtabfile) ) {
204: while (my $line = <$fh>) {
205: next if ($line=~/^\#/);
206: chomp($line);
207: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
208: $language{$key}=$val.' - '.$enc;
209: if ($sup) {
210: $supported_language{$key}=$sup;
211: }
212: if ($latex) {
213: $latex_language_bykey{$key} = $latex;
214: $latex_language{$two} = $latex;
215: }
216: }
217: close($fh);
218: }
219: }
220: # ------------------------------------------------------------------ copyrights
221: {
222: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
223: '/copyright.tab';
224: if ( open (my $fh,'<',$copyrightfile) ) {
225: while (my $line = <$fh>) {
226: next if ($line=~/^\#/);
227: chomp($line);
228: my ($key,$val)=(split(/\s+/,$line,2));
229: $cprtag{$key}=$val;
230: }
231: close($fh);
232: }
233: }
234: # ----------------------------------------------------------- source copyrights
235: {
236: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
237: '/source_copyright.tab';
238: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
239: while (my $line = <$fh>) {
240: next if ($line =~ /^\#/);
241: chomp($line);
242: my ($key,$val)=(split(/\s+/,$line,2));
243: $scprtag{$key}=$val;
244: }
245: close($fh);
246: }
247: }
248:
249: # -------------------------------------------------------------- default domain designs
250: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
251: my $designfile = $designdir.'/default.tab';
252: if ( open (my $fh,'<',$designfile) ) {
253: while (my $line = <$fh>) {
254: next if ($line =~ /^\#/);
255: chomp($line);
256: my ($key,$val)=(split(/\=/,$line));
257: if ($val) { $defaultdesign{$key}=$val; }
258: }
259: close($fh);
260: }
261:
262: # ------------------------------------------------------------- file categories
263: {
264: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
265: '/filecategories.tab';
266: if ( open (my $fh,'<',$categoryfile) ) {
267: while (my $line = <$fh>) {
268: next if ($line =~ /^\#/);
269: chomp($line);
270: my ($extension,$category)=(split(/\s+/,$line,2));
271: push(@{$category_extensions{lc($category)}},$extension);
272: }
273: close($fh);
274: }
275:
276: }
277: # ------------------------------------------------------------------ file types
278: {
279: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
280: '/filetypes.tab';
281: if ( open (my $fh,'<',$typesfile) ) {
282: while (my $line = <$fh>) {
283: next if ($line =~ /^\#/);
284: chomp($line);
285: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
286: if ($descr ne '') {
287: $fe{$ending}=lc($emb);
288: $fd{$ending}=$descr;
289: if ($mime ne 'unk') { $fm{$ending}=$mime; }
290: }
291: }
292: close($fh);
293: }
294: }
295: &Apache::lonnet::logthis(
296: "<span style='color:yellow;'>INFO: Read file types</span>");
297: $readit=1;
298: } # end of unless($readit)
299:
300: }
301:
302: ###############################################################
303: ## HTML and Javascript Helper Functions ##
304: ###############################################################
305:
306: =pod
307:
308: =head1 HTML and Javascript Functions
309:
310: =over 4
311:
312: =item * &browser_and_searcher_javascript()
313:
314: X<browsing, javascript>X<searching, javascript>Returns a string
315: containing javascript with two functions, C<openbrowser> and
316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
317: tags.
318:
319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
320:
321: inputs: formname, elementname, only, omit
322:
323: formname and elementname indicate the name of the html form and name of
324: the element that the results of the browsing selection are to be placed in.
325:
326: Specifying 'only' will restrict the browser to displaying only files
327: with the given extension. Can be a comma separated list.
328:
329: Specifying 'omit' will restrict the browser to NOT displaying files
330: with the given extension. Can be a comma separated list.
331:
332: =item * &opensearcher(formname,elementname) [javascript]
333:
334: Inputs: formname, elementname
335:
336: formname and elementname specify the name of the html form and the name
337: of the element the selection from the search results will be placed in.
338:
339: =cut
340:
341: sub browser_and_searcher_javascript {
342: my ($mode)=@_;
343: if (!defined($mode)) { $mode='edit'; }
344: my $resurl=&escape_single(&lastresurl());
345: return <<END;
346: // <!-- BEGIN LON-CAPA Internal
347: var editbrowser = null;
348: function openbrowser(formname,elementname,only,omit,titleelement) {
349: var url = '$resurl/?';
350: if (editbrowser == null) {
351: url += 'launch=1&';
352: }
353: url += 'catalogmode=interactive&';
354: url += 'mode=$mode&';
355: url += 'inhibitmenu=yes&';
356: url += 'form=' + formname + '&';
357: if (only != null) {
358: url += 'only=' + only + '&';
359: } else {
360: url += 'only=&';
361: }
362: if (omit != null) {
363: url += 'omit=' + omit + '&';
364: } else {
365: url += 'omit=&';
366: }
367: if (titleelement != null) {
368: url += 'titleelement=' + titleelement + '&';
369: } else {
370: url += 'titleelement=&';
371: }
372: url += 'element=' + elementname + '';
373: var title = 'Browser';
374: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
375: options += ',width=700,height=600';
376: editbrowser = open(url,title,options,'1');
377: editbrowser.focus();
378: }
379: var editsearcher;
380: function opensearcher(formname,elementname,titleelement) {
381: var url = '/adm/searchcat?';
382: if (editsearcher == null) {
383: url += 'launch=1&';
384: }
385: url += 'catalogmode=interactive&';
386: url += 'mode=$mode&';
387: url += 'form=' + formname + '&';
388: if (titleelement != null) {
389: url += 'titleelement=' + titleelement + '&';
390: } else {
391: url += 'titleelement=&';
392: }
393: url += 'element=' + elementname + '';
394: var title = 'Search';
395: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
396: options += ',width=700,height=600';
397: editsearcher = open(url,title,options,'1');
398: editsearcher.focus();
399: }
400: // END LON-CAPA Internal -->
401: END
402: }
403:
404: sub lastresurl {
405: if ($env{'environment.lastresurl'}) {
406: return $env{'environment.lastresurl'}
407: } else {
408: return '/res';
409: }
410: }
411:
412: sub storeresurl {
413: my $resurl=&Apache::lonnet::clutter(shift);
414: unless ($resurl=~/^\/res/) { return 0; }
415: $resurl=~s/\/$//;
416: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
417: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
418: return 1;
419: }
420:
421: sub studentbrowser_javascript {
422: unless (
423: (($env{'request.course.id'}) &&
424: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
425: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
426: '/'.$env{'request.course.sec'})
427: ))
428: || ($env{'request.role'}=~/^(au|dc|su)/)
429: ) { return ''; }
430: return (<<'ENDSTDBRW');
431: <script type="text/javascript" language="Javascript">
432: // <![CDATA[
433: var stdeditbrowser;
434: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
435: var url = '/adm/pickstudent?';
436: var filter;
437: if (!ignorefilter) {
438: eval('filter=document.'+formname+'.'+uname+'.value;');
439: }
440: if (filter != null) {
441: if (filter != '') {
442: url += 'filter='+filter+'&';
443: }
444: }
445: url += 'form=' + formname + '&unameelement='+uname+
446: '&udomelement='+udom+
447: '&clicker='+clicker;
448: if (roleflag) { url+="&roles=1"; }
449: if (courseadv == 'condition') {
450: if (document.getElementById('courseadv')) {
451: courseadv = document.getElementById('courseadv').value;
452: }
453: }
454: if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
455: if (uident !== '') { url+="&identelement="+uident; }
456: var title = 'Student_Browser';
457: var options = 'scrollbars=1,resizable=1,menubar=0';
458: options += ',width=700,height=600';
459: stdeditbrowser = open(url,title,options,'1');
460: stdeditbrowser.focus();
461: }
462: // ]]>
463: </script>
464: ENDSTDBRW
465: }
466:
467: sub resourcebrowser_javascript {
468: unless ($env{'request.course.id'}) { return ''; }
469: return (<<'ENDRESBRW');
470: <script type="text/javascript" language="Javascript">
471: // <![CDATA[
472: var reseditbrowser;
473: function openresbrowser(formname,reslink) {
474: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
475: var title = 'Resource_Browser';
476: var options = 'scrollbars=1,resizable=1,menubar=0';
477: options += ',width=700,height=500';
478: reseditbrowser = open(url,title,options,'1');
479: reseditbrowser.focus();
480: }
481: // ]]>
482: </script>
483: ENDRESBRW
484: }
485:
486: sub selectstudent_link {
487: my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
488: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
489: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
490: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
491: if ($env{'request.course.id'}) {
492: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
493: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
494: '/'.$env{'request.course.sec'})) {
495: return '';
496: }
497: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
498: if ($courseadv eq 'only') {
499: $callargs .= ",'',1,'$courseadv'";
500: } elsif ($courseadv eq 'none') {
501: $callargs .= ",'','','$courseadv'";
502: } elsif ($courseadv eq 'condition') {
503: $callargs .= ",'','','$courseadv'";
504: } elsif ($identelem ne '') {
505: $callargs .= ",'','',''";
506: }
507: if ($identelem ne '') {
508: $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
509: }
510: return '<span class="LC_nobreak">'.
511: '<a href="javascript:openstdbrowser('.$callargs.');">'.
512: &mt('Select User').'</a></span>';
513: }
514: if ($env{'request.role'}=~/^(au|dc|su)/) {
515: $callargs .= ",'',1";
516: return '<span class="LC_nobreak">'.
517: '<a href="javascript:openstdbrowser('.$callargs.');">'.
518: &mt('Select User').'</a></span>';
519: }
520: return '';
521: }
522:
523: sub selectresource_link {
524: my ($form,$reslink,$arg)=@_;
525:
526: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
527: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
528: unless ($env{'request.course.id'}) { return $arg; }
529: return '<span class="LC_nobreak">'.
530: '<a href="javascript:openresbrowser('.$callargs.');">'.
531: $arg.'</a></span>';
532: }
533:
534:
535:
536: sub authorbrowser_javascript {
537: return <<"ENDAUTHORBRW";
538: <script type="text/javascript" language="JavaScript">
539: // <![CDATA[
540: var stdeditbrowser;
541:
542: function openauthorbrowser(formname,udom) {
543: var url = '/adm/pickauthor?';
544: url += 'form='+formname+'&roledom='+udom;
545: var title = 'Author_Browser';
546: var options = 'scrollbars=1,resizable=1,menubar=0';
547: options += ',width=700,height=600';
548: stdeditbrowser = open(url,title,options,'1');
549: stdeditbrowser.focus();
550: }
551:
552: // ]]>
553: </script>
554: ENDAUTHORBRW
555: }
556:
557: sub coursebrowser_javascript {
558: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
559: $credits_element,$instcode) = @_;
560: my $wintitle = 'Course_Browser';
561: if ($crstype eq 'Community') {
562: $wintitle = 'Community_Browser';
563: }
564: my $id_functions = &javascript_index_functions();
565: my $output = '
566: <script type="text/javascript" language="JavaScript">
567: // <![CDATA[
568: var stdeditbrowser;'."\n";
569:
570: $output .= <<"ENDSTDBRW";
571: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
572: var url = '/adm/pickcourse?';
573: var formid = getFormIdByName(formname);
574: var domainfilter = getDomainFromSelectbox(formname,udom);
575: if (domainfilter != null) {
576: if (domainfilter != '') {
577: url += 'domainfilter='+domainfilter+'&';
578: }
579: }
580: url += 'form=' + formname + '&cnumelement='+uname+
581: '&cdomelement='+udom+
582: '&cnameelement='+desc;
583: if (extra_element !=null && extra_element != '') {
584: if (formname == 'rolechoice' || formname == 'studentform') {
585: url += '&roleelement='+extra_element;
586: if (domainfilter == null || domainfilter == '') {
587: url += '&domainfilter='+extra_element;
588: }
589: }
590: else {
591: if (formname == 'portform') {
592: url += '&setroles='+extra_element;
593: } else {
594: if (formname == 'rules') {
595: url += '&fixeddom='+extra_element;
596: }
597: }
598: }
599: }
600: if (type != null && type != '') {
601: url += '&type='+type;
602: }
603: if (type_elem != null && type_elem != '') {
604: url += '&typeelement='+type_elem;
605: }
606: if (formname == 'ccrs') {
607: var ownername = document.forms[formid].ccuname.value;
608: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
609: url += '&cloner='+ownername+':'+ownerdom;
610: if (type == 'Course') {
611: url += '&crscode='+document.forms[formid].crscode.value;
612: }
613: }
614: if (formname == 'requestcrs') {
615: url += '&crsdom=$domainfilter&crscode=$instcode';
616: }
617: if (multflag !=null && multflag != '') {
618: url += '&multiple='+multflag;
619: }
620: var title = '$wintitle';
621: var options = 'scrollbars=1,resizable=1,menubar=0';
622: options += ',width=700,height=600';
623: stdeditbrowser = open(url,title,options,'1');
624: stdeditbrowser.focus();
625: }
626: $id_functions
627: ENDSTDBRW
628: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
629: $output .= &setsec_javascript($sec_element,$formname,$role_element,
630: $credits_element);
631: }
632: $output .= '
633: // ]]>
634: </script>';
635: return $output;
636: }
637:
638: sub javascript_index_functions {
639: return <<"ENDJS";
640:
641: function getFormIdByName(formname) {
642: for (var i=0;i<document.forms.length;i++) {
643: if (document.forms[i].name == formname) {
644: return i;
645: }
646: }
647: return -1;
648: }
649:
650: function getIndexByName(formid,item) {
651: for (var i=0;i<document.forms[formid].elements.length;i++) {
652: if (document.forms[formid].elements[i].name == item) {
653: return i;
654: }
655: }
656: return -1;
657: }
658:
659: function getDomainFromSelectbox(formname,udom) {
660: var userdom;
661: var formid = getFormIdByName(formname);
662: if (formid > -1) {
663: var domid = getIndexByName(formid,udom);
664: if (domid > -1) {
665: if (document.forms[formid].elements[domid].type == 'select-one') {
666: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
667: }
668: if (document.forms[formid].elements[domid].type == 'hidden') {
669: userdom=document.forms[formid].elements[domid].value;
670: }
671: }
672: }
673: return userdom;
674: }
675:
676: ENDJS
677:
678: }
679:
680: sub javascript_array_indexof {
681: return <<ENDJS;
682: <script type="text/javascript" language="JavaScript">
683: // <![CDATA[
684:
685: if (!Array.prototype.indexOf) {
686: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
687: "use strict";
688: if (this === void 0 || this === null) {
689: throw new TypeError();
690: }
691: var t = Object(this);
692: var len = t.length >>> 0;
693: if (len === 0) {
694: return -1;
695: }
696: var n = 0;
697: if (arguments.length > 0) {
698: n = Number(arguments[1]);
699: if (n !== n) { // shortcut for verifying if it's NaN
700: n = 0;
701: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
702: n = (n > 0 || -1) * Math.floor(Math.abs(n));
703: }
704: }
705: if (n >= len) {
706: return -1;
707: }
708: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
709: for (; k < len; k++) {
710: if (k in t && t[k] === searchElement) {
711: return k;
712: }
713: }
714: return -1;
715: }
716: }
717:
718: // ]]>
719: </script>
720:
721: ENDJS
722:
723: }
724:
725: sub userbrowser_javascript {
726: my $id_functions = &javascript_index_functions();
727: return <<"ENDUSERBRW";
728:
729: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
730: var url = '/adm/pickuser?';
731: var userdom = getDomainFromSelectbox(formname,udom);
732: if (userdom != null) {
733: if (userdom != '') {
734: url += 'srchdom='+userdom+'&';
735: }
736: }
737: url += 'form=' + formname + '&unameelement='+uname+
738: '&udomelement='+udom+
739: '&ulastelement='+ulast+
740: '&ufirstelement='+ufirst+
741: '&uemailelement='+uemail+
742: '&hideudomelement='+hideudom+
743: '&coursedom='+crsdom;
744: if ((caller != null) && (caller != undefined)) {
745: url += '&caller='+caller;
746: }
747: var title = 'User_Browser';
748: var options = 'scrollbars=1,resizable=1,menubar=0';
749: options += ',width=700,height=600';
750: var stdeditbrowser = open(url,title,options,'1');
751: stdeditbrowser.focus();
752: }
753:
754: function fix_domain (formname,udom,origdom,uname) {
755: var formid = getFormIdByName(formname);
756: if (formid > -1) {
757: var unameid = getIndexByName(formid,uname);
758: var domid = getIndexByName(formid,udom);
759: var hidedomid = getIndexByName(formid,origdom);
760: if (hidedomid > -1) {
761: var fixeddom = document.forms[formid].elements[hidedomid].value;
762: var unameval = document.forms[formid].elements[unameid].value;
763: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
764: if (domid > -1) {
765: var slct = document.forms[formid].elements[domid];
766: if (slct.type == 'select-one') {
767: var i;
768: for (i=0;i<slct.length;i++) {
769: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
770: }
771: }
772: if (slct.type == 'hidden') {
773: slct.value = fixeddom;
774: }
775: }
776: }
777: }
778: }
779: return;
780: }
781:
782: $id_functions
783: ENDUSERBRW
784: }
785:
786: sub setsec_javascript {
787: my ($sec_element,$formname,$role_element,$credits_element) = @_;
788: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
789: $communityrolestr);
790: if ($role_element ne '') {
791: my @allroles = ('st','ta','ep','in','ad');
792: foreach my $crstype ('Course','Community') {
793: if ($crstype eq 'Community') {
794: foreach my $role (@allroles) {
795: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
796: }
797: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
798: } else {
799: foreach my $role (@allroles) {
800: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
801: }
802: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
803: }
804: }
805: $rolestr = '"'.join('","',@allroles).'"';
806: $courserolestr = '"'.join('","',@courserolenames).'"';
807: $communityrolestr = '"'.join('","',@communityrolenames).'"';
808: }
809: my $setsections = qq|
810: function setSect(sectionlist) {
811: var sectionsArray = new Array();
812: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
813: sectionsArray = sectionlist.split(",");
814: }
815: var numSections = sectionsArray.length;
816: document.$formname.$sec_element.length = 0;
817: if (numSections == 0) {
818: document.$formname.$sec_element.multiple=false;
819: document.$formname.$sec_element.size=1;
820: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
821: } else {
822: if (numSections == 1) {
823: document.$formname.$sec_element.multiple=false;
824: document.$formname.$sec_element.size=1;
825: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
826: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
827: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
828: } else {
829: for (var i=0; i<numSections; i++) {
830: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
831: }
832: document.$formname.$sec_element.multiple=true
833: if (numSections < 3) {
834: document.$formname.$sec_element.size=numSections;
835: } else {
836: document.$formname.$sec_element.size=3;
837: }
838: document.$formname.$sec_element.options[0].selected = false
839: }
840: }
841: }
842:
843: function setRole(crstype) {
844: |;
845: if ($role_element eq '') {
846: $setsections .= ' return;
847: }
848: ';
849: } else {
850: $setsections .= qq|
851: var elementLength = document.$formname.$role_element.length;
852: var allroles = Array($rolestr);
853: var courserolenames = Array($courserolestr);
854: var communityrolenames = Array($communityrolestr);
855: if (elementLength != undefined) {
856: if (document.$formname.$role_element.options[5].value == 'cc') {
857: if (crstype == 'Course') {
858: return;
859: } else {
860: allroles[5] = 'co';
861: for (var i=0; i<6; i++) {
862: document.$formname.$role_element.options[i].value = allroles[i];
863: document.$formname.$role_element.options[i].text = communityrolenames[i];
864: }
865: }
866: } else {
867: if (crstype == 'Community') {
868: return;
869: } else {
870: allroles[5] = 'cc';
871: for (var i=0; i<6; i++) {
872: document.$formname.$role_element.options[i].value = allroles[i];
873: document.$formname.$role_element.options[i].text = courserolenames[i];
874: }
875: }
876: }
877: }
878: return;
879: }
880: |;
881: }
882: if ($credits_element) {
883: $setsections .= qq|
884: function setCredits(defaultcredits) {
885: document.$formname.$credits_element.value = defaultcredits;
886: return;
887: }
888: |;
889: }
890: return $setsections;
891: }
892:
893: sub selectcourse_link {
894: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
895: $typeelement) = @_;
896: my $type = $selecttype;
897: my $linktext = &mt('Select Course');
898: if ($selecttype eq 'Community') {
899: $linktext = &mt('Select Community');
900: } elsif ($selecttype eq 'Course/Community') {
901: $linktext = &mt('Select Course/Community');
902: $type = '';
903: } elsif ($selecttype eq 'Select') {
904: $linktext = &mt('Select');
905: $type = '';
906: }
907: return '<span class="LC_nobreak">'
908: ."<a href='"
909: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
910: .'","'.$udomele.'","'.$desc.'","'.$extra_element
911: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
912: ."'>".$linktext.'</a>'
913: .'</span>';
914: }
915:
916: sub selectauthor_link {
917: my ($form,$udom)=@_;
918: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
919: &mt('Select Author').'</a>';
920: }
921:
922: sub selectuser_link {
923: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
924: $coursedom,$linktext,$caller) = @_;
925: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
926: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
927: ');">'.$linktext.'</a>';
928: }
929:
930: sub check_uncheck_jscript {
931: my $jscript = <<"ENDSCRT";
932: function checkAll(field) {
933: if (field.length > 0) {
934: for (i = 0; i < field.length; i++) {
935: if (!field[i].disabled) {
936: field[i].checked = true;
937: }
938: }
939: } else {
940: if (!field.disabled) {
941: field.checked = true;
942: }
943: }
944: }
945:
946: function uncheckAll(field) {
947: if (field.length > 0) {
948: for (i = 0; i < field.length; i++) {
949: field[i].checked = false ;
950: }
951: } else {
952: field.checked = false ;
953: }
954: }
955: ENDSCRT
956: return $jscript;
957: }
958:
959: sub select_timezone {
960: my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
961: my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
962: if ($includeempty) {
963: $output .= '<option value=""';
964: if (($selected eq '') || ($selected eq 'local')) {
965: $output .= ' selected="selected" ';
966: }
967: $output .= '> </option>';
968: }
969: my @timezones = DateTime::TimeZone->all_names;
970: foreach my $tzone (@timezones) {
971: $output.= '<option value="'.$tzone.'"';
972: if ($tzone eq $selected) {
973: $output.=' selected="selected"';
974: }
975: $output.=">$tzone</option>\n";
976: }
977: $output.="</select>";
978: return $output;
979: }
980:
981: sub select_datelocale {
982: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
983: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
984: if ($includeempty) {
985: $output .= '<option value=""';
986: if ($selected eq '') {
987: $output .= ' selected="selected" ';
988: }
989: $output .= '> </option>';
990: }
991: my @languages = &Apache::lonlocal::preferred_languages();
992: my (@possibles,%locale_names);
993: my @locales = DateTime::Locale->ids();
994: foreach my $id (@locales) {
995: if ($id ne '') {
996: my ($en_terr,$native_terr);
997: my $loc = DateTime::Locale->load($id);
998: if (ref($loc)) {
999: $en_terr = $loc->name();
1000: $native_terr = $loc->native_name();
1001: if (grep(/^en$/,@languages) || !@languages) {
1002: if ($en_terr ne '') {
1003: $locale_names{$id} = '('.$en_terr.')';
1004: } elsif ($native_terr ne '') {
1005: $locale_names{$id} = $native_terr;
1006: }
1007: } else {
1008: if ($native_terr ne '') {
1009: $locale_names{$id} = $native_terr.' ';
1010: } elsif ($en_terr ne '') {
1011: $locale_names{$id} = '('.$en_terr.')';
1012: }
1013: }
1014: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1015: push(@possibles,$id);
1016: }
1017: }
1018: }
1019: foreach my $item (sort(@possibles)) {
1020: $output.= '<option value="'.$item.'"';
1021: if ($item eq $selected) {
1022: $output.=' selected="selected"';
1023: }
1024: $output.=">$item";
1025: if ($locale_names{$item} ne '') {
1026: $output.=' '.$locale_names{$item};
1027: }
1028: $output.="</option>\n";
1029: }
1030: $output.="</select>";
1031: return $output;
1032: }
1033:
1034: sub select_language {
1035: my ($name,$selected,$includeempty,$noedit) = @_;
1036: my %langchoices;
1037: if ($includeempty) {
1038: %langchoices = ('' => 'No language preference');
1039: }
1040: foreach my $id (&languageids()) {
1041: my $code = &supportedlanguagecode($id);
1042: if ($code) {
1043: $langchoices{$code} = &plainlanguagedescription($id);
1044: }
1045: }
1046: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1047: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1048: }
1049:
1050: =pod
1051:
1052: =item * &linked_select_forms(...)
1053:
1054: linked_select_forms returns a string containing a <script></script> block
1055: and html for two <select> menus. The select menus will be linked in that
1056: changing the value of the first menu will result in new values being placed
1057: in the second menu. The values in the select menu will appear in alphabetical
1058: order unless a defined order is provided.
1059:
1060: linked_select_forms takes the following ordered inputs:
1061:
1062: =over 4
1063:
1064: =item * $formname, the name of the <form> tag
1065:
1066: =item * $middletext, the text which appears between the <select> tags
1067:
1068: =item * $firstdefault, the default value for the first menu
1069:
1070: =item * $firstselectname, the name of the first <select> tag
1071:
1072: =item * $secondselectname, the name of the second <select> tag
1073:
1074: =item * $hashref, a reference to a hash containing the data for the menus.
1075:
1076: =item * $menuorder, the order of values in the first menu
1077:
1078: =item * $onchangefirst, additional javascript call to execute for an onchange
1079: event for the first <select> tag
1080:
1081: =item * $onchangesecond, additional javascript call to execute for an onchange
1082: event for the second <select> tag
1083:
1084: =back
1085:
1086: Below is an example of such a hash. Only the 'text', 'default', and
1087: 'select2' keys must appear as stated. keys(%menu) are the possible
1088: values for the first select menu. The text that coincides with the
1089: first menu value is given in $menu{$choice1}->{'text'}. The values
1090: and text for the second menu are given in the hash pointed to by
1091: $menu{$choice1}->{'select2'}.
1092:
1093: my %menu = ( A1 => { text =>"Choice A1" ,
1094: default => "B3",
1095: select2 => {
1096: B1 => "Choice B1",
1097: B2 => "Choice B2",
1098: B3 => "Choice B3",
1099: B4 => "Choice B4"
1100: },
1101: order => ['B4','B3','B1','B2'],
1102: },
1103: A2 => { text =>"Choice A2" ,
1104: default => "C2",
1105: select2 => {
1106: C1 => "Choice C1",
1107: C2 => "Choice C2",
1108: C3 => "Choice C3"
1109: },
1110: order => ['C2','C1','C3'],
1111: },
1112: A3 => { text =>"Choice A3" ,
1113: default => "D6",
1114: select2 => {
1115: D1 => "Choice D1",
1116: D2 => "Choice D2",
1117: D3 => "Choice D3",
1118: D4 => "Choice D4",
1119: D5 => "Choice D5",
1120: D6 => "Choice D6",
1121: D7 => "Choice D7"
1122: },
1123: order => ['D4','D3','D2','D1','D7','D6','D5'],
1124: }
1125: );
1126:
1127: =cut
1128:
1129: sub linked_select_forms {
1130: my ($formname,
1131: $middletext,
1132: $firstdefault,
1133: $firstselectname,
1134: $secondselectname,
1135: $hashref,
1136: $menuorder,
1137: $onchangefirst,
1138: $onchangesecond
1139: ) = @_;
1140: my $second = "document.$formname.$secondselectname";
1141: my $first = "document.$formname.$firstselectname";
1142: # output the javascript to do the changing
1143: my $result = '';
1144: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1145: $result.="// <![CDATA[\n";
1146: $result.="var select2data = new Object();\n";
1147: $" = '","';
1148: my $debug = '';
1149: foreach my $s1 (sort(keys(%$hashref))) {
1150: $result.="select2data.d_$s1 = new Object();\n";
1151: $result.="select2data.d_$s1.def = new String('".
1152: $hashref->{$s1}->{'default'}."');\n";
1153: $result.="select2data.d_$s1.values = new Array(";
1154: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1155: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1156: @s2values = @{$hashref->{$s1}->{'order'}};
1157: }
1158: $result.="\"@s2values\");\n";
1159: $result.="select2data.d_$s1.texts = new Array(";
1160: my @s2texts;
1161: foreach my $value (@s2values) {
1162: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1163: }
1164: $result.="\"@s2texts\");\n";
1165: }
1166: $"=' ';
1167: $result.= <<"END";
1168:
1169: function select1_changed() {
1170: // Determine new choice
1171: var newvalue = "d_" + $first.value;
1172: // update select2
1173: var values = select2data[newvalue].values;
1174: var texts = select2data[newvalue].texts;
1175: var select2def = select2data[newvalue].def;
1176: var i;
1177: // out with the old
1178: for (i = 0; i < $second.options.length; i++) {
1179: $second.options[i] = null;
1180: }
1181: // in with the nuclear
1182: for (i=0;i<values.length; i++) {
1183: $second.options[i] = new Option(values[i]);
1184: $second.options[i].value = values[i];
1185: $second.options[i].text = texts[i];
1186: if (values[i] == select2def) {
1187: $second.options[i].selected = true;
1188: }
1189: }
1190: }
1191: // ]]>
1192: </script>
1193: END
1194: # output the initial values for the selection lists
1195: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1196: my @order = sort(keys(%{$hashref}));
1197: if (ref($menuorder) eq 'ARRAY') {
1198: @order = @{$menuorder};
1199: }
1200: foreach my $value (@order) {
1201: $result.=" <option value=\"$value\" ";
1202: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1203: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1204: }
1205: $result .= "</select>\n";
1206: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1207: $result .= $middletext;
1208: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1209: if ($onchangesecond) {
1210: $result .= ' onchange="'.$onchangesecond.'"';
1211: }
1212: $result .= ">\n";
1213: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1214:
1215: my @secondorder = sort(keys(%select2));
1216: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1217: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1218: }
1219: foreach my $value (@secondorder) {
1220: $result.=" <option value=\"$value\" ";
1221: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1222: $result.=">".&mt($select2{$value})."</option>\n";
1223: }
1224: $result .= "</select>\n";
1225: # return $debug;
1226: return $result;
1227: } # end of sub linked_select_forms {
1228:
1229: =pod
1230:
1231: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1232:
1233: Returns a string corresponding to an HTML link to the given help
1234: $topic, where $topic corresponds to the name of a .tex file in
1235: /home/httpd/html/adm/help/tex, with underscores replaced by
1236: spaces.
1237:
1238: $text will optionally be linked to the same topic, allowing you to
1239: link text in addition to the graphic. If you do not want to link
1240: text, but wish to specify one of the later parameters, pass an
1241: empty string.
1242:
1243: $stayOnPage is a value that will be interpreted as a boolean. If true,
1244: the link will not open a new window. If false, the link will open
1245: a new window using Javascript. (Default is false.)
1246:
1247: $width and $height are optional numerical parameters that will
1248: override the width and height of the popped up window, which may
1249: be useful for certain help topics with big pictures included.
1250:
1251: $imgid is the id of the img tag used for the help icon. This may be
1252: used in a javascript call to switch the image src. See
1253: lonhtmlcommon::htmlareaselectactive() for an example.
1254:
1255: $links_target will optionally be set to a target (_top, _parent or _self).
1256:
1257: =cut
1258:
1259: sub help_open_topic {
1260: my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1261: $text = "" if (not defined $text);
1262: $stayOnPage = 0 if (not defined $stayOnPage);
1263: $width = 500 if (not defined $width);
1264: $height = 400 if (not defined $height);
1265: my $filename = $topic;
1266: $filename =~ s/ /_/g;
1267:
1268: my $template = "";
1269: my $link;
1270:
1271: $topic=~s/\W/\_/g;
1272:
1273: if (!$stayOnPage) {
1274: if ($env{'browser.mobile'}) {
1275: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1276: } else {
1277: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1278: }
1279: } elsif ($stayOnPage eq 'popup') {
1280: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1281: } else {
1282: $link = "/adm/help/${filename}.hlp";
1283: }
1284:
1285: # Add the text
1286: my $target = ' target="_top"';
1287: if ($links_target) {
1288: $target = ' target="'.$links_target.'"';
1289: } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1290: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1291: $target = '';
1292: }
1293: if ($text ne "") {
1294: $template.='<span class="LC_help_open_topic">'
1295: .'<a'.$target.' href="'.$link.'">'
1296: .$text.'</a>';
1297: }
1298:
1299: # (Always) Add the graphic
1300: my $title = &mt('Online Help');
1301: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1302: if ($imgid ne '') {
1303: $imgid = ' id="'.$imgid.'"';
1304: }
1305: $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1306: .'<img src="'.$helpicon.'" border="0"'
1307: .' alt="'.&mt('Help: [_1]',$topic).'"'
1308: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1309: .' /></a>';
1310: if ($text ne "") {
1311: $template.='</span>';
1312: }
1313: return $template;
1314:
1315: }
1316:
1317: # This is a quicky function for Latex cheatsheet editing, since it
1318: # appears in at least four places
1319: sub helpLatexCheatsheet {
1320: my ($topic,$text,$not_author,$stayOnPage) = @_;
1321: my $out;
1322: my $addOther = '';
1323: if ($topic) {
1324: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1325: }
1326: $out = '<span>' # Start cheatsheet
1327: .$addOther
1328: .'<span>'
1329: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1330: .'</span> <span>'
1331: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1332: .'</span>';
1333: unless ($not_author) {
1334: $out .= ' <span>'
1335: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1336: .'</span> <span>'
1337: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1338: .'</span>';
1339: }
1340: $out .= '</span>'; # End cheatsheet
1341: return $out;
1342: }
1343:
1344: sub general_help {
1345: my $helptopic='Student_Intro';
1346: if ($env{'request.role'}=~/^(ca|au)/) {
1347: $helptopic='Authoring_Intro';
1348: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1349: $helptopic='Course_Coordination_Intro';
1350: } elsif ($env{'request.role'}=~/^dc/) {
1351: $helptopic='Domain_Coordination_Intro';
1352: }
1353: return $helptopic;
1354: }
1355:
1356: sub update_help_link {
1357: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1358: my $origurl = $ENV{'REQUEST_URI'};
1359: $origurl=~s|^/~|/priv/|;
1360: my $timestamp = time;
1361: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1362: $$datum = &escape($$datum);
1363: }
1364:
1365: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1366: my $output .= <<"ENDOUTPUT";
1367: <script type="text/javascript">
1368: // <![CDATA[
1369: banner_link = '$banner_link';
1370: // ]]>
1371: </script>
1372: ENDOUTPUT
1373: return $output;
1374: }
1375:
1376: # now just updates the help link and generates a blue icon
1377: sub help_open_menu {
1378: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target)
1379: = @_;
1380: $stayOnPage = 1;
1381: my $output;
1382: if ($component_help) {
1383: if (!$text) {
1384: $output=&help_open_topic($component_help,undef,$stayOnPage,
1385: $width,$height,'',$links_target);
1386: } else {
1387: my $help_text;
1388: $help_text=&unescape($topic);
1389: $output='<table><tr><td>'.
1390: &help_open_topic($component_help,$help_text,$stayOnPage,
1391: $width,$height,'',$links_target).'</td></tr></table>';
1392: }
1393: }
1394: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1395: return $output.$banner_link;
1396: }
1397:
1398: sub top_nav_help {
1399: my ($text,$linkattr) = @_;
1400: $text = &mt($text);
1401: my $stay_on_page;
1402: unless ($env{'environment.remote'} eq 'on') {
1403: $stay_on_page = 1;
1404: }
1405: my ($link,$banner_link);
1406: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1407: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1408: : "javascript:helpMenu('open')";
1409: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1410: }
1411: my $title = &mt('Get help');
1412: if ($link) {
1413: return <<"END";
1414: $banner_link
1415: <a href="$link" title="$title" $linkattr>$text</a>
1416: END
1417: } else {
1418: return ' '.$text.' ';
1419: }
1420: }
1421:
1422: sub help_menu_js {
1423: my ($httphost) = @_;
1424: my $stayOnPage = 1;
1425: my $width = 620;
1426: my $height = 600;
1427: my $helptopic=&general_help();
1428: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1429: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1430: my $start_page =
1431: &Apache::loncommon::start_page('Help Menu', undef,
1432: {'frameset' => 1,
1433: 'js_ready' => 1,
1434: 'use_absolute' => $httphost,
1435: 'add_entries' => {
1436: 'border' => '0',
1437: 'rows' => "110,*",},});
1438: my $end_page =
1439: &Apache::loncommon::end_page({'frameset' => 1,
1440: 'js_ready' => 1,});
1441:
1442: my $template .= <<"ENDTEMPLATE";
1443: <script type="text/javascript">
1444: // <![CDATA[
1445: // <!-- BEGIN LON-CAPA Internal
1446: var banner_link = '';
1447: function helpMenu(target) {
1448: var caller = this;
1449: if (target == 'open') {
1450: var newWindow = null;
1451: try {
1452: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1453: }
1454: catch(error) {
1455: writeHelp(caller);
1456: return;
1457: }
1458: if (newWindow) {
1459: caller = newWindow;
1460: }
1461: }
1462: writeHelp(caller);
1463: return;
1464: }
1465: function writeHelp(caller) {
1466: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1467: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1468: caller.document.close();
1469: caller.focus();
1470: }
1471: // END LON-CAPA Internal -->
1472: // ]]>
1473: </script>
1474: ENDTEMPLATE
1475: return $template;
1476: }
1477:
1478: sub help_open_bug {
1479: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1480: unless ($env{'user.adv'}) { return ''; }
1481: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1482: $text = "" if (not defined $text);
1483: $stayOnPage=1;
1484: $width = 600 if (not defined $width);
1485: $height = 600 if (not defined $height);
1486:
1487: $topic=~s/\W+/\+/g;
1488: my $link='';
1489: my $template='';
1490: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1491: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1492: if (!$stayOnPage)
1493: {
1494: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1495: }
1496: else
1497: {
1498: $link = $url;
1499: }
1500:
1501: my $target = '_top';
1502: if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1503: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1504: $target = '_blank';
1505: }
1506:
1507: # Add the text
1508: if ($text ne "")
1509: {
1510: $template .=
1511: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1512: "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1513: }
1514:
1515: # Add the graphic
1516: my $title = &mt('Report a Bug');
1517: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1518: $template .= <<"ENDTEMPLATE";
1519: <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1520: ENDTEMPLATE
1521: if ($text ne '') { $template.='</td></tr></table>' };
1522: return $template;
1523:
1524: }
1525:
1526: sub help_open_faq {
1527: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1528: unless ($env{'user.adv'}) { return ''; }
1529: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1530: $text = "" if (not defined $text);
1531: $stayOnPage=1;
1532: $width = 350 if (not defined $width);
1533: $height = 400 if (not defined $height);
1534:
1535: $topic=~s/\W+/\+/g;
1536: my $link='';
1537: my $template='';
1538: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1539: if (!$stayOnPage)
1540: {
1541: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1542: }
1543: else
1544: {
1545: $link = $url;
1546: }
1547:
1548: # Add the text
1549: if ($text ne "")
1550: {
1551: $template .=
1552: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1553: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1554: }
1555:
1556: # Add the graphic
1557: my $title = &mt('View the FAQ');
1558: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1559: $template .= <<"ENDTEMPLATE";
1560: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1561: ENDTEMPLATE
1562: if ($text ne '') { $template.='</td></tr></table>' };
1563: return $template;
1564:
1565: }
1566:
1567: ###############################################################
1568: ###############################################################
1569:
1570: =pod
1571:
1572: =item * &change_content_javascript():
1573:
1574: This and the next function allow you to create small sections of an
1575: otherwise static HTML page that you can update on the fly with
1576: Javascript, even in Netscape 4.
1577:
1578: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1579: must be written to the HTML page once. It will prove the Javascript
1580: function "change(name, content)". Calling the change function with the
1581: name of the section
1582: you want to update, matching the name passed to C<changable_area>, and
1583: the new content you want to put in there, will put the content into
1584: that area.
1585:
1586: B<Note>: Netscape 4 only reserves enough space for the changable area
1587: to contain room for the original contents. You need to "make space"
1588: for whatever changes you wish to make, and be B<sure> to check your
1589: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1590: it's adequate for updating a one-line status display, but little more.
1591: This script will set the space to 100% width, so you only need to
1592: worry about height in Netscape 4.
1593:
1594: Modern browsers are much less limiting, and if you can commit to the
1595: user not using Netscape 4, this feature may be used freely with
1596: pretty much any HTML.
1597:
1598: =cut
1599:
1600: sub change_content_javascript {
1601: # If we're on Netscape 4, we need to use Layer-based code
1602: if ($env{'browser.type'} eq 'netscape' &&
1603: $env{'browser.version'} =~ /^4\./) {
1604: return (<<NETSCAPE4);
1605: function change(name, content) {
1606: doc = document.layers[name+"___escape"].layers[0].document;
1607: doc.open();
1608: doc.write(content);
1609: doc.close();
1610: }
1611: NETSCAPE4
1612: } else {
1613: # Otherwise, we need to use semi-standards-compliant code
1614: # (technically, "innerHTML" isn't standard but the equivalent
1615: # is really scary, and every useful browser supports it
1616: return (<<DOMBASED);
1617: function change(name, content) {
1618: element = document.getElementById(name);
1619: element.innerHTML = content;
1620: }
1621: DOMBASED
1622: }
1623: }
1624:
1625: =pod
1626:
1627: =item * &changable_area($name,$origContent):
1628:
1629: This provides a "changable area" that can be modified on the fly via
1630: the Javascript code provided in C<change_content_javascript>. $name is
1631: the name you will use to reference the area later; do not repeat the
1632: same name on a given HTML page more then once. $origContent is what
1633: the area will originally contain, which can be left blank.
1634:
1635: =cut
1636:
1637: sub changable_area {
1638: my ($name, $origContent) = @_;
1639:
1640: if ($env{'browser.type'} eq 'netscape' &&
1641: $env{'browser.version'} =~ /^4\./) {
1642: # If this is netscape 4, we need to use the Layer tag
1643: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1644: } else {
1645: return "<span id='$name'>$origContent</span>";
1646: }
1647: }
1648:
1649: =pod
1650:
1651: =item * &viewport_geometry_js
1652:
1653: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1654:
1655: =cut
1656:
1657:
1658: sub viewport_geometry_js {
1659: return <<"GEOMETRY";
1660: var Geometry = {};
1661: function init_geometry() {
1662: if (Geometry.init) { return };
1663: Geometry.init=1;
1664: if (window.innerHeight) {
1665: Geometry.getViewportHeight = function() { return window.innerHeight; };
1666: Geometry.getViewportWidth = function() { return window.innerWidth; };
1667: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1668: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1669: }
1670: else if (document.documentElement && document.documentElement.clientHeight) {
1671: Geometry.getViewportHeight =
1672: function() { return document.documentElement.clientHeight; };
1673: Geometry.getViewportWidth =
1674: function() { return document.documentElement.clientWidth; };
1675:
1676: Geometry.getHorizontalScroll =
1677: function() { return document.documentElement.scrollLeft; };
1678: Geometry.getVerticalScroll =
1679: function() { return document.documentElement.scrollTop; };
1680: }
1681: else if (document.body.clientHeight) {
1682: Geometry.getViewportHeight =
1683: function() { return document.body.clientHeight; };
1684: Geometry.getViewportWidth =
1685: function() { return document.body.clientWidth; };
1686: Geometry.getHorizontalScroll =
1687: function() { return document.body.scrollLeft; };
1688: Geometry.getVerticalScroll =
1689: function() { return document.body.scrollTop; };
1690: }
1691: }
1692:
1693: GEOMETRY
1694: }
1695:
1696: =pod
1697:
1698: =item * &viewport_size_js()
1699:
1700: 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.
1701:
1702: =cut
1703:
1704: sub viewport_size_js {
1705: my $geometry = &viewport_geometry_js();
1706: return <<"DIMS";
1707:
1708: $geometry
1709:
1710: function getViewportDims(width,height) {
1711: init_geometry();
1712: width.value = Geometry.getViewportWidth();
1713: height.value = Geometry.getViewportHeight();
1714: return;
1715: }
1716:
1717: DIMS
1718: }
1719:
1720: =pod
1721:
1722: =item * &resize_textarea_js()
1723:
1724: emits the needed javascript to resize a textarea to be as big as possible
1725:
1726: creates a function resize_textrea that takes two IDs first should be
1727: the id of the element to resize, second should be the id of a div that
1728: surrounds everything that comes after the textarea, this routine needs
1729: to be attached to the <body> for the onload and onresize events.
1730:
1731: =cut
1732:
1733: sub resize_textarea_js {
1734: my $geometry = &viewport_geometry_js();
1735: return <<"RESIZE";
1736: <script type="text/javascript">
1737: // <![CDATA[
1738: $geometry
1739:
1740: function getX(element) {
1741: var x = 0;
1742: while (element) {
1743: x += element.offsetLeft;
1744: element = element.offsetParent;
1745: }
1746: return x;
1747: }
1748: function getY(element) {
1749: var y = 0;
1750: while (element) {
1751: y += element.offsetTop;
1752: element = element.offsetParent;
1753: }
1754: return y;
1755: }
1756:
1757:
1758: function resize_textarea(textarea_id,bottom_id) {
1759: init_geometry();
1760: var textarea = document.getElementById(textarea_id);
1761: //alert(textarea);
1762:
1763: var textarea_top = getY(textarea);
1764: var textarea_height = textarea.offsetHeight;
1765: var bottom = document.getElementById(bottom_id);
1766: var bottom_top = getY(bottom);
1767: var bottom_height = bottom.offsetHeight;
1768: var window_height = Geometry.getViewportHeight();
1769: var fudge = 23;
1770: var new_height = window_height-fudge-textarea_top-bottom_height;
1771: if (new_height < 300) {
1772: new_height = 300;
1773: }
1774: textarea.style.height=new_height+'px';
1775: }
1776: // ]]>
1777: </script>
1778: RESIZE
1779:
1780: }
1781:
1782: sub colorfuleditor_js {
1783: return <<"COLORFULEDIT"
1784: <script type="text/javascript">
1785: // <![CDATA[>
1786: function fold_box(curDepth, lastresource){
1787:
1788: // we need a list because there can be several blocks you need to fold in one tag
1789: var block = document.getElementsByName('foldblock_'+curDepth);
1790: // but there is only one folding button per tag
1791: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1792:
1793: if(block.item(0).style.display == 'none'){
1794:
1795: foldbutton.value = '@{[&mt("Hide")]}';
1796: for (i = 0; i < block.length; i++){
1797: block.item(i).style.display = '';
1798: }
1799: }else{
1800:
1801: foldbutton.value = '@{[&mt("Show")]}';
1802: for (i = 0; i < block.length; i++){
1803: // block.item(i).style.visibility = 'collapse';
1804: block.item(i).style.display = 'none';
1805: }
1806: };
1807: saveState(lastresource);
1808: }
1809:
1810: function saveState (lastresource) {
1811:
1812: var tag_list = getTagList();
1813: if(tag_list != null){
1814: var timestamp = new Date().getTime();
1815: var key = lastresource;
1816:
1817: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1818: // starting with timestamp
1819: var value = timestamp+';';
1820:
1821: // building the list of key-value pairs
1822: for(var i = 0; i < tag_list.length; i++){
1823: value += tag_list[i]+',';
1824: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1825: }
1826:
1827: // only iterate whole storage if nothing to override
1828: if(localStorage.getItem(key) == null){
1829:
1830: // prevent storage from growing large
1831: if(localStorage.length > 50){
1832: var regex_getTimestamp = /^(?:\d)+;/;
1833: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1834: var oldest_key;
1835:
1836: for(var i = 1; i < localStorage.length; i++){
1837: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1838: oldest_key = localStorage.key(i);
1839: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1840: }
1841: }
1842: localStorage.removeItem(oldest_key);
1843: }
1844: }
1845: localStorage.setItem(key,value);
1846: }
1847: }
1848:
1849: // restore folding status of blocks (on page load)
1850: function restoreState (lastresource) {
1851: if(localStorage.getItem(lastresource) != null){
1852: var key = lastresource;
1853: var value = localStorage.getItem(key);
1854: var regex_delTimestamp = /^\d+;/;
1855:
1856: value.replace(regex_delTimestamp, '');
1857:
1858: var valueArr = value.split(';');
1859: var pairs;
1860: var elements;
1861: for (var i = 0; i < valueArr.length; i++){
1862: pairs = valueArr[i].split(',');
1863: elements = document.getElementsByName(pairs[0]);
1864:
1865: for (var j = 0; j < elements.length; j++){
1866: elements[j].style.display = pairs[1];
1867: if (pairs[1] == "none"){
1868: var regex_id = /([_\\d]+)\$/;
1869: regex_id.exec(pairs[0]);
1870: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
1871: }
1872: }
1873: }
1874: }
1875: }
1876:
1877: function getTagList () {
1878:
1879: var stringToSearch = document.lonhomework.innerHTML;
1880:
1881: var ret = new Array();
1882: var regex_findBlock = /(foldblock_.*?)"/g;
1883: var tag_list = stringToSearch.match(regex_findBlock);
1884:
1885: if(tag_list != null){
1886: for(var i = 0; i < tag_list.length; i++){
1887: ret.push(tag_list[i].replace(/"/, ''));
1888: }
1889: }
1890: return ret;
1891: }
1892:
1893: function saveScrollPosition (resource) {
1894: var tag_list = getTagList();
1895:
1896: // we dont always want to jump to the first block
1897: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
1898: if(\$(window).scrollTop() > 170){
1899: if(tag_list != null){
1900: var result;
1901: for(var i = 0; i < tag_list.length; i++){
1902: if(isElementInViewport(tag_list[i])){
1903: result += tag_list[i]+';';
1904: }
1905: }
1906: sessionStorage.setItem('anchor_'+resource, result);
1907: }
1908: } else {
1909: // we dont need to save zero, just delete the item to leave everything tidy
1910: sessionStorage.removeItem('anchor_'+resource);
1911: }
1912: }
1913:
1914: function restoreScrollPosition(resource){
1915:
1916: var elem = sessionStorage.getItem('anchor_'+resource);
1917: if(elem != null){
1918: var tag_list = elem.split(';');
1919: var elem_list;
1920:
1921: for(var i = 0; i < tag_list.length; i++){
1922: elem_list = document.getElementsByName(tag_list[i]);
1923:
1924: if(elem_list.length > 0){
1925: elem = elem_list[0];
1926: break;
1927: }
1928: }
1929: elem.scrollIntoView();
1930: }
1931: }
1932:
1933: function isElementInViewport(el) {
1934:
1935: // change to last element instead of first
1936: var elem = document.getElementsByName(el);
1937: var rect = elem[0].getBoundingClientRect();
1938:
1939: return (
1940: rect.top >= 0 &&
1941: rect.left >= 0 &&
1942: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
1943: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
1944: );
1945: }
1946:
1947: function autosize(depth){
1948: var cmInst = window['cm'+depth];
1949: var fitsizeButton = document.getElementById('fitsize'+depth);
1950:
1951: // is fixed size, switching to dynamic
1952: if (sessionStorage.getItem("autosized_"+depth) == null) {
1953: cmInst.setSize("","auto");
1954: fitsizeButton.value = "@{[&mt('Fixed size')]}";
1955: sessionStorage.setItem("autosized_"+depth, "yes");
1956:
1957: // is dynamic size, switching to fixed
1958: } else {
1959: cmInst.setSize("","300px");
1960: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
1961: sessionStorage.removeItem("autosized_"+depth);
1962: }
1963: }
1964:
1965:
1966:
1967: // ]]>
1968: </script>
1969: COLORFULEDIT
1970: }
1971:
1972: sub xmleditor_js {
1973: return <<XMLEDIT
1974: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
1975: <script type="text/javascript">
1976: // <![CDATA[>
1977:
1978: function saveScrollPosition (resource) {
1979:
1980: var scrollPos = \$(window).scrollTop();
1981: sessionStorage.setItem(resource,scrollPos);
1982: }
1983:
1984: function restoreScrollPosition(resource){
1985:
1986: var scrollPos = sessionStorage.getItem(resource);
1987: \$(window).scrollTop(scrollPos);
1988: }
1989:
1990: // unless internet explorer
1991: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
1992:
1993: \$(document).ready(function() {
1994: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
1995: });
1996: }
1997:
1998: // inserts text at cursor position into codemirror (xml editor only)
1999: function insertText(text){
2000: cm.focus();
2001: var curPos = cm.getCursor();
2002: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2003: }
2004: // ]]>
2005: </script>
2006: XMLEDIT
2007: }
2008:
2009: sub insert_folding_button {
2010: my $curDepth = $Apache::lonxml::curdepth;
2011: my $lastresource = $env{'request.ambiguous'};
2012:
2013: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2014: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2015: }
2016:
2017: =pod
2018:
2019: =item * &iframe_wrapper_headjs()
2020:
2021: emits javascript containing two global vars to facilitate handling of resizing
2022: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
2023: with standard LON-CAPA menus.
2024:
2025: =cut
2026:
2027: #
2028: # Where iframe is in use, if window.onload() executes before the custom resize function
2029: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
2030: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
2031: # do not obscure the Functions menu.
2032: #
2033:
2034: sub iframe_wrapper_headjs {
2035: return <<"ENDJS";
2036: <script type="text/javascript">
2037: // <![CDATA[
2038: var LCnotready = 0;
2039: var LCresizedef = 0;
2040: // ]]>
2041: </script>
2042:
2043: ENDJS
2044:
2045: }
2046:
2047: =pod
2048:
2049: =item * &iframe_wrapper_resizejs()
2050:
2051: emits javascript used to handle resizing for a page containing
2052: an iframe, to ensure that the iframe does not obscure any
2053: standard LON-CAPA menu items.
2054:
2055: =back
2056:
2057: =cut
2058:
2059: #
2060: # jQuery to use when iframe is in use and a page resize occurs.
2061: # This script will ensure that the iframe does not obscure any
2062: # standard LON-CAPA inline menus (primary, secondary, and/or
2063: # breadcrumbs and Functions menus. Expects javascript from
2064: # &iframe_wrapper_headjs() to be in head portion of the web page,
2065: # e.g., by inclusion in second arg passed to &start_page().
2066: #
2067:
2068: sub iframe_wrapper_resizejs {
2069: my $offset = 5;
2070: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
2071: if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
2072: $offset = 0;
2073: }
2074: return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
2075: \$(document).ready( function() {
2076: \$(window).unbind('resize').resize(function(){
2077: var header = null;
2078: var offset = $offset;
2079: var height = 0;
2080: var hdrtop = 0;
2081: if (\$('div.LC_menus_content:first').length) {
2082: if (\$('div.LC_menus_content:first').hasClass ("shown")) {
2083: header = \$('div.LC_menus_content:first');
2084: offset = 12;
2085: }
2086: } else if (\$('div.LC_head_subbox:first').length) {
2087: header = \$('div.LC_head_subbox:first');
2088: offset = 9;
2089: } else {
2090: if (\$('#LC_breadcrumbs').length) {
2091: header = \$('#LC_breadcrumbs');
2092: }
2093: }
2094: if (header != null && header.length) {
2095: height = header.height();
2096: hdrtop = header.position().top;
2097: }
2098: var pos = height + hdrtop + offset;
2099: \$('.LC_iframecontainer').css('top', pos);
2100: });
2101: LCresizedef = 1;
2102: if (LCnotready == 1) {
2103: LCnotready = 0;
2104: \$(window).trigger('resize');
2105: }
2106: });
2107: window.onload = function(){
2108: if (LCresizedef) {
2109: LCnotready = 0;
2110: \$(window).trigger('resize');
2111: } else {
2112: LCnotready = 1;
2113: }
2114: };
2115: SCRIPT
2116:
2117: }
2118:
2119: =pod
2120:
2121: =head1 Excel and CSV file utility routines
2122:
2123: =cut
2124:
2125: ###############################################################
2126: ###############################################################
2127:
2128: =pod
2129:
2130: =over 4
2131:
2132: =item * &csv_translate($text)
2133:
2134: Translate $text to allow it to be output as a 'comma separated values'
2135: format.
2136:
2137: =cut
2138:
2139: ###############################################################
2140: ###############################################################
2141: sub csv_translate {
2142: my $text = shift;
2143: $text =~ s/\"/\"\"/g;
2144: $text =~ s/\n/ /g;
2145: return $text;
2146: }
2147:
2148: ###############################################################
2149: ###############################################################
2150:
2151: =pod
2152:
2153: =item * &define_excel_formats()
2154:
2155: Define some commonly used Excel cell formats.
2156:
2157: Currently supported formats:
2158:
2159: =over 4
2160:
2161: =item header
2162:
2163: =item bold
2164:
2165: =item h1
2166:
2167: =item h2
2168:
2169: =item h3
2170:
2171: =item h4
2172:
2173: =item i
2174:
2175: =item date
2176:
2177: =back
2178:
2179: Inputs: $workbook
2180:
2181: Returns: $format, a hash reference.
2182:
2183:
2184: =cut
2185:
2186: ###############################################################
2187: ###############################################################
2188: sub define_excel_formats {
2189: my ($workbook) = @_;
2190: my $format;
2191: $format->{'header'} = $workbook->add_format(bold => 1,
2192: bottom => 1,
2193: align => 'center');
2194: $format->{'bold'} = $workbook->add_format(bold=>1);
2195: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2196: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2197: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2198: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2199: $format->{'i'} = $workbook->add_format(italic=>1);
2200: $format->{'date'} = $workbook->add_format(num_format=>
2201: 'mm/dd/yyyy hh:mm:ss');
2202: return $format;
2203: }
2204:
2205: ###############################################################
2206: ###############################################################
2207:
2208: =pod
2209:
2210: =item * &create_workbook()
2211:
2212: Create an Excel worksheet. If it fails, output message on the
2213: request object and return undefs.
2214:
2215: Inputs: Apache request object
2216:
2217: Returns (undef) on failure,
2218: Excel worksheet object, scalar with filename, and formats
2219: from &Apache::loncommon::define_excel_formats on success
2220:
2221: =cut
2222:
2223: ###############################################################
2224: ###############################################################
2225: sub create_workbook {
2226: my ($r) = @_;
2227: #
2228: # Create the excel spreadsheet
2229: my $filename = '/prtspool/'.
2230: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2231: time.'_'.rand(1000000000).'.xls';
2232: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2233: if (! defined($workbook)) {
2234: $r->log_error("Error creating excel spreadsheet $filename: $!");
2235: $r->print(
2236: '<p class="LC_error">'
2237: .&mt('Problems occurred in creating the new Excel file.')
2238: .' '.&mt('This error has been logged.')
2239: .' '.&mt('Please alert your LON-CAPA administrator.')
2240: .'</p>'
2241: );
2242: return (undef);
2243: }
2244: #
2245: $workbook->set_tempdir(LONCAPA::tempdir());
2246: #
2247: my $format = &Apache::loncommon::define_excel_formats($workbook);
2248: return ($workbook,$filename,$format);
2249: }
2250:
2251: ###############################################################
2252: ###############################################################
2253:
2254: =pod
2255:
2256: =item * &create_text_file()
2257:
2258: Create a file to write to and eventually make available to the user.
2259: If file creation fails, outputs an error message on the request object and
2260: return undefs.
2261:
2262: Inputs: Apache request object, and file suffix
2263:
2264: Returns (undef) on failure,
2265: Filehandle and filename on success.
2266:
2267: =cut
2268:
2269: ###############################################################
2270: ###############################################################
2271: sub create_text_file {
2272: my ($r,$suffix) = @_;
2273: if (! defined($suffix)) { $suffix = 'txt'; };
2274: my $fh;
2275: my $filename = '/prtspool/'.
2276: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2277: time.'_'.rand(1000000000).'.'.$suffix;
2278: $fh = Apache::File->new('>/home/httpd'.$filename);
2279: if (! defined($fh)) {
2280: $r->log_error("Couldn't open $filename for output $!");
2281: $r->print(
2282: '<p class="LC_error">'
2283: .&mt('Problems occurred in creating the output file.')
2284: .' '.&mt('This error has been logged.')
2285: .' '.&mt('Please alert your LON-CAPA administrator.')
2286: .'</p>'
2287: );
2288: }
2289: return ($fh,$filename)
2290: }
2291:
2292:
2293: =pod
2294:
2295: =back
2296:
2297: =cut
2298:
2299: ###############################################################
2300: ## Home server <option> list generating code ##
2301: ###############################################################
2302:
2303: # ------------------------------------------
2304:
2305: sub domain_select {
2306: my ($name,$value,$multiple)=@_;
2307: my %domains=map {
2308: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2309: } &Apache::lonnet::all_domains();
2310: if ($multiple) {
2311: $domains{''}=&mt('Any domain');
2312: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2313: return &multiple_select_form($name,$value,4,\%domains);
2314: } else {
2315: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2316: return &select_form($name,$value,\%domains);
2317: }
2318: }
2319:
2320: #-------------------------------------------
2321:
2322: =pod
2323:
2324: =head1 Routines for form select boxes
2325:
2326: =over 4
2327:
2328: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2329:
2330: Returns a string containing a <select> element int multiple mode
2331:
2332:
2333: Args:
2334: $name - name of the <select> element
2335: $value - scalar or array ref of values that should already be selected
2336: $size - number of rows long the select element is
2337: $hash - the elements should be 'option' => 'shown text'
2338: (shown text should already have been &mt())
2339: $order - (optional) array ref of the order to show the elements in
2340:
2341: =cut
2342:
2343: #-------------------------------------------
2344: sub multiple_select_form {
2345: my ($name,$value,$size,$hash,$order)=@_;
2346: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2347: my $output='';
2348: if (! defined($size)) {
2349: $size = 4;
2350: if (scalar(keys(%$hash))<4) {
2351: $size = scalar(keys(%$hash));
2352: }
2353: }
2354: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2355: my @order;
2356: if (ref($order) eq 'ARRAY') {
2357: @order = @{$order};
2358: } else {
2359: @order = sort(keys(%$hash));
2360: }
2361: if (exists($$hash{'select_form_order'})) {
2362: @order = @{$$hash{'select_form_order'}};
2363: }
2364:
2365: foreach my $key (@order) {
2366: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2367: $output.='selected="selected" ' if ($selected{$key});
2368: $output.='>'.$hash->{$key}."</option>\n";
2369: }
2370: $output.="</select>\n";
2371: return $output;
2372: }
2373:
2374: #-------------------------------------------
2375:
2376: =pod
2377:
2378: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2379:
2380: Returns a string containing a <select name='$name' size='1'> form to
2381: allow a user to select options from a ref to a hash containing:
2382: option_name => displayed text. An optional $onchange can include
2383: a javascript onchange item, e.g., onchange="this.form.submit();".
2384: An optional arg -- $readonly -- if true will cause the select form
2385: to be disabled, e.g., for the case where an instructor has a section-
2386: specific role, and is viewing/modifying parameters.
2387:
2388: See lonrights.pm for an example invocation and use.
2389:
2390: =cut
2391:
2392: #-------------------------------------------
2393: sub select_form {
2394: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2395: return unless (ref($hashref) eq 'HASH');
2396: if ($onchange) {
2397: $onchange = ' onchange="'.$onchange.'"';
2398: }
2399: my $disabled;
2400: if ($readonly) {
2401: $disabled = ' disabled="disabled"';
2402: }
2403: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2404: my @keys;
2405: if (exists($hashref->{'select_form_order'})) {
2406: @keys=@{$hashref->{'select_form_order'}};
2407: } else {
2408: @keys=sort(keys(%{$hashref}));
2409: }
2410: foreach my $key (@keys) {
2411: $selectform.=
2412: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2413: ($key eq $def ? 'selected="selected" ' : '').
2414: ">".$hashref->{$key}."</option>\n";
2415: }
2416: $selectform.="</select>";
2417: return $selectform;
2418: }
2419:
2420: # For display filters
2421:
2422: sub display_filter {
2423: my ($context) = @_;
2424: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2425: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2426: my $phraseinput = 'hidden';
2427: my $includeinput = 'hidden';
2428: my ($checked,$includetypestext);
2429: if ($env{'form.displayfilter'} eq 'containing') {
2430: $phraseinput = 'text';
2431: if ($context eq 'parmslog') {
2432: $includeinput = 'checkbox';
2433: if ($env{'form.includetypes'}) {
2434: $checked = ' checked="checked"';
2435: }
2436: $includetypestext = &mt('Include parameter types');
2437: }
2438: } else {
2439: $includetypestext = ' ';
2440: }
2441: my ($additional,$secondid,$thirdid);
2442: if ($context eq 'parmslog') {
2443: $additional =
2444: '<label><input type="'.$includeinput.'" name="includetypes"'.
2445: $checked.' name="includetypes" value="1" id="includetypes" />'.
2446: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2447: '</label>';
2448: $secondid = 'includetypes';
2449: $thirdid = 'includetypestext';
2450: }
2451: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2452: '$secondid','$thirdid')";
2453: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2454: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2455: (&mt('all'),10,20,50,100,1000,10000))).
2456: '</label></span> <span class="LC_nobreak">'.
2457: &mt('Filter: [_1]',
2458: &select_form($env{'form.displayfilter'},
2459: 'displayfilter',
2460: {'currentfolder' => 'Current folder/page',
2461: 'containing' => 'Containing phrase',
2462: 'none' => 'None'},$onchange)).' '.
2463: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2464: &HTML::Entities::encode($env{'form.containingphrase'}).
2465: '" />'.$additional;
2466: }
2467:
2468: sub display_filter_js {
2469: my $includetext = &mt('Include parameter types');
2470: return <<"ENDJS";
2471:
2472: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2473: var firstType = 'hidden';
2474: if (setter.options[setter.selectedIndex].value == 'containing') {
2475: firstType = 'text';
2476: }
2477: firstObject = document.getElementById(firstid);
2478: if (typeof(firstObject) == 'object') {
2479: if (firstObject.type != firstType) {
2480: changeInputType(firstObject,firstType);
2481: }
2482: }
2483: if (context == 'parmslog') {
2484: var secondType = 'hidden';
2485: if (firstType == 'text') {
2486: secondType = 'checkbox';
2487: }
2488: secondObject = document.getElementById(secondid);
2489: if (typeof(secondObject) == 'object') {
2490: if (secondObject.type != secondType) {
2491: changeInputType(secondObject,secondType);
2492: }
2493: }
2494: var textItem = document.getElementById(thirdid);
2495: var currtext = textItem.innerHTML;
2496: var newtext;
2497: if (firstType == 'text') {
2498: newtext = '$includetext';
2499: } else {
2500: newtext = ' ';
2501: }
2502: if (currtext != newtext) {
2503: textItem.innerHTML = newtext;
2504: }
2505: }
2506: return;
2507: }
2508:
2509: function changeInputType(oldObject,newType) {
2510: var newObject = document.createElement('input');
2511: newObject.type = newType;
2512: if (oldObject.size) {
2513: newObject.size = oldObject.size;
2514: }
2515: if (oldObject.value) {
2516: newObject.value = oldObject.value;
2517: }
2518: if (oldObject.name) {
2519: newObject.name = oldObject.name;
2520: }
2521: if (oldObject.id) {
2522: newObject.id = oldObject.id;
2523: }
2524: oldObject.parentNode.replaceChild(newObject,oldObject);
2525: return;
2526: }
2527:
2528: ENDJS
2529: }
2530:
2531: sub gradeleveldescription {
2532: my $gradelevel=shift;
2533: my %gradelevels=(0 => 'Not specified',
2534: 1 => 'Grade 1',
2535: 2 => 'Grade 2',
2536: 3 => 'Grade 3',
2537: 4 => 'Grade 4',
2538: 5 => 'Grade 5',
2539: 6 => 'Grade 6',
2540: 7 => 'Grade 7',
2541: 8 => 'Grade 8',
2542: 9 => 'Grade 9',
2543: 10 => 'Grade 10',
2544: 11 => 'Grade 11',
2545: 12 => 'Grade 12',
2546: 13 => 'Grade 13',
2547: 14 => '100 Level',
2548: 15 => '200 Level',
2549: 16 => '300 Level',
2550: 17 => '400 Level',
2551: 18 => 'Graduate Level');
2552: return &mt($gradelevels{$gradelevel});
2553: }
2554:
2555: sub select_level_form {
2556: my ($deflevel,$name)=@_;
2557: unless ($deflevel) { $deflevel=0; }
2558: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2559: for (my $i=0; $i<=18; $i++) {
2560: $selectform.="<option value=\"$i\" ".
2561: ($i==$deflevel ? 'selected="selected" ' : '').
2562: ">".&gradeleveldescription($i)."</option>\n";
2563: }
2564: $selectform.="</select>";
2565: return $selectform;
2566: }
2567:
2568: #-------------------------------------------
2569:
2570: =pod
2571:
2572: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2573:
2574: Returns a string containing a <select name='$name' size='1'> form to
2575: allow a user to select the domain to preform an operation in.
2576: See loncreateuser.pm for an example invocation and use.
2577:
2578: If the $includeempty flag is set, it also includes an empty choice ("no domain
2579: selected");
2580:
2581: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2582:
2583: 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.
2584:
2585: The optional $incdoms is a reference to an array of domains which will be the only available options.
2586:
2587: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2588:
2589: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2590:
2591: =cut
2592:
2593: #-------------------------------------------
2594: sub select_dom_form {
2595: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2596: if ($onchange) {
2597: $onchange = ' onchange="'.$onchange.'"';
2598: }
2599: if ($disabled) {
2600: $disabled = ' disabled="disabled"';
2601: }
2602: my (@domains,%exclude);
2603: if (ref($incdoms) eq 'ARRAY') {
2604: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2605: } else {
2606: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2607: }
2608: if ($includeempty) { @domains=('',@domains); }
2609: if (ref($excdoms) eq 'ARRAY') {
2610: map { $exclude{$_} = 1; } @{$excdoms};
2611: }
2612: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2613: foreach my $dom (@domains) {
2614: next if ($exclude{$dom});
2615: $selectdomain.="<option value=\"$dom\" ".
2616: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2617: if ($showdomdesc) {
2618: if ($dom ne '') {
2619: my $domdesc = &Apache::lonnet::domain($dom,'description');
2620: if ($domdesc ne '') {
2621: $selectdomain .= ' ('.$domdesc.')';
2622: }
2623: }
2624: }
2625: $selectdomain .= "</option>\n";
2626: }
2627: $selectdomain.="</select>";
2628: return $selectdomain;
2629: }
2630:
2631: #-------------------------------------------
2632:
2633: =pod
2634:
2635: =item * &home_server_form_item($domain,$name,$defaultflag)
2636:
2637: input: 4 arguments (two required, two optional) -
2638: $domain - domain of new user
2639: $name - name of form element
2640: $default - Value of 'default' causes a default item to be first
2641: option, and selected by default.
2642: $hide - Value of 'hide' causes hiding of the name of the server,
2643: if 1 server found, or default, if 0 found.
2644: output: returns 2 items:
2645: (a) form element which contains either:
2646: (i) <select name="$name">
2647: <option value="$hostid1">$hostid $servers{$hostid}</option>
2648: <option value="$hostid2">$hostid $servers{$hostid}</option>
2649: </select>
2650: form item if there are multiple library servers in $domain, or
2651: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2652: if there is only one library server in $domain.
2653:
2654: (b) number of library servers found.
2655:
2656: See loncreateuser.pm for example of use.
2657:
2658: =cut
2659:
2660: #-------------------------------------------
2661: sub home_server_form_item {
2662: my ($domain,$name,$default,$hide) = @_;
2663: my %servers = &Apache::lonnet::get_servers($domain,'library');
2664: my $result;
2665: my $numlib = keys(%servers);
2666: if ($numlib > 1) {
2667: $result .= '<select name="'.$name.'" />'."\n";
2668: if ($default) {
2669: $result .= '<option value="default" selected="selected">'.&mt('default').
2670: '</option>'."\n";
2671: }
2672: foreach my $hostid (sort(keys(%servers))) {
2673: $result.= '<option value="'.$hostid.'">'.
2674: $hostid.' '.$servers{$hostid}."</option>\n";
2675: }
2676: $result .= '</select>'."\n";
2677: } elsif ($numlib == 1) {
2678: my $hostid;
2679: foreach my $item (keys(%servers)) {
2680: $hostid = $item;
2681: }
2682: $result .= '<input type="hidden" name="'.$name.'" value="'.
2683: $hostid.'" />';
2684: if (!$hide) {
2685: $result .= $hostid.' '.$servers{$hostid};
2686: }
2687: $result .= "\n";
2688: } elsif ($default) {
2689: $result .= '<input type="hidden" name="'.$name.
2690: '" value="default" />';
2691: if (!$hide) {
2692: $result .= &mt('default');
2693: }
2694: $result .= "\n";
2695: }
2696: return ($result,$numlib);
2697: }
2698:
2699: =pod
2700:
2701: =back
2702:
2703: =cut
2704:
2705: ###############################################################
2706: ## Decoding User Agent ##
2707: ###############################################################
2708:
2709: =pod
2710:
2711: =head1 Decoding the User Agent
2712:
2713: =over 4
2714:
2715: =item * &decode_user_agent()
2716:
2717: Inputs: $r
2718:
2719: Outputs:
2720:
2721: =over 4
2722:
2723: =item * $httpbrowser
2724:
2725: =item * $clientbrowser
2726:
2727: =item * $clientversion
2728:
2729: =item * $clientmathml
2730:
2731: =item * $clientunicode
2732:
2733: =item * $clientos
2734:
2735: =item * $clientmobile
2736:
2737: =item * $clientinfo
2738:
2739: =item * $clientosversion
2740:
2741: =back
2742:
2743: =back
2744:
2745: =cut
2746:
2747: ###############################################################
2748: ###############################################################
2749: sub decode_user_agent {
2750: my ($r)=@_;
2751: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2752: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2753: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2754: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2755: my $clientbrowser='unknown';
2756: my $clientversion='0';
2757: my $clientmathml='';
2758: my $clientunicode='0';
2759: my $clientmobile=0;
2760: my $clientosversion='';
2761: for (my $i=0;$i<=$#browsertype;$i++) {
2762: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2763: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2764: $clientbrowser=$bname;
2765: $httpbrowser=~/$vreg/i;
2766: $clientversion=$1;
2767: $clientmathml=($clientversion>=$minv);
2768: $clientunicode=($clientversion>=$univ);
2769: }
2770: }
2771: my $clientos='unknown';
2772: my $clientinfo;
2773: if (($httpbrowser=~/linux/i) ||
2774: ($httpbrowser=~/unix/i) ||
2775: ($httpbrowser=~/ux/i) ||
2776: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2777: if (($httpbrowser=~/vax/i) ||
2778: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2779: if ($httpbrowser=~/next/i) { $clientos='next'; }
2780: if (($httpbrowser=~/mac/i) ||
2781: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2782: if ($httpbrowser=~/win/i) {
2783: $clientos='win';
2784: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2785: $clientosversion = $1;
2786: }
2787: }
2788: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2789: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2790: $clientmobile=lc($1);
2791: }
2792: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2793: $clientinfo = 'firefox-'.$1;
2794: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2795: $clientinfo = 'chromeframe-'.$1;
2796: }
2797: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2798: $clientunicode,$clientos,$clientmobile,$clientinfo,
2799: $clientosversion);
2800: }
2801:
2802: ###############################################################
2803: ## Authentication changing form generation subroutines ##
2804: ###############################################################
2805: ##
2806: ## All of the authform_xxxxxxx subroutines take their inputs in a
2807: ## hash, and have reasonable default values.
2808: ##
2809: ## formname = the name given in the <form> tag.
2810: #-------------------------------------------
2811:
2812: =pod
2813:
2814: =head1 Authentication Routines
2815:
2816: =over 4
2817:
2818: =item * &authform_xxxxxx()
2819:
2820: The authform_xxxxxx subroutines provide javascript and html forms which
2821: handle some of the conveniences required for authentication forms.
2822: This is not an optimal method, but it works.
2823:
2824: =over 4
2825:
2826: =item * authform_header
2827:
2828: =item * authform_authorwarning
2829:
2830: =item * authform_nochange
2831:
2832: =item * authform_kerberos
2833:
2834: =item * authform_internal
2835:
2836: =item * authform_filesystem
2837:
2838: =item * authform_lti
2839:
2840: =back
2841:
2842: See loncreateuser.pm for invocation and use examples.
2843:
2844: =cut
2845:
2846: #-------------------------------------------
2847: sub authform_header{
2848: my %in = (
2849: formname => 'cu',
2850: kerb_def_dom => '',
2851: @_,
2852: );
2853: $in{'formname'} = 'document.' . $in{'formname'};
2854: my $result='';
2855:
2856: #---------------------------------------------- Code for upper case translation
2857: my $Javascript_toUpperCase;
2858: unless ($in{kerb_def_dom}) {
2859: $Javascript_toUpperCase =<<"END";
2860: switch (choice) {
2861: case 'krb': currentform.elements[choicearg].value =
2862: currentform.elements[choicearg].value.toUpperCase();
2863: break;
2864: default:
2865: }
2866: END
2867: } else {
2868: $Javascript_toUpperCase = "";
2869: }
2870:
2871: my $radioval = "'nochange'";
2872: if (defined($in{'curr_authtype'})) {
2873: if ($in{'curr_authtype'} ne '') {
2874: $radioval = "'".$in{'curr_authtype'}."arg'";
2875: }
2876: }
2877: my $argfield = 'null';
2878: if (defined($in{'mode'})) {
2879: if ($in{'mode'} eq 'modifycourse') {
2880: if (defined($in{'curr_autharg'})) {
2881: if ($in{'curr_autharg'} ne '') {
2882: $argfield = "'$in{'curr_autharg'}'";
2883: }
2884: }
2885: }
2886: }
2887:
2888: $result.=<<"END";
2889: var current = new Object();
2890: current.radiovalue = $radioval;
2891: current.argfield = $argfield;
2892:
2893: function changed_radio(choice,currentform) {
2894: var choicearg = choice + 'arg';
2895: // If a radio button in changed, we need to change the argfield
2896: if (current.radiovalue != choice) {
2897: current.radiovalue = choice;
2898: if (current.argfield != null) {
2899: currentform.elements[current.argfield].value = '';
2900: }
2901: if (choice == 'nochange') {
2902: current.argfield = null;
2903: } else {
2904: current.argfield = choicearg;
2905: switch(choice) {
2906: case 'krb':
2907: currentform.elements[current.argfield].value =
2908: "$in{'kerb_def_dom'}";
2909: break;
2910: default:
2911: break;
2912: }
2913: }
2914: }
2915: return;
2916: }
2917:
2918: function changed_text(choice,currentform) {
2919: var choicearg = choice + 'arg';
2920: if (currentform.elements[choicearg].value !='') {
2921: $Javascript_toUpperCase
2922: // clear old field
2923: if ((current.argfield != choicearg) && (current.argfield != null)) {
2924: currentform.elements[current.argfield].value = '';
2925: }
2926: current.argfield = choicearg;
2927: }
2928: set_auth_radio_buttons(choice,currentform);
2929: return;
2930: }
2931:
2932: function set_auth_radio_buttons(newvalue,currentform) {
2933: var numauthchoices = currentform.login.length;
2934: if (typeof numauthchoices == "undefined") {
2935: return;
2936: }
2937: var i=0;
2938: while (i < numauthchoices) {
2939: if (currentform.login[i].value == newvalue) { break; }
2940: i++;
2941: }
2942: if (i == numauthchoices) {
2943: return;
2944: }
2945: current.radiovalue = newvalue;
2946: currentform.login[i].checked = true;
2947: return;
2948: }
2949: END
2950: return $result;
2951: }
2952:
2953: sub authform_authorwarning {
2954: my $result='';
2955: $result='<i>'.
2956: &mt('As a general rule, only authors or co-authors should be '.
2957: 'filesystem authenticated '.
2958: '(which allows access to the server filesystem).')."</i>\n";
2959: return $result;
2960: }
2961:
2962: sub authform_nochange {
2963: my %in = (
2964: formname => 'document.cu',
2965: kerb_def_dom => 'MSU.EDU',
2966: @_,
2967: );
2968: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2969: my $result;
2970: if (!$authnum) {
2971: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2972: } else {
2973: $result = '<label>'.&mt('[_1] Do not change login data',
2974: '<input type="radio" name="login" value="nochange" '.
2975: 'checked="checked" onclick="'.
2976: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2977: '</label>';
2978: }
2979: return $result;
2980: }
2981:
2982: sub authform_kerberos {
2983: my %in = (
2984: formname => 'document.cu',
2985: kerb_def_dom => 'MSU.EDU',
2986: kerb_def_auth => 'krb4',
2987: @_,
2988: );
2989: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2990: $autharg,$jscall,$disabled);
2991: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2992: if ($in{'kerb_def_auth'} eq 'krb5') {
2993: $check5 = ' checked="checked"';
2994: } else {
2995: $check4 = ' checked="checked"';
2996: }
2997: if ($in{'readonly'}) {
2998: $disabled = ' disabled="disabled"';
2999: }
3000: $krbarg = $in{'kerb_def_dom'};
3001: if (defined($in{'curr_authtype'})) {
3002: if ($in{'curr_authtype'} eq 'krb') {
3003: $krbcheck = ' checked="checked"';
3004: if (defined($in{'mode'})) {
3005: if ($in{'mode'} eq 'modifyuser') {
3006: $krbcheck = '';
3007: }
3008: }
3009: if (defined($in{'curr_kerb_ver'})) {
3010: if ($in{'curr_krb_ver'} eq '5') {
3011: $check5 = ' checked="checked"';
3012: $check4 = '';
3013: } else {
3014: $check4 = ' checked="checked"';
3015: $check5 = '';
3016: }
3017: }
3018: if (defined($in{'curr_autharg'})) {
3019: $krbarg = $in{'curr_autharg'};
3020: }
3021: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3022: if (defined($in{'curr_autharg'})) {
3023: $result =
3024: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3025: $in{'curr_autharg'},$krbver);
3026: } else {
3027: $result =
3028: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3029: }
3030: return $result;
3031: }
3032: }
3033: } else {
3034: if ($authnum == 1) {
3035: $authtype = '<input type="hidden" name="login" value="krb" />';
3036: }
3037: }
3038: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3039: return;
3040: } elsif ($authtype eq '') {
3041: if (defined($in{'mode'})) {
3042: if ($in{'mode'} eq 'modifycourse') {
3043: if ($authnum == 1) {
3044: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
3045: }
3046: }
3047: }
3048: }
3049: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3050: if ($authtype eq '') {
3051: $authtype = '<input type="radio" name="login" value="krb" '.
3052: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3053: $krbcheck.$disabled.' />';
3054: }
3055: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3056: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3057: $in{'curr_authtype'} eq 'krb5') ||
3058: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3059: $in{'curr_authtype'} eq 'krb4')) {
3060: $result .= &mt
3061: ('[_1] Kerberos authenticated with domain [_2] '.
3062: '[_3] Version 4 [_4] Version 5 [_5]',
3063: '<label>'.$authtype,
3064: '</label><input type="text" size="10" name="krbarg" '.
3065: 'value="'.$krbarg.'" '.
3066: 'onchange="'.$jscall.'"'.$disabled.' />',
3067: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
3068: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
3069: '</label>');
3070: } elsif ($can_assign{'krb4'}) {
3071: $result .= &mt
3072: ('[_1] Kerberos authenticated with domain [_2] '.
3073: '[_3] Version 4 [_4]',
3074: '<label>'.$authtype,
3075: '</label><input type="text" size="10" name="krbarg" '.
3076: 'value="'.$krbarg.'" '.
3077: 'onchange="'.$jscall.'"'.$disabled.' />',
3078: '<label><input type="hidden" name="krbver" value="4" />',
3079: '</label>');
3080: } elsif ($can_assign{'krb5'}) {
3081: $result .= &mt
3082: ('[_1] Kerberos authenticated with domain [_2] '.
3083: '[_3] Version 5 [_4]',
3084: '<label>'.$authtype,
3085: '</label><input type="text" size="10" name="krbarg" '.
3086: 'value="'.$krbarg.'" '.
3087: 'onchange="'.$jscall.'"'.$disabled.' />',
3088: '<label><input type="hidden" name="krbver" value="5" />',
3089: '</label>');
3090: }
3091: return $result;
3092: }
3093:
3094: sub authform_internal {
3095: my %in = (
3096: formname => 'document.cu',
3097: kerb_def_dom => 'MSU.EDU',
3098: @_,
3099: );
3100: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
3101: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3102: if ($in{'readonly'}) {
3103: $disabled = ' disabled="disabled"';
3104: }
3105: if (defined($in{'curr_authtype'})) {
3106: if ($in{'curr_authtype'} eq 'int') {
3107: if ($can_assign{'int'}) {
3108: $intcheck = 'checked="checked" ';
3109: if (defined($in{'mode'})) {
3110: if ($in{'mode'} eq 'modifyuser') {
3111: $intcheck = '';
3112: }
3113: }
3114: if (defined($in{'curr_autharg'})) {
3115: $intarg = $in{'curr_autharg'};
3116: }
3117: } else {
3118: $result = &mt('Currently internally authenticated.');
3119: return $result;
3120: }
3121: }
3122: } else {
3123: if ($authnum == 1) {
3124: $authtype = '<input type="hidden" name="login" value="int" />';
3125: }
3126: }
3127: if (!$can_assign{'int'}) {
3128: return;
3129: } elsif ($authtype eq '') {
3130: if (defined($in{'mode'})) {
3131: if ($in{'mode'} eq 'modifycourse') {
3132: if ($authnum == 1) {
3133: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3134: }
3135: }
3136: }
3137: }
3138: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3139: if ($authtype eq '') {
3140: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3141: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3142: }
3143: $autharg = '<input type="password" size="10" name="intarg" value="'.
3144: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3145: $result = &mt
3146: ('[_1] Internally authenticated (with initial password [_2])',
3147: '<label>'.$authtype,'</label>'.$autharg);
3148: $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>';
3149: return $result;
3150: }
3151:
3152: sub authform_local {
3153: my %in = (
3154: formname => 'document.cu',
3155: kerb_def_dom => 'MSU.EDU',
3156: @_,
3157: );
3158: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3159: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3160: if ($in{'readonly'}) {
3161: $disabled = ' disabled="disabled"';
3162: }
3163: if (defined($in{'curr_authtype'})) {
3164: if ($in{'curr_authtype'} eq 'loc') {
3165: if ($can_assign{'loc'}) {
3166: $loccheck = 'checked="checked" ';
3167: if (defined($in{'mode'})) {
3168: if ($in{'mode'} eq 'modifyuser') {
3169: $loccheck = '';
3170: }
3171: }
3172: if (defined($in{'curr_autharg'})) {
3173: $locarg = $in{'curr_autharg'};
3174: }
3175: } else {
3176: $result = &mt('Currently using local (institutional) authentication.');
3177: return $result;
3178: }
3179: }
3180: } else {
3181: if ($authnum == 1) {
3182: $authtype = '<input type="hidden" name="login" value="loc" />';
3183: }
3184: }
3185: if (!$can_assign{'loc'}) {
3186: return;
3187: } elsif ($authtype eq '') {
3188: if (defined($in{'mode'})) {
3189: if ($in{'mode'} eq 'modifycourse') {
3190: if ($authnum == 1) {
3191: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3192: }
3193: }
3194: }
3195: }
3196: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3197: if ($authtype eq '') {
3198: $authtype = '<input type="radio" name="login" value="loc" '.
3199: $loccheck.' onchange="'.$jscall.'" onclick="'.
3200: $jscall.'"'.$disabled.' />';
3201: }
3202: $autharg = '<input type="text" size="10" name="locarg" value="'.
3203: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3204: $result = &mt('[_1] Local Authentication with argument [_2]',
3205: '<label>'.$authtype,'</label>'.$autharg);
3206: return $result;
3207: }
3208:
3209: sub authform_filesystem {
3210: my %in = (
3211: formname => 'document.cu',
3212: kerb_def_dom => 'MSU.EDU',
3213: @_,
3214: );
3215: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3216: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3217: if ($in{'readonly'}) {
3218: $disabled = ' disabled="disabled"';
3219: }
3220: if (defined($in{'curr_authtype'})) {
3221: if ($in{'curr_authtype'} eq 'fsys') {
3222: if ($can_assign{'fsys'}) {
3223: $fsyscheck = 'checked="checked" ';
3224: if (defined($in{'mode'})) {
3225: if ($in{'mode'} eq 'modifyuser') {
3226: $fsyscheck = '';
3227: }
3228: }
3229: } else {
3230: $result = &mt('Currently Filesystem Authenticated.');
3231: return $result;
3232: }
3233: }
3234: } else {
3235: if ($authnum == 1) {
3236: $authtype = '<input type="hidden" name="login" value="fsys" />';
3237: }
3238: }
3239: if (!$can_assign{'fsys'}) {
3240: return;
3241: } elsif ($authtype eq '') {
3242: if (defined($in{'mode'})) {
3243: if ($in{'mode'} eq 'modifycourse') {
3244: if ($authnum == 1) {
3245: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3246: }
3247: }
3248: }
3249: }
3250: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3251: if ($authtype eq '') {
3252: $authtype = '<input type="radio" name="login" value="fsys" '.
3253: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3254: $jscall.'"'.$disabled.' />';
3255: }
3256: $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
3257: ' onchange="'.$jscall.'"'.$disabled.' />';
3258: $result = &mt
3259: ('[_1] Filesystem Authenticated (with initial password [_2])',
3260: '<label>'.$authtype,'</label>'.$autharg);
3261: return $result;
3262: }
3263:
3264: sub authform_lti {
3265: my %in = (
3266: formname => 'document.cu',
3267: kerb_def_dom => 'MSU.EDU',
3268: @_,
3269: );
3270: my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
3271: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3272: if ($in{'readonly'}) {
3273: $disabled = ' disabled="disabled"';
3274: }
3275: if (defined($in{'curr_authtype'})) {
3276: if ($in{'curr_authtype'} eq 'lti') {
3277: if ($can_assign{'lti'}) {
3278: $lticheck = 'checked="checked" ';
3279: if (defined($in{'mode'})) {
3280: if ($in{'mode'} eq 'modifyuser') {
3281: $lticheck = '';
3282: }
3283: }
3284: } else {
3285: $result = &mt('Currently LTI Authenticated.');
3286: return $result;
3287: }
3288: }
3289: } else {
3290: if ($authnum == 1) {
3291: $authtype = '<input type="hidden" name="login" value="lti" />';
3292: }
3293: }
3294: if (!$can_assign{'lti'}) {
3295: return;
3296: } elsif ($authtype eq '') {
3297: if (defined($in{'mode'})) {
3298: if ($in{'mode'} eq 'modifycourse') {
3299: if ($authnum == 1) {
3300: $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
3301: }
3302: }
3303: }
3304: }
3305: $jscall = "javascript:changed_radio('lti',$in{'formname'});";
3306: if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
3307: $authtype = '<input type="radio" name="login" value="lti" '.
3308: $lticheck.' onchange="'.$jscall.'" onclick="'.
3309: $jscall.'"'.$disabled.' />';
3310: }
3311: $autharg = '<input type="hidden" name="ltiarg" value="" />';
3312: if ($authtype) {
3313: $result = &mt('[_1] LTI Authenticated',
3314: '<label>'.$authtype.'</label>'.$autharg);
3315: } else {
3316: $result = '<b>'.&mt('LTI Authenticated').'</b>'.
3317: $autharg;
3318: }
3319: return $result;
3320: }
3321:
3322: sub get_assignable_auth {
3323: my ($dom) = @_;
3324: if ($dom eq '') {
3325: $dom = $env{'request.role.domain'};
3326: }
3327: my %can_assign = (
3328: krb4 => 1,
3329: krb5 => 1,
3330: int => 1,
3331: loc => 1,
3332: );
3333: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3334: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3335: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3336: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3337: my $context;
3338: if ($env{'request.role'} =~ /^au/) {
3339: $context = 'author';
3340: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3341: $context = 'domain';
3342: } elsif ($env{'request.course.id'}) {
3343: $context = 'course';
3344: }
3345: if ($context) {
3346: if (ref($authhash->{$context}) eq 'HASH') {
3347: %can_assign = %{$authhash->{$context}};
3348: }
3349: }
3350: }
3351: }
3352: my $authnum = 0;
3353: foreach my $key (keys(%can_assign)) {
3354: if ($can_assign{$key}) {
3355: $authnum ++;
3356: }
3357: }
3358: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3359: $authnum --;
3360: }
3361: return ($authnum,%can_assign);
3362: }
3363:
3364: sub check_passwd_rules {
3365: my ($domain,$plainpass) = @_;
3366: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3367: my ($min,$max,@chars,@brokerule,$warning);
3368: $min = $Apache::lonnet::passwdmin;
3369: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3370: if ($passwdconf{'min'} =~ /^\d+$/) {
3371: if ($passwdconf{'min'} > $min) {
3372: $min = $passwdconf{'min'};
3373: }
3374: }
3375: if ($passwdconf{'max'} =~ /^\d+$/) {
3376: $max = $passwdconf{'max'};
3377: }
3378: @chars = @{$passwdconf{'chars'}};
3379: }
3380: if (($min) && (length($plainpass) < $min)) {
3381: push(@brokerule,'min');
3382: }
3383: if (($max) && (length($plainpass) > $max)) {
3384: push(@brokerule,'max');
3385: }
3386: if (@chars) {
3387: my %rules;
3388: map { $rules{$_} = 1; } @chars;
3389: if ($rules{'uc'}) {
3390: unless ($plainpass =~ /[A-Z]/) {
3391: push(@brokerule,'uc');
3392: }
3393: }
3394: if ($rules{'lc'}) {
3395: unless ($plainpass =~ /[a-z]/) {
3396: push(@brokerule,'lc');
3397: }
3398: }
3399: if ($rules{'num'}) {
3400: unless ($plainpass =~ /\d/) {
3401: push(@brokerule,'num');
3402: }
3403: }
3404: if ($rules{'spec'}) {
3405: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3406: push(@brokerule,'spec');
3407: }
3408: }
3409: }
3410: if (@brokerule) {
3411: my %rulenames = &Apache::lonlocal::texthash(
3412: uc => 'At least one upper case letter',
3413: lc => 'At least one lower case letter',
3414: num => 'At least one number',
3415: spec => 'At least one non-alphanumeric',
3416: );
3417: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3418: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3419: $rulenames{'num'} .= ': 0123456789';
3420: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3421: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3422: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3423: $warning = &mt('Password did not satisfy the following:').'<ul>';
3424: foreach my $rule ('min','max','uc','lc','num','spec') {
3425: if (grep(/^$rule$/,@brokerule)) {
3426: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3427: }
3428: }
3429: $warning .= '</ul>';
3430: }
3431: if (wantarray) {
3432: return @brokerule;
3433: }
3434: return $warning;
3435: }
3436:
3437: sub passwd_validation_js {
3438: my ($currpasswdval,$domain,$context,$id) = @_;
3439: my (%passwdconf,$alertmsg);
3440: if ($context eq 'linkprot') {
3441: my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
3442: if (ref($domconfig{'ltisec'}) eq 'HASH') {
3443: if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
3444: %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
3445: }
3446: }
3447: if ($id eq 'add') {
3448: $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
3449: } elsif ($id =~ /^\d+$/) {
3450: my $pos = $id+1;
3451: $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
3452: } else {
3453: $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
3454: }
3455: } else {
3456: %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3457: $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
3458: }
3459: my ($min,$max,@chars,$numrules,$intargjs,%alert);
3460: $numrules = 0;
3461: $min = $Apache::lonnet::passwdmin;
3462: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3463: if ($passwdconf{'min'} =~ /^\d+$/) {
3464: if ($passwdconf{'min'} > $min) {
3465: $min = $passwdconf{'min'};
3466: }
3467: }
3468: if ($passwdconf{'max'} =~ /^\d+$/) {
3469: $max = $passwdconf{'max'};
3470: $numrules ++;
3471: }
3472: @chars = @{$passwdconf{'chars'}};
3473: if (@chars) {
3474: $numrules ++;
3475: }
3476: }
3477: if ($min > 0) {
3478: $numrules ++;
3479: }
3480: if (($min > 0) || ($max ne '') || (@chars > 0)) {
3481: if ($min) {
3482: $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
3483: }
3484: if ($max) {
3485: $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
3486: }
3487: my (@charalerts,@charrules);
3488: if (@chars) {
3489: if (grep(/^uc$/,@chars)) {
3490: push(@charalerts,&mt('contain at least one upper case letter'));
3491: push(@charrules,'uc');
3492: }
3493: if (grep(/^lc$/,@chars)) {
3494: push(@charalerts,&mt('contain at least one lower case letter'));
3495: push(@charrules,'lc');
3496: }
3497: if (grep(/^num$/,@chars)) {
3498: push(@charalerts,&mt('contain at least one number'));
3499: push(@charrules,'num');
3500: }
3501: if (grep(/^spec$/,@chars)) {
3502: push(@charalerts,&mt('contain at least one non-alphanumeric'));
3503: push(@charrules,'spec');
3504: }
3505: }
3506: $intargjs = qq| var rulesmsg = '';\n|.
3507: qq| var currpwval = $currpasswdval;\n|;
3508: if ($min) {
3509: $intargjs .= qq|
3510: if (currpwval.length < $min) {
3511: rulesmsg += ' - $alert{min}';
3512: }
3513: |;
3514: }
3515: if ($max) {
3516: $intargjs .= qq|
3517: if (currpwval.length > $max) {
3518: rulesmsg += ' - $alert{max}';
3519: }
3520: |;
3521: }
3522: if (@chars > 0) {
3523: my $charrulestr = '"'.join('","',@charrules).'"';
3524: my $charalertstr = '"'.join('","',@charalerts).'"';
3525: $intargjs .= qq| var brokerules = new Array();\n|.
3526: qq| var charrules = new Array($charrulestr);\n|.
3527: qq| var charalerts = new Array($charalertstr);\n|;
3528: my %rules;
3529: map { $rules{$_} = 1; } @chars;
3530: if ($rules{'uc'}) {
3531: $intargjs .= qq|
3532: var ucRegExp = /[A-Z]/;
3533: if (!ucRegExp.test(currpwval)) {
3534: brokerules.push('uc');
3535: }
3536: |;
3537: }
3538: if ($rules{'lc'}) {
3539: $intargjs .= qq|
3540: var lcRegExp = /[a-z]/;
3541: if (!lcRegExp.test(currpwval)) {
3542: brokerules.push('lc');
3543: }
3544: |;
3545: }
3546: if ($rules{'num'}) {
3547: $intargjs .= qq|
3548: var numRegExp = /[0-9]/;
3549: if (!numRegExp.test(currpwval)) {
3550: brokerules.push('num');
3551: }
3552: |;
3553: }
3554: if ($rules{'spec'}) {
3555: $intargjs .= q|
3556: var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
3557: if (!specRegExp.test(currpwval)) {
3558: brokerules.push('spec');
3559: }
3560: |;
3561: }
3562: $intargjs .= qq|
3563: if (brokerules.length > 0) {
3564: for (var i=0; i<brokerules.length; i++) {
3565: for (var j=0; j<charrules.length; j++) {
3566: if (brokerules[i] == charrules[j]) {
3567: rulesmsg += ' - '+charalerts[j]+'\\n';
3568: break;
3569: }
3570: }
3571: }
3572: }
3573: |;
3574: }
3575: $intargjs .= qq|
3576: if (rulesmsg != '') {
3577: rulesmsg = '$alertmsg'+rulesmsg;
3578: alert(rulesmsg);
3579: return false;
3580: }
3581: |;
3582: }
3583: return ($numrules,$intargjs);
3584: }
3585:
3586: ###############################################################
3587: ## Get Kerberos Defaults for Domain ##
3588: ###############################################################
3589: ##
3590: ## Returns default kerberos version and an associated argument
3591: ## as listed in file domain.tab. If not listed, provides
3592: ## appropriate default domain and kerberos version.
3593: ##
3594: #-------------------------------------------
3595:
3596: =pod
3597:
3598: =item * &get_kerberos_defaults()
3599:
3600: get_kerberos_defaults($target_domain) returns the default kerberos
3601: version and domain. If not found, it defaults to version 4 and the
3602: domain of the server.
3603:
3604: =over 4
3605:
3606: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3607:
3608: =back
3609:
3610: =back
3611:
3612: =cut
3613:
3614: #-------------------------------------------
3615: sub get_kerberos_defaults {
3616: my $domain=shift;
3617: my ($krbdef,$krbdefdom);
3618: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3619: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3620: $krbdef = $domdefaults{'auth_def'};
3621: $krbdefdom = $domdefaults{'auth_arg_def'};
3622: } else {
3623: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3624: my $krbdefdom=$1;
3625: $krbdefdom=~tr/a-z/A-Z/;
3626: $krbdef = "krb4";
3627: }
3628: return ($krbdef,$krbdefdom);
3629: }
3630:
3631:
3632: ###############################################################
3633: ## Thesaurus Functions ##
3634: ###############################################################
3635:
3636: =pod
3637:
3638: =head1 Thesaurus Functions
3639:
3640: =over 4
3641:
3642: =item * &initialize_keywords()
3643:
3644: Initializes the package variable %Keywords if it is empty. Uses the
3645: package variable $thesaurus_db_file.
3646:
3647: =cut
3648:
3649: ###################################################
3650:
3651: sub initialize_keywords {
3652: return 1 if (scalar keys(%Keywords));
3653: # If we are here, %Keywords is empty, so fill it up
3654: # Make sure the file we need exists...
3655: if (! -e $thesaurus_db_file) {
3656: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3657: " failed because it does not exist");
3658: return 0;
3659: }
3660: # Set up the hash as a database
3661: my %thesaurus_db;
3662: if (! tie(%thesaurus_db,'GDBM_File',
3663: $thesaurus_db_file,&GDBM_READER(),0640)){
3664: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3665: $thesaurus_db_file);
3666: return 0;
3667: }
3668: # Get the average number of appearances of a word.
3669: my $avecount = $thesaurus_db{'average.count'};
3670: # Put keywords (those that appear > average) into %Keywords
3671: while (my ($word,$data)=each (%thesaurus_db)) {
3672: my ($count,undef) = split /:/,$data;
3673: $Keywords{$word}++ if ($count > $avecount);
3674: }
3675: untie %thesaurus_db;
3676: # Remove special values from %Keywords.
3677: foreach my $value ('total.count','average.count') {
3678: delete($Keywords{$value}) if (exists($Keywords{$value}));
3679: }
3680: return 1;
3681: }
3682:
3683: ###################################################
3684:
3685: =pod
3686:
3687: =item * &keyword($word)
3688:
3689: Returns true if $word is a keyword. A keyword is a word that appears more
3690: than the average number of times in the thesaurus database. Calls
3691: &initialize_keywords
3692:
3693: =cut
3694:
3695: ###################################################
3696:
3697: sub keyword {
3698: return if (!&initialize_keywords());
3699: my $word=lc(shift());
3700: $word=~s/\W//g;
3701: return exists($Keywords{$word});
3702: }
3703:
3704: ###############################################################
3705:
3706: =pod
3707:
3708: =item * &get_related_words()
3709:
3710: Look up a word in the thesaurus. Takes a scalar argument and returns
3711: an array of words. If the keyword is not in the thesaurus, an empty array
3712: will be returned. The order of the words returned is determined by the
3713: database which holds them.
3714:
3715: Uses global $thesaurus_db_file.
3716:
3717:
3718: =cut
3719:
3720: ###############################################################
3721: sub get_related_words {
3722: my $keyword = shift;
3723: my %thesaurus_db;
3724: if (! -e $thesaurus_db_file) {
3725: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3726: "failed because the file does not exist");
3727: return ();
3728: }
3729: if (! tie(%thesaurus_db,'GDBM_File',
3730: $thesaurus_db_file,&GDBM_READER(),0640)){
3731: return ();
3732: }
3733: my @Words=();
3734: my $count=0;
3735: if (exists($thesaurus_db{$keyword})) {
3736: # The first element is the number of times
3737: # the word appears. We do not need it now.
3738: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3739: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3740: my $threshold=$mostfrequentcount/10;
3741: foreach my $possibleword (@RelatedWords) {
3742: my ($word,$wordcount)=split(/\,/,$possibleword);
3743: if ($wordcount>$threshold) {
3744: push(@Words,$word);
3745: $count++;
3746: if ($count>10) { last; }
3747: }
3748: }
3749: }
3750: untie %thesaurus_db;
3751: return @Words;
3752: }
3753:
3754: =pod
3755:
3756: =back
3757:
3758: =cut
3759:
3760: # -------------------------------------------------------------- Plaintext name
3761: =pod
3762:
3763: =head1 User Name Functions
3764:
3765: =over 4
3766:
3767: =item * &plainname($uname,$udom,$first)
3768:
3769: Takes a users logon name and returns it as a string in
3770: "first middle last generation" form
3771: if $first is set to 'lastname' then it returns it as
3772: 'lastname generation, firstname middlename' if their is a lastname
3773:
3774: =cut
3775:
3776:
3777: ###############################################################
3778: sub plainname {
3779: my ($uname,$udom,$first)=@_;
3780: return if (!defined($uname) || !defined($udom));
3781: my %names=&getnames($uname,$udom);
3782: my $name=&Apache::lonnet::format_name($names{'firstname'},
3783: $names{'middlename'},
3784: $names{'lastname'},
3785: $names{'generation'},$first);
3786: $name=~s/^\s+//;
3787: $name=~s/\s+$//;
3788: $name=~s/\s+/ /g;
3789: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3790: return $name;
3791: }
3792:
3793: # -------------------------------------------------------------------- Nickname
3794: =pod
3795:
3796: =item * &nickname($uname,$udom)
3797:
3798: Gets a users name and returns it as a string as
3799:
3800: ""nickname""
3801:
3802: if the user has a nickname or
3803:
3804: "first middle last generation"
3805:
3806: if the user does not
3807:
3808: =cut
3809:
3810: sub nickname {
3811: my ($uname,$udom)=@_;
3812: return if (!defined($uname) || !defined($udom));
3813: my %names=&getnames($uname,$udom);
3814: my $name=$names{'nickname'};
3815: if ($name) {
3816: $name='"'.$name.'"';
3817: } else {
3818: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3819: $names{'lastname'}.' '.$names{'generation'};
3820: $name=~s/\s+$//;
3821: $name=~s/\s+/ /g;
3822: }
3823: return $name;
3824: }
3825:
3826: sub getnames {
3827: my ($uname,$udom)=@_;
3828: return if (!defined($uname) || !defined($udom));
3829: if ($udom eq 'public' && $uname eq 'public') {
3830: return ('lastname' => &mt('Public'));
3831: }
3832: my $id=$uname.':'.$udom;
3833: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3834: if ($cached) {
3835: return %{$names};
3836: } else {
3837: my %loadnames=&Apache::lonnet::get('environment',
3838: ['firstname','middlename','lastname','generation','nickname'],
3839: $udom,$uname);
3840: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3841: return %loadnames;
3842: }
3843: }
3844:
3845: # -------------------------------------------------------------------- getemails
3846:
3847: =pod
3848:
3849: =item * &getemails($uname,$udom)
3850:
3851: Gets a user's email information and returns it as a hash with keys:
3852: notification, critnotification, permanentemail
3853:
3854: For notification and critnotification, values are comma-separated lists
3855: of e-mail addresses; for permanentemail, value is a single e-mail address.
3856:
3857:
3858: =cut
3859:
3860:
3861: sub getemails {
3862: my ($uname,$udom)=@_;
3863: if ($udom eq 'public' && $uname eq 'public') {
3864: return;
3865: }
3866: if (!$udom) { $udom=$env{'user.domain'}; }
3867: if (!$uname) { $uname=$env{'user.name'}; }
3868: my $id=$uname.':'.$udom;
3869: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3870: if ($cached) {
3871: return %{$names};
3872: } else {
3873: my %loadnames=&Apache::lonnet::get('environment',
3874: ['notification','critnotification',
3875: 'permanentemail'],
3876: $udom,$uname);
3877: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3878: return %loadnames;
3879: }
3880: }
3881:
3882: sub flush_email_cache {
3883: my ($uname,$udom)=@_;
3884: if (!$udom) { $udom =$env{'user.domain'}; }
3885: if (!$uname) { $uname=$env{'user.name'}; }
3886: return if ($udom eq 'public' && $uname eq 'public');
3887: my $id=$uname.':'.$udom;
3888: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3889: }
3890:
3891: # -------------------------------------------------------------------- getlangs
3892:
3893: =pod
3894:
3895: =item * &getlangs($uname,$udom)
3896:
3897: Gets a user's language preference and returns it as a hash with key:
3898: language.
3899:
3900: =cut
3901:
3902:
3903: sub getlangs {
3904: my ($uname,$udom) = @_;
3905: if (!$udom) { $udom =$env{'user.domain'}; }
3906: if (!$uname) { $uname=$env{'user.name'}; }
3907: my $id=$uname.':'.$udom;
3908: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3909: if ($cached) {
3910: return %{$langs};
3911: } else {
3912: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3913: $udom,$uname);
3914: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3915: return %loadlangs;
3916: }
3917: }
3918:
3919: sub flush_langs_cache {
3920: my ($uname,$udom)=@_;
3921: if (!$udom) { $udom =$env{'user.domain'}; }
3922: if (!$uname) { $uname=$env{'user.name'}; }
3923: return if ($udom eq 'public' && $uname eq 'public');
3924: my $id=$uname.':'.$udom;
3925: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3926: }
3927:
3928: # ------------------------------------------------------------------ Screenname
3929:
3930: =pod
3931:
3932: =item * &screenname($uname,$udom)
3933:
3934: Gets a users screenname and returns it as a string
3935:
3936: =cut
3937:
3938: sub screenname {
3939: my ($uname,$udom)=@_;
3940: if ($uname eq $env{'user.name'} &&
3941: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3942: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3943: return $names{'screenname'};
3944: }
3945:
3946:
3947: # ------------------------------------------------------------- Confirm Wrapper
3948: =pod
3949:
3950: =item * &confirmwrapper($message)
3951:
3952: Wrap messages about completion of operation in box
3953:
3954: =cut
3955:
3956: sub confirmwrapper {
3957: my ($message)=@_;
3958: if ($message) {
3959: return "\n".'<div class="LC_confirm_box">'."\n"
3960: .$message."\n"
3961: .'</div>'."\n";
3962: } else {
3963: return $message;
3964: }
3965: }
3966:
3967: # ------------------------------------------------------------- Message Wrapper
3968:
3969: sub messagewrapper {
3970: my ($link,$username,$domain,$subject,$text)=@_;
3971: return
3972: '<a href="/adm/email?compose=individual&'.
3973: 'recname='.$username.'&recdom='.$domain.
3974: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3975: 'title="'.&mt('Send message').'">'.$link.'</a>';
3976: }
3977:
3978: # --------------------------------------------------------------- Notes Wrapper
3979:
3980: sub noteswrapper {
3981: my ($link,$un,$do)=@_;
3982: return
3983: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3984: }
3985:
3986: # ------------------------------------------------------------- Aboutme Wrapper
3987:
3988: sub aboutmewrapper {
3989: my ($link,$username,$domain,$target,$class)=@_;
3990: if (!defined($username) && !defined($domain)) {
3991: return;
3992: }
3993: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3994: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3995: }
3996:
3997: # ------------------------------------------------------------ Syllabus Wrapper
3998:
3999: sub syllabuswrapper {
4000: my ($linktext,$coursedir,$domain)=@_;
4001: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
4002: }
4003:
4004: sub aboutme_on {
4005: my ($uname,$udom)=@_;
4006: unless ($uname) { $uname=$env{'user.name'}; }
4007: unless ($udom) { $udom=$env{'user.domain'}; }
4008: return if ($udom eq 'public' && $uname eq 'public');
4009: my $hashkey=$uname.':'.$udom;
4010: my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
4011: if ($cached) {
4012: return $aboutme;
4013: }
4014: $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
4015: &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
4016: return $aboutme;
4017: }
4018:
4019: sub devalidate_aboutme_cache {
4020: my ($uname,$udom)=@_;
4021: if (!$udom) { $udom =$env{'user.domain'}; }
4022: if (!$uname) { $uname=$env{'user.name'}; }
4023: return if ($udom eq 'public' && $uname eq 'public');
4024: my $id=$uname.':'.$udom;
4025: &Apache::lonnet::devalidate_cache_new('aboutme',$id);
4026: }
4027:
4028: # -----------------------------------------------------------------------------
4029:
4030: sub track_student_link {
4031: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
4032: my $link ="/adm/trackstudent?";
4033: my $title = 'View recent activity';
4034: if (defined($sname) && $sname !~ /^\s*$/ &&
4035: defined($sdom) && $sdom !~ /^\s*$/) {
4036: $link .= "selected_student=$sname:$sdom";
4037: $title .= ' of this student';
4038: }
4039: if (defined($target) && $target !~ /^\s*$/) {
4040: $target = qq{target="$target"};
4041: } else {
4042: $target = '';
4043: }
4044: if ($start) { $link.='&start='.$start; }
4045: if ($only_body) { $link .= '&only_body=1'; }
4046: $title = &mt($title);
4047: $linktext = &mt($linktext);
4048: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
4049: &help_open_topic('View_recent_activity');
4050: }
4051:
4052: sub slot_reservations_link {
4053: my ($linktext,$sname,$sdom,$target) = @_;
4054: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
4055: my $title = 'View slot reservation history';
4056: if (defined($sname) && $sname !~ /^\s*$/ &&
4057: defined($sdom) && $sdom !~ /^\s*$/) {
4058: $link .= "&uname=$sname&udom=$sdom";
4059: $title .= ' of this student';
4060: }
4061: if (defined($target) && $target !~ /^\s*$/) {
4062: $target = qq{target="$target"};
4063: } else {
4064: $target = '';
4065: }
4066: $title = &mt($title);
4067: $linktext = &mt($linktext);
4068: return qq{<a href="$link" title="$title" $target>$linktext</a>};
4069: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
4070:
4071: }
4072:
4073: # ===================================================== Display a student photo
4074:
4075:
4076: sub student_image_tag {
4077: my ($domain,$user)=@_;
4078: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
4079: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
4080: return '<img src="'.$imgsrc.'" align="right" />';
4081: } else {
4082: return '';
4083: }
4084: }
4085:
4086: =pod
4087:
4088: =back
4089:
4090: =head1 Access .tab File Data
4091:
4092: =over 4
4093:
4094: =item * &languageids()
4095:
4096: returns list of all language ids
4097:
4098: =cut
4099:
4100: sub languageids {
4101: return sort(keys(%language));
4102: }
4103:
4104: =pod
4105:
4106: =item * &languagedescription()
4107:
4108: returns description of a specified language id
4109:
4110: =cut
4111:
4112: sub languagedescription {
4113: my $code=shift;
4114: return ($supported_language{$code}?'* ':'').
4115: $language{$code}.
4116: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4117: }
4118:
4119: =pod
4120:
4121: =item * &plainlanguagedescription
4122:
4123: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4124: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4125:
4126: =cut
4127:
4128: sub plainlanguagedescription {
4129: my $code=shift;
4130: return $language{$code};
4131: }
4132:
4133: =pod
4134:
4135: =item * &supportedlanguagecode
4136:
4137: Returns the supported language code (e.g. sptutf maps to pt) given a language
4138: code.
4139:
4140: =cut
4141:
4142: sub supportedlanguagecode {
4143: my $code=shift;
4144: return $supported_language{$code};
4145: }
4146:
4147: =pod
4148:
4149: =item * &latexlanguage()
4150:
4151: Given a language key code returns the correspondnig language to use
4152: to select the correct hyphenation on LaTeX printouts. This is undef if there
4153: is no supported hyphenation for the language code.
4154:
4155: =cut
4156:
4157: sub latexlanguage {
4158: my $code = shift;
4159: return $latex_language{$code};
4160: }
4161:
4162: =pod
4163:
4164: =item * &latexhyphenation()
4165:
4166: Same as above but what's supplied is the language as it might be stored
4167: in the metadata.
4168:
4169: =cut
4170:
4171: sub latexhyphenation {
4172: my $key = shift;
4173: return $latex_language_bykey{$key};
4174: }
4175:
4176: =pod
4177:
4178: =item * ©rightids()
4179:
4180: returns list of all copyrights
4181:
4182: =cut
4183:
4184: sub copyrightids {
4185: return sort(keys(%cprtag));
4186: }
4187:
4188: =pod
4189:
4190: =item * ©rightdescription()
4191:
4192: returns description of a specified copyright id
4193:
4194: =cut
4195:
4196: sub copyrightdescription {
4197: return &mt($cprtag{shift(@_)});
4198: }
4199:
4200: =pod
4201:
4202: =item * &source_copyrightids()
4203:
4204: returns list of all source copyrights
4205:
4206: =cut
4207:
4208: sub source_copyrightids {
4209: return sort(keys(%scprtag));
4210: }
4211:
4212: =pod
4213:
4214: =item * &source_copyrightdescription()
4215:
4216: returns description of a specified source copyright id
4217:
4218: =cut
4219:
4220: sub source_copyrightdescription {
4221: return &mt($scprtag{shift(@_)});
4222: }
4223:
4224: =pod
4225:
4226: =item * &filecategories()
4227:
4228: returns list of all file categories
4229:
4230: =cut
4231:
4232: sub filecategories {
4233: return sort(keys(%category_extensions));
4234: }
4235:
4236: =pod
4237:
4238: =item * &filecategorytypes()
4239:
4240: returns list of file types belonging to a given file
4241: category
4242:
4243: =cut
4244:
4245: sub filecategorytypes {
4246: my ($cat) = @_;
4247: return @{$category_extensions{lc($cat)}};
4248: }
4249:
4250: =pod
4251:
4252: =item * &fileembstyle()
4253:
4254: returns embedding style for a specified file type
4255:
4256: =cut
4257:
4258: sub fileembstyle {
4259: return $fe{lc(shift(@_))};
4260: }
4261:
4262: sub filemimetype {
4263: return $fm{lc(shift(@_))};
4264: }
4265:
4266:
4267: sub filecategoryselect {
4268: my ($name,$value)=@_;
4269: return &select_form($value,$name,
4270: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4271: }
4272:
4273: =pod
4274:
4275: =item * &filedescription()
4276:
4277: returns description for a specified file type
4278:
4279: =cut
4280:
4281: sub filedescription {
4282: my $file_description = $fd{lc(shift())};
4283: $file_description =~ s:([\[\]]):~$1:g;
4284: return &mt($file_description);
4285: }
4286:
4287: =pod
4288:
4289: =item * &filedescriptionex()
4290:
4291: returns description for a specified file type with
4292: extra formatting
4293:
4294: =cut
4295:
4296: sub filedescriptionex {
4297: my $ex=shift;
4298: my $file_description = $fd{lc($ex)};
4299: $file_description =~ s:([\[\]]):~$1:g;
4300: return '.'.$ex.' '.&mt($file_description);
4301: }
4302:
4303: # End of .tab access
4304: =pod
4305:
4306: =back
4307:
4308: =cut
4309:
4310: # ------------------------------------------------------------------ File Types
4311: sub fileextensions {
4312: return sort(keys(%fe));
4313: }
4314:
4315: # ----------------------------------------------------------- Display Languages
4316: # returns a hash with all desired display languages
4317: #
4318:
4319: sub display_languages {
4320: my %languages=();
4321: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4322: $languages{$lang}=1;
4323: }
4324: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4325: if ($env{'form.displaylanguage'}) {
4326: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4327: $languages{$lang}=1;
4328: }
4329: }
4330: return %languages;
4331: }
4332:
4333: sub languages {
4334: my ($possible_langs) = @_;
4335: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4336: if (!ref($possible_langs)) {
4337: if( wantarray ) {
4338: return @preferred_langs;
4339: } else {
4340: return $preferred_langs[0];
4341: }
4342: }
4343: my %possibilities = map { $_ => 1 } (@$possible_langs);
4344: my @preferred_possibilities;
4345: foreach my $preferred_lang (@preferred_langs) {
4346: if (exists($possibilities{$preferred_lang})) {
4347: push(@preferred_possibilities, $preferred_lang);
4348: }
4349: }
4350: if( wantarray ) {
4351: return @preferred_possibilities;
4352: }
4353: return $preferred_possibilities[0];
4354: }
4355:
4356: sub user_lang {
4357: my ($touname,$toudom,$fromcid) = @_;
4358: my @userlangs;
4359: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4360: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4361: $env{'course.'.$fromcid.'.languages'}));
4362: } else {
4363: my %langhash = &getlangs($touname,$toudom);
4364: if ($langhash{'languages'} ne '') {
4365: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4366: } else {
4367: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4368: if ($domdefs{'lang_def'} ne '') {
4369: @userlangs = ($domdefs{'lang_def'});
4370: }
4371: }
4372: }
4373: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4374: my $user_lh = Apache::localize->get_handle(@languages);
4375: return $user_lh;
4376: }
4377:
4378:
4379: ###############################################################
4380: ## Student Answer Attempts ##
4381: ###############################################################
4382:
4383: =pod
4384:
4385: =head1 Alternate Problem Views
4386:
4387: =over 4
4388:
4389: =item * &get_previous_attempt($symb, $username, $domain, $course,
4390: $getattempt, $regexp, $gradesub, $usec, $identifier)
4391:
4392: Return string with previous attempt on problem. Arguments:
4393:
4394: =over 4
4395:
4396: =item * $symb: Problem, including path
4397:
4398: =item * $username: username of the desired student
4399:
4400: =item * $domain: domain of the desired student
4401:
4402: =item * $course: Course ID
4403:
4404: =item * $getattempt: Leave blank for all attempts, otherwise put
4405: something
4406:
4407: =item * $regexp: if string matches this regexp, the string will be
4408: sent to $gradesub
4409:
4410: =item * $gradesub: routine that processes the string if it matches $regexp
4411:
4412: =item * $usec: section of the desired student
4413:
4414: =item * $identifier: counter for student (multiple students one problem) or
4415: problem (one student; whole sequence).
4416:
4417: =back
4418:
4419: The output string is a table containing all desired attempts, if any.
4420:
4421: =cut
4422:
4423: sub get_previous_attempt {
4424: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4425: my $prevattempts='';
4426: no strict 'refs';
4427: if ($symb) {
4428: my (%returnhash)=
4429: &Apache::lonnet::restore($symb,$course,$domain,$username);
4430: if ($returnhash{'version'}) {
4431: my %lasthash=();
4432: my $version;
4433: for ($version=1;$version<=$returnhash{'version'};$version++) {
4434: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4435: if ($key =~ /\.rawrndseed$/) {
4436: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4437: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4438: } else {
4439: $lasthash{$key}=$returnhash{$version.':'.$key};
4440: }
4441: }
4442: }
4443: $prevattempts=&start_data_table().&start_data_table_header_row();
4444: $prevattempts.='<th>'.&mt('History').'</th>';
4445: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4446: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4447: foreach my $key (sort(keys(%lasthash))) {
4448: my ($ign,@parts) = split(/\./,$key);
4449: if ($#parts > 0) {
4450: my $data=$parts[-1];
4451: next if ($data eq 'foilorder');
4452: pop(@parts);
4453: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4454: if ($data eq 'type') {
4455: unless ($showsurv) {
4456: my $id = join(',',@parts);
4457: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4458: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4459: $lasthidden{$ign.'.'.$id} = 1;
4460: }
4461: }
4462: if ($identifier ne '') {
4463: my $id = join(',',@parts);
4464: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4465: $domain,$username,$usec,undef,$course) =~ /^no/) {
4466: $hidestatus{$ign.'.'.$id} = 1;
4467: }
4468: }
4469: } elsif ($data eq 'regrader') {
4470: if (($identifier ne '') && (@parts)) {
4471: my $id = join(',',@parts);
4472: $regraded{$ign.'.'.$id} = 1;
4473: }
4474: }
4475: } else {
4476: if ($#parts == 0) {
4477: $prevattempts.='<th>'.$parts[0].'</th>';
4478: } else {
4479: $prevattempts.='<th>'.$ign.'</th>';
4480: }
4481: }
4482: }
4483: $prevattempts.=&end_data_table_header_row();
4484: if ($getattempt eq '') {
4485: my (%solved,%resets,%probstatus);
4486: if (($identifier ne '') && (keys(%regraded) > 0)) {
4487: for ($version=1;$version<=$returnhash{'version'};$version++) {
4488: foreach my $id (keys(%regraded)) {
4489: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4490: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4491: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4492: push(@{$resets{$id}},$version);
4493: }
4494: }
4495: }
4496: }
4497: for ($version=1;$version<=$returnhash{'version'};$version++) {
4498: my (@hidden,@unsolved);
4499: if (%typeparts) {
4500: foreach my $id (keys(%typeparts)) {
4501: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4502: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4503: push(@hidden,$id);
4504: } elsif ($identifier ne '') {
4505: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4506: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4507: ($hidestatus{$id})) {
4508: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4509: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4510: push(@{$solved{$id}},$version);
4511: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4512: (ref($solved{$id}) eq 'ARRAY')) {
4513: my $skip;
4514: if (ref($resets{$id}) eq 'ARRAY') {
4515: foreach my $reset (@{$resets{$id}}) {
4516: if ($reset > $solved{$id}[-1]) {
4517: $skip=1;
4518: last;
4519: }
4520: }
4521: }
4522: unless ($skip) {
4523: my ($ign,$partslist) = split(/\./,$id,2);
4524: push(@unsolved,$partslist);
4525: }
4526: }
4527: }
4528: }
4529: }
4530: }
4531: $prevattempts.=&start_data_table_row().
4532: '<td>'.&mt('Transaction [_1]',$version);
4533: if (@unsolved) {
4534: $prevattempts .= '<span class="LC_nobreak"><label>'.
4535: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4536: &mt('Hide').'</label></span>';
4537: }
4538: $prevattempts .= '</td>';
4539: if (@hidden) {
4540: foreach my $key (sort(keys(%lasthash))) {
4541: next if ($key =~ /\.foilorder$/);
4542: my $hide;
4543: foreach my $id (@hidden) {
4544: if ($key =~ /^\Q$id\E/) {
4545: $hide = 1;
4546: last;
4547: }
4548: }
4549: if ($hide) {
4550: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4551: if (($data eq 'award') || ($data eq 'awarddetail')) {
4552: my $value = &format_previous_attempt_value($key,
4553: $returnhash{$version.':'.$key});
4554: $prevattempts.='<td>'.$value.' </td>';
4555: } else {
4556: $prevattempts.='<td> </td>';
4557: }
4558: } else {
4559: if ($key =~ /\./) {
4560: my $value = $returnhash{$version.':'.$key};
4561: if ($key =~ /\.rndseed$/) {
4562: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4563: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4564: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4565: }
4566: }
4567: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4568: ' </td>';
4569: } else {
4570: $prevattempts.='<td> </td>';
4571: }
4572: }
4573: }
4574: } else {
4575: foreach my $key (sort(keys(%lasthash))) {
4576: next if ($key =~ /\.foilorder$/);
4577: my $value = $returnhash{$version.':'.$key};
4578: if ($key =~ /\.rndseed$/) {
4579: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4580: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4581: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4582: }
4583: }
4584: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4585: ' </td>';
4586: }
4587: }
4588: $prevattempts.=&end_data_table_row();
4589: }
4590: }
4591: my @currhidden = keys(%lasthidden);
4592: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4593: foreach my $key (sort(keys(%lasthash))) {
4594: next if ($key =~ /\.foilorder$/);
4595: if (%typeparts) {
4596: my $hidden;
4597: foreach my $id (@currhidden) {
4598: if ($key =~ /^\Q$id\E/) {
4599: $hidden = 1;
4600: last;
4601: }
4602: }
4603: if ($hidden) {
4604: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4605: if (($data eq 'award') || ($data eq 'awarddetail')) {
4606: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4607: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4608: $value = &$gradesub($value);
4609: }
4610: $prevattempts.='<td>'.$value.' </td>';
4611: } else {
4612: $prevattempts.='<td> </td>';
4613: }
4614: } else {
4615: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4616: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4617: $value = &$gradesub($value);
4618: }
4619: $prevattempts.='<td>'.$value.' </td>';
4620: }
4621: } else {
4622: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4623: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4624: $value = &$gradesub($value);
4625: }
4626: $prevattempts.='<td>'.$value.' </td>';
4627: }
4628: }
4629: $prevattempts.= &end_data_table_row().&end_data_table();
4630: } else {
4631: my $msg;
4632: if ($symb =~ /ext\.tool$/) {
4633: $msg = &mt('No grade passed back.');
4634: } else {
4635: $msg = &mt('Nothing submitted - no attempts.');
4636: }
4637: $prevattempts=
4638: &start_data_table().&start_data_table_row().
4639: '<td>'.$msg.'</td>'.
4640: &end_data_table_row().&end_data_table();
4641: }
4642: } else {
4643: $prevattempts=
4644: &start_data_table().&start_data_table_row().
4645: '<td>'.&mt('No data.').'</td>'.
4646: &end_data_table_row().&end_data_table();
4647: }
4648: }
4649:
4650: sub format_previous_attempt_value {
4651: my ($key,$value) = @_;
4652: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4653: $value = &Apache::lonlocal::locallocaltime($value);
4654: } elsif (ref($value) eq 'ARRAY') {
4655: $value = '('.join(', ', @{ $value }).')';
4656: } elsif ($key =~ /answerstring$/) {
4657: my %answers = &Apache::lonnet::str2hash($value);
4658: my @anskeys = sort(keys(%answers));
4659: if (@anskeys == 1) {
4660: my $answer = $answers{$anskeys[0]};
4661: if ($answer =~ m{\0}) {
4662: $answer =~ s{\0}{,}g;
4663: }
4664: my $tag_internal_answer_name = 'INTERNAL';
4665: if ($anskeys[0] eq $tag_internal_answer_name) {
4666: $value = $answer;
4667: } else {
4668: $value = $anskeys[0].'='.$answer;
4669: }
4670: } else {
4671: foreach my $ans (@anskeys) {
4672: my $answer = $answers{$ans};
4673: if ($answer =~ m{\0}) {
4674: $answer =~ s{\0}{,}g;
4675: }
4676: $value .= $ans.'='.$answer.'<br />';;
4677: }
4678: }
4679: } else {
4680: $value = &unescape($value);
4681: }
4682: return $value;
4683: }
4684:
4685:
4686: sub relative_to_absolute {
4687: my ($url,$output)=@_;
4688: my $parser=HTML::TokeParser->new(\$output);
4689: my $token;
4690: my $thisdir=$url;
4691: my @rlinks=();
4692: while ($token=$parser->get_token) {
4693: if ($token->[0] eq 'S') {
4694: if ($token->[1] eq 'a') {
4695: if ($token->[2]->{'href'}) {
4696: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4697: }
4698: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4699: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4700: } elsif ($token->[1] eq 'base') {
4701: $thisdir=$token->[2]->{'href'};
4702: }
4703: }
4704: }
4705: $thisdir=~s-/[^/]*$--;
4706: foreach my $link (@rlinks) {
4707: unless (($link=~/^https?\:\/\//i) ||
4708: ($link=~/^\//) ||
4709: ($link=~/^javascript:/i) ||
4710: ($link=~/^mailto:/i) ||
4711: ($link=~/^\#/)) {
4712: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4713: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4714: }
4715: }
4716: # -------------------------------------------------- Deal with Applet codebases
4717: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4718: return $output;
4719: }
4720:
4721: =pod
4722:
4723: =item * &get_student_view()
4724:
4725: show a snapshot of what student was looking at
4726:
4727: =cut
4728:
4729: sub get_student_view {
4730: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4731: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4732: my (%form);
4733: my @elements=('symb','courseid','domain','username');
4734: foreach my $element (@elements) {
4735: $form{'grade_'.$element}=eval '$'.$element #'
4736: }
4737: if (defined($moreenv)) {
4738: %form=(%form,%{$moreenv});
4739: }
4740: if (defined($target)) { $form{'grade_target'} = $target; }
4741: $feedurl=&Apache::lonnet::clutter($feedurl);
4742: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4743: $userview=~s/\<body[^\>]*\>//gi;
4744: $userview=~s/\<\/body\>//gi;
4745: $userview=~s/\<html\>//gi;
4746: $userview=~s/\<\/html\>//gi;
4747: $userview=~s/\<head\>//gi;
4748: $userview=~s/\<\/head\>//gi;
4749: $userview=~s/action\s*\=/would_be_action\=/gi;
4750: $userview=&relative_to_absolute($feedurl,$userview);
4751: if (wantarray) {
4752: return ($userview,$response);
4753: } else {
4754: return $userview;
4755: }
4756: }
4757:
4758: sub get_student_view_with_retries {
4759: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4760:
4761: my $ok = 0; # True if we got a good response.
4762: my $content;
4763: my $response;
4764:
4765: # Try to get the student_view done. within the retries count:
4766:
4767: do {
4768: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4769: $ok = $response->is_success;
4770: if (!$ok) {
4771: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4772: }
4773: $retries--;
4774: } while (!$ok && ($retries > 0));
4775:
4776: if (!$ok) {
4777: $content = ''; # On error return an empty content.
4778: }
4779: if (wantarray) {
4780: return ($content, $response);
4781: } else {
4782: return $content;
4783: }
4784: }
4785:
4786: sub css_links {
4787: my ($currsymb,$level) = @_;
4788: my ($links,@symbs,%cssrefs,%httpref);
4789: if ($level eq 'map') {
4790: my $navmap = Apache::lonnavmaps::navmap->new();
4791: if (ref($navmap)) {
4792: my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
4793: my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
4794: foreach my $res (@resources) {
4795: if (ref($res) && $res->symb()) {
4796: push(@symbs,$res->symb());
4797: }
4798: }
4799: }
4800: } else {
4801: @symbs = ($currsymb);
4802: }
4803: foreach my $symb (@symbs) {
4804: my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
4805: if ($css_href =~ /\S/) {
4806: unless ($css_href =~ m{https?://}) {
4807: my $url = (&Apache::lonnet::decode_symb($symb))[-1];
4808: my $proburl = &Apache::lonnet::clutter($url);
4809: my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
4810: unless ($css_href =~ m{^/}) {
4811: $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
4812: }
4813: if ($css_href =~ m{^/(res|uploaded)/}) {
4814: unless (($httpref{'httpref.'.$css_href}) ||
4815: (&Apache::lonnet::is_on_map($css_href))) {
4816: my $thisurl = $proburl;
4817: if ($env{'httpref.'.$proburl}) {
4818: $thisurl = $env{'httpref.'.$proburl};
4819: }
4820: $httpref{'httpref.'.$css_href} = $thisurl;
4821: }
4822: }
4823: }
4824: $cssrefs{$css_href} = 1;
4825: }
4826: }
4827: if (keys(%httpref)) {
4828: &Apache::lonnet::appenv(\%httpref);
4829: }
4830: if (keys(%cssrefs)) {
4831: foreach my $css_href (keys(%cssrefs)) {
4832: next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
4833: $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
4834: }
4835: }
4836: return $links;
4837: }
4838:
4839: =pod
4840:
4841: =item * &get_student_answers()
4842:
4843: show a snapshot of how student was answering problem
4844:
4845: =cut
4846:
4847: sub get_student_answers {
4848: my ($symb,$username,$domain,$courseid,%form) = @_;
4849: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4850: my (%moreenv);
4851: my @elements=('symb','courseid','domain','username');
4852: foreach my $element (@elements) {
4853: $moreenv{'grade_'.$element}=eval '$'.$element #'
4854: }
4855: $moreenv{'grade_target'}='answer';
4856: %moreenv=(%form,%moreenv);
4857: $feedurl = &Apache::lonnet::clutter($feedurl);
4858: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4859: return $userview;
4860: }
4861:
4862: =pod
4863:
4864: =item * &submlink()
4865:
4866: Inputs: $text $uname $udom $symb $target
4867:
4868: Returns: A link to grades.pm such as to see the SUBM view of a student
4869:
4870: =cut
4871:
4872: ###############################################
4873: sub submlink {
4874: my ($text,$uname,$udom,$symb,$target)=@_;
4875: if (!($uname && $udom)) {
4876: (my $cursymb, my $courseid,$udom,$uname)=
4877: &Apache::lonnet::whichuser($symb);
4878: if (!$symb) { $symb=$cursymb; }
4879: }
4880: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4881: $symb=&escape($symb);
4882: if ($target) { $target=" target=\"$target\""; }
4883: return
4884: '<a href="/adm/grades?command=submission'.
4885: '&symb='.$symb.
4886: '&student='.$uname.
4887: '&userdom='.$udom.'"'.
4888: $target.'>'.$text.'</a>';
4889: }
4890: ##############################################
4891:
4892: =pod
4893:
4894: =item * &pgrdlink()
4895:
4896: Inputs: $text $uname $udom $symb $target
4897:
4898: Returns: A link to grades.pm such as to see the PGRD view of a student
4899:
4900: =cut
4901:
4902: ###############################################
4903: sub pgrdlink {
4904: my $link=&submlink(@_);
4905: $link=~s/(&command=submission)/$1&showgrading=yes/;
4906: return $link;
4907: }
4908: ##############################################
4909:
4910: =pod
4911:
4912: =item * &pprmlink()
4913:
4914: Inputs: $text $uname $udom $symb $target
4915:
4916: Returns: A link to parmset.pm such as to see the PPRM view of a
4917: student and a specific resource
4918:
4919: =cut
4920:
4921: ###############################################
4922: sub pprmlink {
4923: my ($text,$uname,$udom,$symb,$target)=@_;
4924: if (!($uname && $udom)) {
4925: (my $cursymb, my $courseid,$udom,$uname)=
4926: &Apache::lonnet::whichuser($symb);
4927: if (!$symb) { $symb=$cursymb; }
4928: }
4929: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4930: $symb=&escape($symb);
4931: if ($target) { $target="target=\"$target\""; }
4932: return '<a href="/adm/parmset?command=set&'.
4933: 'symb='.$symb.'&uname='.$uname.
4934: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4935: }
4936: ##############################################
4937:
4938: =pod
4939:
4940: =back
4941:
4942: =cut
4943:
4944: ###############################################
4945:
4946:
4947: sub timehash {
4948: my ($thistime) = @_;
4949: my $timezone = &Apache::lonlocal::gettimezone();
4950: my $dt = DateTime->from_epoch(epoch => $thistime)
4951: ->set_time_zone($timezone);
4952: my $wday = $dt->day_of_week();
4953: if ($wday == 7) { $wday = 0; }
4954: return ( 'second' => $dt->second(),
4955: 'minute' => $dt->minute(),
4956: 'hour' => $dt->hour(),
4957: 'day' => $dt->day_of_month(),
4958: 'month' => $dt->month(),
4959: 'year' => $dt->year(),
4960: 'weekday' => $wday,
4961: 'dayyear' => $dt->day_of_year(),
4962: 'dlsav' => $dt->is_dst() );
4963: }
4964:
4965: sub utc_string {
4966: my ($date)=@_;
4967: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4968: }
4969:
4970: sub maketime {
4971: my %th=@_;
4972: my ($epoch_time,$timezone,$dt);
4973: $timezone = &Apache::lonlocal::gettimezone();
4974: eval {
4975: $dt = DateTime->new( year => $th{'year'},
4976: month => $th{'month'},
4977: day => $th{'day'},
4978: hour => $th{'hour'},
4979: minute => $th{'minute'},
4980: second => $th{'second'},
4981: time_zone => $timezone,
4982: );
4983: };
4984: if (!$@) {
4985: $epoch_time = $dt->epoch;
4986: if ($epoch_time) {
4987: return $epoch_time;
4988: }
4989: }
4990: return POSIX::mktime(
4991: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4992: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4993: }
4994:
4995: #########################################
4996:
4997: sub findallcourses {
4998: my ($roles,$uname,$udom) = @_;
4999: my %roles;
5000: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
5001: my %courses;
5002: my $now=time;
5003: if (!defined($uname)) {
5004: $uname = $env{'user.name'};
5005: }
5006: if (!defined($udom)) {
5007: $udom = $env{'user.domain'};
5008: }
5009: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
5010: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
5011: if (!%roles) {
5012: %roles = (
5013: cc => 1,
5014: co => 1,
5015: in => 1,
5016: ep => 1,
5017: ta => 1,
5018: cr => 1,
5019: st => 1,
5020: );
5021: }
5022: foreach my $entry (keys(%roleshash)) {
5023: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
5024: if ($trole =~ /^cr/) {
5025: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
5026: } else {
5027: next if (!exists($roles{$trole}));
5028: }
5029: if ($tend) {
5030: next if ($tend < $now);
5031: }
5032: if ($tstart) {
5033: next if ($tstart > $now);
5034: }
5035: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
5036: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
5037: my $value = $trole.'/'.$cdom.'/';
5038: if ($secpart eq '') {
5039: ($cnum,$role) = split(/_/,$cnumpart);
5040: $sec = 'none';
5041: $value .= $cnum.'/';
5042: } else {
5043: $cnum = $cnumpart;
5044: ($sec,$role) = split(/_/,$secpart);
5045: $value .= $cnum.'/'.$sec;
5046: }
5047: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5048: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5049: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5050: }
5051: } else {
5052: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5053: }
5054: }
5055: } else {
5056: foreach my $key (keys(%env)) {
5057: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
5058: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
5059: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
5060: next if ($role eq 'ca' || $role eq 'aa');
5061: next if (%roles && !exists($roles{$role}));
5062: my ($starttime,$endtime)=split(/\./,$env{$key});
5063: my $active=1;
5064: if ($starttime) {
5065: if ($now<$starttime) { $active=0; }
5066: }
5067: if ($endtime) {
5068: if ($now>$endtime) { $active=0; }
5069: }
5070: if ($active) {
5071: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
5072: if ($sec eq '') {
5073: $sec = 'none';
5074: } else {
5075: $value .= $sec;
5076: }
5077: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5078: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5079: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5080: }
5081: } else {
5082: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5083: }
5084: }
5085: }
5086: }
5087: }
5088: return %courses;
5089: }
5090:
5091: ###############################################
5092:
5093: sub blockcheck {
5094: my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5095:
5096: unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
5097: my ($has_evb,$check_ipaccess);
5098: my $dom = $env{'user.domain'};
5099: if ($env{'request.course.id'}) {
5100: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5101: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5102: my $checkrole = "cm./$cdom/$cnum";
5103: my $sec = $env{'request.course.sec'};
5104: if ($sec ne '') {
5105: $checkrole .= "/$sec";
5106: }
5107: if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
5108: ($env{'request.role'} !~ /^st/)) {
5109: $has_evb = 1;
5110: }
5111: unless ($has_evb) {
5112: if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
5113: ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
5114: if ($udom eq $cdom) {
5115: $check_ipaccess = 1;
5116: }
5117: }
5118: }
5119: } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
5120: ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
5121: my $checkrole;
5122: if ($env{'request.role.domain'} eq '') {
5123: $checkrole = "cm./$env{'user.domain'}/";
5124: } else {
5125: $checkrole = "cm./$env{'request.role.domain'}/";
5126: }
5127: if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
5128: $has_evb = 1;
5129: }
5130: }
5131: unless ($has_evb || $check_ipaccess) {
5132: my @machinedoms = &Apache::lonnet::current_machine_domains();
5133: if (($dom eq 'public') && ($activity eq 'port')) {
5134: $dom = $udom;
5135: }
5136: if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
5137: $check_ipaccess = 1;
5138: } else {
5139: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
5140: my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
5141: my $prim = &Apache::lonnet::domain($dom,'primary');
5142: my $intdom = &Apache::lonnet::internet_dom($prim);
5143: if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
5144: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
5145: $check_ipaccess = 1;
5146: }
5147: }
5148: }
5149: }
5150: if ($check_ipaccess) {
5151: my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
5152: unless (defined($cached)) {
5153: my %domconfig =
5154: &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
5155: $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
5156: }
5157: if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
5158: foreach my $id (keys(%{$ipaccessref})) {
5159: if (ref($ipaccessref->{$id}) eq 'HASH') {
5160: my $range = $ipaccessref->{$id}->{'ip'};
5161: if ($range) {
5162: if (&Apache::lonnet::ip_match($clientip,$range)) {
5163: if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
5164: if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
5165: return ('','','',$id,$dom);
5166: last;
5167: }
5168: }
5169: }
5170: }
5171: }
5172: }
5173: }
5174: }
5175: if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5176: return ();
5177: }
5178: }
5179: if (defined($udom) && defined($uname)) {
5180: # If uname and udom are for a course, check for blocks in the course.
5181: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
5182: my ($startblock,$endblock,$triggerblock) =
5183: &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
5184: return ($startblock,$endblock,$triggerblock);
5185: }
5186: } else {
5187: $udom = $env{'user.domain'};
5188: $uname = $env{'user.name'};
5189: }
5190:
5191: my $startblock = 0;
5192: my $endblock = 0;
5193: my $triggerblock = '';
5194: my %live_courses;
5195: unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5196: %live_courses = &findallcourses(undef,$uname,$udom);
5197: }
5198:
5199: # If uname is for a user, and activity is course-specific, i.e.,
5200: # boards, chat or groups, check for blocking in current course only.
5201:
5202: if (($activity eq 'boards' || $activity eq 'chat' ||
5203: $activity eq 'groups' || $activity eq 'printout' ||
5204: $activity eq 'search' || $activity eq 'reinit' ||
5205: $activity eq 'alert') && ($env{'request.course.id'})) {
5206: foreach my $key (keys(%live_courses)) {
5207: if ($key ne $env{'request.course.id'}) {
5208: delete($live_courses{$key});
5209: }
5210: }
5211: }
5212:
5213: my $otheruser = 0;
5214: my %own_courses;
5215: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
5216: # Resource belongs to user other than current user.
5217: $otheruser = 1;
5218: # Gather courses for current user
5219: %own_courses =
5220: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
5221: }
5222:
5223: # Gather active course roles - course coordinator, instructor,
5224: # exam proctor, ta, student, or custom role.
5225:
5226: foreach my $course (keys(%live_courses)) {
5227: my ($cdom,$cnum);
5228: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5229: $cdom = $env{'course.'.$course.'.domain'};
5230: $cnum = $env{'course.'.$course.'.num'};
5231: } else {
5232: ($cdom,$cnum) = split(/_/,$course);
5233: }
5234: my $no_ownblock = 0;
5235: my $no_userblock = 0;
5236: if ($otheruser && $activity ne 'com') {
5237: # Check if current user has 'evb' priv for this
5238: if (defined($own_courses{$course})) {
5239: foreach my $sec (keys(%{$own_courses{$course}})) {
5240: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5241: if ($sec ne 'none') {
5242: $checkrole .= '/'.$sec;
5243: }
5244: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5245: $no_ownblock = 1;
5246: last;
5247: }
5248: }
5249: }
5250: # if they have 'evb' priv and are currently not playing student
5251: next if (($no_ownblock) &&
5252: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5253: }
5254: foreach my $sec (keys(%{$live_courses{$course}})) {
5255: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5256: if ($sec ne 'none') {
5257: $checkrole .= '/'.$sec;
5258: }
5259: if ($otheruser) {
5260: # Resource belongs to user other than current user.
5261: # Assemble privs for that user, and check for 'evb' priv.
5262: my (%allroles,%userroles);
5263: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5264: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5265: my ($trole,$tdom,$tnum,$tsec);
5266: if ($entry =~ /^cr/) {
5267: ($trole,$tdom,$tnum,$tsec) =
5268: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5269: } else {
5270: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5271: }
5272: my ($spec,$area,$trest);
5273: $area = '/'.$tdom.'/'.$tnum;
5274: $trest = $tnum;
5275: if ($tsec ne '') {
5276: $area .= '/'.$tsec;
5277: $trest .= '/'.$tsec;
5278: }
5279: $spec = $trole.'.'.$area;
5280: if ($trole =~ /^cr/) {
5281: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5282: $tdom,$spec,$trest,$area);
5283: } else {
5284: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5285: $tdom,$spec,$trest,$area);
5286: }
5287: }
5288: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5289: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5290: if ($1) {
5291: $no_userblock = 1;
5292: last;
5293: }
5294: }
5295: }
5296: } else {
5297: # Resource belongs to current user
5298: # Check for 'evb' priv via lonnet::allowed().
5299: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5300: $no_ownblock = 1;
5301: last;
5302: }
5303: }
5304: }
5305: # if they have the evb priv and are currently not playing student
5306: next if (($no_ownblock) &&
5307: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5308: next if ($no_userblock);
5309:
5310: # Retrieve blocking times and identity of blocker for course
5311: # of specified user, unless user has 'evb' privilege.
5312:
5313: my ($start,$end,$trigger) =
5314: &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
5315: if (($start != 0) &&
5316: (($startblock == 0) || ($startblock > $start))) {
5317: $startblock = $start;
5318: if ($trigger ne '') {
5319: $triggerblock = $trigger;
5320: }
5321: }
5322: if (($end != 0) &&
5323: (($endblock == 0) || ($endblock < $end))) {
5324: $endblock = $end;
5325: if ($trigger ne '') {
5326: $triggerblock = $trigger;
5327: }
5328: }
5329: }
5330: return ($startblock,$endblock,$triggerblock);
5331: }
5332:
5333: sub get_blocks {
5334: my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
5335: my $startblock = 0;
5336: my $endblock = 0;
5337: my $triggerblock = '';
5338: my $course = $cdom.'_'.$cnum;
5339: $setters->{$course} = {};
5340: $setters->{$course}{'staff'} = [];
5341: $setters->{$course}{'times'} = [];
5342: $setters->{$course}{'triggers'} = [];
5343: my (@blockers,%triggered);
5344: my $now = time;
5345: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5346: if ($activity eq 'docs') {
5347: my ($blocked,$nosymbcache,$noenccheck);
5348: if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
5349: $blocked = 1;
5350: $nosymbcache = 1;
5351: $noenccheck = 1;
5352: }
5353: @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
5354: foreach my $block (@blockers) {
5355: if ($block =~ /^firstaccess____(.+)$/) {
5356: my $item = $1;
5357: my $type = 'map';
5358: my $timersymb = $item;
5359: if ($item eq 'course') {
5360: $type = 'course';
5361: } elsif ($item =~ /___\d+___/) {
5362: $type = 'resource';
5363: } else {
5364: $timersymb = &Apache::lonnet::symbread($item);
5365: }
5366: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5367: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5368: $triggered{$block} = {
5369: start => $start,
5370: end => $end,
5371: type => $type,
5372: };
5373: }
5374: }
5375: } else {
5376: foreach my $block (keys(%commblocks)) {
5377: if ($block =~ m/^(\d+)____(\d+)$/) {
5378: my ($start,$end) = ($1,$2);
5379: if ($start <= time && $end >= time) {
5380: if (ref($commblocks{$block}) eq 'HASH') {
5381: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5382: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5383: unless(grep(/^\Q$block\E$/,@blockers)) {
5384: push(@blockers,$block);
5385: }
5386: }
5387: }
5388: }
5389: }
5390: } elsif ($block =~ /^firstaccess____(.+)$/) {
5391: my $item = $1;
5392: my $timersymb = $item;
5393: my $type = 'map';
5394: if ($item eq 'course') {
5395: $type = 'course';
5396: } elsif ($item =~ /___\d+___/) {
5397: $type = 'resource';
5398: } else {
5399: $timersymb = &Apache::lonnet::symbread($item);
5400: }
5401: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5402: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5403: if ($start && $end) {
5404: if (($start <= time) && ($end >= time)) {
5405: if (ref($commblocks{$block}) eq 'HASH') {
5406: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5407: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5408: unless(grep(/^\Q$block\E$/,@blockers)) {
5409: push(@blockers,$block);
5410: $triggered{$block} = {
5411: start => $start,
5412: end => $end,
5413: type => $type,
5414: };
5415: }
5416: }
5417: }
5418: }
5419: }
5420: }
5421: }
5422: }
5423: }
5424: foreach my $blocker (@blockers) {
5425: my ($staff_name,$staff_dom,$title,$blocks) =
5426: &parse_block_record($commblocks{$blocker});
5427: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5428: my ($start,$end,$triggertype);
5429: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5430: ($start,$end) = ($1,$2);
5431: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5432: $start = $triggered{$blocker}{'start'};
5433: $end = $triggered{$blocker}{'end'};
5434: $triggertype = $triggered{$blocker}{'type'};
5435: }
5436: if ($start) {
5437: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5438: if ($triggertype) {
5439: push(@{$$setters{$course}{'triggers'}},$triggertype);
5440: } else {
5441: push(@{$$setters{$course}{'triggers'}},0);
5442: }
5443: if ( ($startblock == 0) || ($startblock > $start) ) {
5444: $startblock = $start;
5445: if ($triggertype) {
5446: $triggerblock = $blocker;
5447: }
5448: }
5449: if ( ($endblock == 0) || ($endblock < $end) ) {
5450: $endblock = $end;
5451: if ($triggertype) {
5452: $triggerblock = $blocker;
5453: }
5454: }
5455: }
5456: }
5457: return ($startblock,$endblock,$triggerblock);
5458: }
5459:
5460: sub parse_block_record {
5461: my ($record) = @_;
5462: my ($setuname,$setudom,$title,$blocks);
5463: if (ref($record) eq 'HASH') {
5464: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5465: $title = &unescape($record->{'event'});
5466: $blocks = $record->{'blocks'};
5467: } else {
5468: my @data = split(/:/,$record,3);
5469: if (scalar(@data) eq 2) {
5470: $title = $data[1];
5471: ($setuname,$setudom) = split(/@/,$data[0]);
5472: } else {
5473: ($setuname,$setudom,$title) = @data;
5474: }
5475: $blocks = { 'com' => 'on' };
5476: }
5477: return ($setuname,$setudom,$title,$blocks);
5478: }
5479:
5480: sub blocking_status {
5481: my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5482: my %setters;
5483:
5484: # check for active blocking
5485: if ($clientip eq '') {
5486: $clientip = &Apache::lonnet::get_requestor_ip();
5487: }
5488: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
5489: &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
5490: my $blocked = 0;
5491: if (($startblock && $endblock) || ($by_ip)) {
5492: $blocked = 1;
5493: }
5494:
5495: # caller just wants to know whether a block is active
5496: if (!wantarray) { return $blocked; }
5497:
5498: # build a link to a popup window containing the details
5499: my $querystring = "?activity=$activity";
5500: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
5501: if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
5502: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5503: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5504: } elsif ($activity eq 'docs') {
5505: my $showurl = &Apache::lonenc::check_encrypt($url);
5506: $querystring .= '&url='.&HTML::Entities::encode($showurl,'\'&"<>');
5507: if ($symb) {
5508: my $showsymb = &Apache::lonenc::check_encrypt($symb);
5509: $querystring .= '&symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
5510: }
5511: }
5512:
5513: my $output .= <<'END_MYBLOCK';
5514: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5515: var options = "width=" + w + ",height=" + h + ",";
5516: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5517: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5518: var newWin = window.open(url, wdwName, options);
5519: newWin.focus();
5520: }
5521: END_MYBLOCK
5522:
5523: $output = Apache::lonhtmlcommon::scripttag($output);
5524:
5525: my $popupUrl = "/adm/blockingstatus/$querystring";
5526: my $text = &mt('Communication Blocked');
5527: my $class = 'LC_comblock';
5528: if ($activity eq 'docs') {
5529: $text = &mt('Content Access Blocked');
5530: $class = '';
5531: } elsif ($activity eq 'printout') {
5532: $text = &mt('Printing Blocked');
5533: } elsif ($activity eq 'passwd') {
5534: $text = &mt('Password Changing Blocked');
5535: } elsif ($activity eq 'grades') {
5536: $text = &mt('Gradebook Blocked');
5537: } elsif ($activity eq 'search') {
5538: $text = &mt('Search Blocked');
5539: } elsif ($activity eq 'alert') {
5540: $text = &mt('Checking Critical Messages Blocked');
5541: } elsif ($activity eq 'reinit') {
5542: $text = &mt('Checking Course Update Blocked');
5543: } elsif ($activity eq 'about') {
5544: $text = &mt('Access to User Information Pages Blocked');
5545: } elsif ($activity eq 'wishlist') {
5546: $text = &mt('Access to Stored Links Blocked');
5547: } elsif ($activity eq 'annotate') {
5548: $text = &mt('Access to Annotations Blocked');
5549: }
5550: $output .= <<"END_BLOCK";
5551: <div class='$class'>
5552: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5553: title='$text'>
5554: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5555: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5556: title='$text'>$text</a>
5557: </div>
5558:
5559: END_BLOCK
5560:
5561: return ($blocked, $output);
5562: }
5563:
5564: ###############################################
5565:
5566: sub check_ip_acc {
5567: my ($acc,$clientip)=@_;
5568: &Apache::lonxml::debug("acc is $acc");
5569: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5570: return 1;
5571: }
5572: my $allowed=0;
5573: my $ip;
5574: if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
5575: ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
5576: $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
5577: } else {
5578: my $remote_ip = &Apache::lonnet::get_requestor_ip();
5579: $ip = $remote_ip || $env{'request.host'} || $clientip;
5580: }
5581:
5582: my $name;
5583: my %access = (
5584: allowfrom => 1,
5585: denyfrom => 0,
5586: );
5587: my @allows;
5588: my @denies;
5589: foreach my $item (split(',',$acc)) {
5590: $item =~ s/^\s*//;
5591: $item =~ s/\s*$//;
5592: if ($item =~ /^\!(.+)$/) {
5593: push(@denies,$1);
5594: } else {
5595: push(@allows,$item);
5596: }
5597: }
5598: my $numdenies = scalar(@denies);
5599: my $numallows = scalar(@allows);
5600: my $count = 0;
5601: foreach my $pattern (@denies,@allows) {
5602: $count ++;
5603: my $acctype = 'allowfrom';
5604: if ($count <= $numdenies) {
5605: $acctype = 'denyfrom';
5606: }
5607: if ($pattern =~ /\*$/) {
5608: #35.8.*
5609: $pattern=~s/\*//;
5610: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5611: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5612: #35.8.3.[34-56]
5613: my $low=$2;
5614: my $high=$3;
5615: $pattern=$1;
5616: if ($ip =~ /^\Q$pattern\E/) {
5617: my $last=(split(/\./,$ip))[3];
5618: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5619: }
5620: } elsif ($pattern =~ /^\*/) {
5621: #*.msu.edu
5622: $pattern=~s/\*//;
5623: if (!defined($name)) {
5624: use Socket;
5625: my $netaddr=inet_aton($ip);
5626: ($name)=gethostbyaddr($netaddr,AF_INET);
5627: }
5628: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5629: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5630: #127.0.0.1
5631: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5632: } else {
5633: #some.name.com
5634: if (!defined($name)) {
5635: use Socket;
5636: my $netaddr=inet_aton($ip);
5637: ($name)=gethostbyaddr($netaddr,AF_INET);
5638: }
5639: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5640: }
5641: if ($allowed =~ /^(0|1)$/) { last; }
5642: }
5643: if ($allowed eq '') {
5644: if ($numdenies && !$numallows) {
5645: $allowed = 1;
5646: } else {
5647: $allowed = 0;
5648: }
5649: }
5650: return $allowed;
5651: }
5652:
5653: ###############################################
5654:
5655: =pod
5656:
5657: =head1 Domain Template Functions
5658:
5659: =over 4
5660:
5661: =item * &determinedomain()
5662:
5663: Inputs: $domain (usually will be undef)
5664:
5665: Returns: Determines which domain should be used for designs
5666:
5667: =cut
5668:
5669: ###############################################
5670: sub determinedomain {
5671: my $domain=shift;
5672: if (! $domain) {
5673: # Determine domain if we have not been given one
5674: $domain = &Apache::lonnet::default_login_domain();
5675: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5676: if ($env{'request.role.domain'}) {
5677: $domain=$env{'request.role.domain'};
5678: }
5679: }
5680: return $domain;
5681: }
5682: ###############################################
5683:
5684: sub devalidate_domconfig_cache {
5685: my ($udom)=@_;
5686: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5687: }
5688:
5689: # ---------------------- Get domain configuration for a domain
5690: sub get_domainconf {
5691: my ($udom) = @_;
5692: my $cachetime=1800;
5693: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5694: if (defined($cached)) { return %{$result}; }
5695:
5696: my %domconfig = &Apache::lonnet::get_dom('configuration',
5697: ['login','rolecolors','autoenroll'],$udom);
5698: my (%designhash,%legacy);
5699: if (keys(%domconfig) > 0) {
5700: if (ref($domconfig{'login'}) eq 'HASH') {
5701: if (keys(%{$domconfig{'login'}})) {
5702: foreach my $key (keys(%{$domconfig{'login'}})) {
5703: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5704: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5705: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5706: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5707: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5708: if ($key eq 'loginvia') {
5709: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5710: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5711: $designhash{$udom.'.login.loginvia'} = $server;
5712: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5713: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5714: } else {
5715: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5716: }
5717: }
5718: } elsif ($key eq 'headtag') {
5719: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5720: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5721: }
5722: }
5723: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5724: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5725: }
5726: }
5727: }
5728: }
5729: } elsif ($key eq 'saml') {
5730: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5731: foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
5732: if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
5733: $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
5734: foreach my $item ('text','img','alt','url','title','window','notsso') {
5735: $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
5736: }
5737: }
5738: }
5739: }
5740: } else {
5741: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5742: $designhash{$udom.'.login.'.$key.'_'.$img} =
5743: $domconfig{'login'}{$key}{$img};
5744: }
5745: }
5746: } else {
5747: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5748: }
5749: }
5750: } else {
5751: $legacy{'login'} = 1;
5752: }
5753: } else {
5754: $legacy{'login'} = 1;
5755: }
5756: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5757: if (keys(%{$domconfig{'rolecolors'}})) {
5758: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5759: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5760: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5761: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5762: }
5763: }
5764: }
5765: } else {
5766: $legacy{'rolecolors'} = 1;
5767: }
5768: } else {
5769: $legacy{'rolecolors'} = 1;
5770: }
5771: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5772: if ($domconfig{'autoenroll'}{'co-owners'}) {
5773: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5774: }
5775: }
5776: if (keys(%legacy) > 0) {
5777: my %legacyhash = &get_legacy_domconf($udom);
5778: foreach my $item (keys(%legacyhash)) {
5779: if ($item =~ /^\Q$udom\E\.login/) {
5780: if ($legacy{'login'}) {
5781: $designhash{$item} = $legacyhash{$item};
5782: }
5783: } else {
5784: if ($legacy{'rolecolors'}) {
5785: $designhash{$item} = $legacyhash{$item};
5786: }
5787: }
5788: }
5789: }
5790: } else {
5791: %designhash = &get_legacy_domconf($udom);
5792: }
5793: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5794: $cachetime);
5795: return %designhash;
5796: }
5797:
5798: sub get_legacy_domconf {
5799: my ($udom) = @_;
5800: my %legacyhash;
5801: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5802: my $designfile = $designdir.'/'.$udom.'.tab';
5803: if (-e $designfile) {
5804: if ( open (my $fh,'<',$designfile) ) {
5805: while (my $line = <$fh>) {
5806: next if ($line =~ /^\#/);
5807: chomp($line);
5808: my ($key,$val)=(split(/\=/,$line));
5809: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5810: }
5811: close($fh);
5812: }
5813: }
5814: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5815: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5816: }
5817: return %legacyhash;
5818: }
5819:
5820: =pod
5821:
5822: =item * &domainlogo()
5823:
5824: Inputs: $domain (usually will be undef)
5825:
5826: Returns: A link to a domain logo, if the domain logo exists.
5827: If the domain logo does not exist, a description of the domain.
5828:
5829: =cut
5830:
5831: ###############################################
5832: sub domainlogo {
5833: my $domain = &determinedomain(shift);
5834: my %designhash = &get_domainconf($domain);
5835: # See if there is a logo
5836: if ($designhash{$domain.'.login.domlogo'} ne '') {
5837: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5838: if ($imgsrc =~ m{^/(adm|res)/}) {
5839: if ($imgsrc =~ m{^/res/}) {
5840: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5841: &Apache::lonnet::repcopy($local_name);
5842: }
5843: $imgsrc = &lonhttpdurl($imgsrc);
5844: }
5845: my $alttext = $domain;
5846: if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
5847: $alttext = $designhash{$domain.'.login.alttext_domlogo'};
5848: }
5849: return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
5850: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5851: return &Apache::lonnet::domain($domain,'description');
5852: } else {
5853: return '';
5854: }
5855: }
5856: ##############################################
5857:
5858: =pod
5859:
5860: =item * &designparm()
5861:
5862: Inputs: $which parameter; $domain (usually will be undef)
5863:
5864: Returns: value of designparamter $which
5865:
5866: =cut
5867:
5868:
5869: ##############################################
5870: sub designparm {
5871: my ($which,$domain)=@_;
5872: if (exists($env{'environment.color.'.$which})) {
5873: return $env{'environment.color.'.$which};
5874: }
5875: $domain=&determinedomain($domain);
5876: my %domdesign;
5877: unless ($domain eq 'public') {
5878: %domdesign = &get_domainconf($domain);
5879: }
5880: my $output;
5881: if ($domdesign{$domain.'.'.$which} ne '') {
5882: $output = $domdesign{$domain.'.'.$which};
5883: } else {
5884: $output = $defaultdesign{$which};
5885: }
5886: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5887: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5888: if ($output =~ m{^/(adm|res)/}) {
5889: if ($output =~ m{^/res/}) {
5890: my $local_name = &Apache::lonnet::filelocation('',$output);
5891: &Apache::lonnet::repcopy($local_name);
5892: }
5893: $output = &lonhttpdurl($output);
5894: }
5895: }
5896: return $output;
5897: }
5898:
5899: ##############################################
5900: =pod
5901:
5902: =item * &authorspace()
5903:
5904: Inputs: $url (usually will be undef).
5905:
5906: Returns: Path to Authoring Space containing the resource or
5907: directory being viewed (or for which action is being taken).
5908: If $url is provided, and begins /priv/<domain>/<uname>
5909: the path will be that portion of the $context argument.
5910: Otherwise the path will be for the author space of the current
5911: user when the current role is author, or for that of the
5912: co-author/assistant co-author space when the current role
5913: is co-author or assistant co-author.
5914:
5915: =cut
5916:
5917: sub authorspace {
5918: my ($url) = @_;
5919: if ($url ne '') {
5920: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5921: return $1;
5922: }
5923: }
5924: my $caname = '';
5925: my $cadom = '';
5926: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5927: ($cadom,$caname) =
5928: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5929: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5930: $caname = $env{'user.name'};
5931: $cadom = $env{'user.domain'};
5932: }
5933: if (($caname ne '') && ($cadom ne '')) {
5934: return "/priv/$cadom/$caname/";
5935: }
5936: return;
5937: }
5938:
5939: ##############################################
5940: =pod
5941:
5942: =item * &head_subbox()
5943:
5944: Inputs: $content (contains HTML code with page functions, etc.)
5945:
5946: Returns: HTML div with $content
5947: To be included in page header
5948:
5949: =cut
5950:
5951: sub head_subbox {
5952: my ($content)=@_;
5953: my $output =
5954: '<div class="LC_head_subbox">'
5955: .$content
5956: .'</div>'
5957: }
5958:
5959: ##############################################
5960: =pod
5961:
5962: =item * &CSTR_pageheader()
5963:
5964: Input: (optional) filename from which breadcrumb trail is built.
5965: In most cases no input as needed, as $env{'request.filename'}
5966: is appropriate for use in building the breadcrumb trail.
5967: frameset flag
5968: If page header is being requested for use in a frameset, then
5969: the second (option) argument -- frameset will be true, and
5970: the target attribute set for links should be target="_parent".
5971:
5972: Returns: HTML div with CSTR path and recent box
5973: To be included on Authoring Space pages
5974:
5975: =cut
5976:
5977: sub CSTR_pageheader {
5978: my ($trailfile,$frameset) = @_;
5979: if ($trailfile eq '') {
5980: $trailfile = $env{'request.filename'};
5981: }
5982:
5983: # this is for resources; directories have customtitle, and crumbs
5984: # and select recent are created in lonpubdir.pm
5985:
5986: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5987: my ($udom,$uname,$thisdisfn)=
5988: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5989: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5990: $formaction =~ s{/+}{/}g;
5991:
5992: my $parentpath = '';
5993: my $lastitem = '';
5994: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5995: $parentpath = $1;
5996: $lastitem = $2;
5997: } else {
5998: $lastitem = $thisdisfn;
5999: }
6000:
6001: my ($target,$crumbtarget) = (' target="_top"','_top');
6002: if ($frameset) {
6003: $target = ' target="_parent"';
6004: $crumbtarget = '_parent';
6005: } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
6006: $target = '';
6007: $crumbtarget = '';
6008: } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
6009: $target = ' target="'.$env{'request.deeplink.target'}.'"';
6010: $crumbtarget = $env{'request.deeplink.target'};
6011: }
6012:
6013: my $output =
6014: '<div>'
6015: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
6016: .'<b>'.&mt('Authoring Space:').'</b> '
6017: .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
6018: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
6019:
6020: if ($lastitem) {
6021: $output .=
6022: '<span class="LC_filename">'
6023: .$lastitem
6024: .'</span>';
6025: }
6026: $output .=
6027: '<br />'
6028: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
6029: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
6030: .'</form>'
6031: .&Apache::lonmenu::constspaceform($frameset)
6032: .'</div>';
6033:
6034: return $output;
6035: }
6036:
6037: ##############################################
6038: =pod
6039:
6040: =item * &nocodemirror()
6041:
6042: Input: None
6043:
6044: Returns: 1 if CodeMirror is deactivated based on
6045: user's preference, or domain default,
6046: if user indicated use of default.
6047:
6048: =cut
6049:
6050: sub nocodemirror {
6051: my $nocodem = $env{'environment.nocodemirror'};
6052: unless ($nocodem) {
6053: my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
6054: if ($domdefs{'nocodemirror'}) {
6055: $nocodem = 'yes';
6056: }
6057: }
6058: if ($nocodem eq 'yes') {
6059: return 1;
6060: }
6061: return;
6062: }
6063:
6064: ##############################################
6065: =pod
6066:
6067: =item * &permitted_editors()
6068:
6069: Input: $uri (optional)
6070:
6071: Returns: %editors hash in which keys are editors
6072: permitted in current Authoring Space.
6073: Value for each key is 1. Possible keys
6074: are: edit, xml, and daxe. If no specific
6075: set of editors has been set for the Author
6076: who owns the Authoring Space, then the
6077: domain default will be used. If no domain
6078: default has been set, then the keys will be
6079: edit and xml.
6080:
6081: =cut
6082:
6083: sub permitted_editors {
6084: my ($uri) = @_;
6085: my ($is_author,$is_coauthor,$auname,$audom,%editors);
6086: if ($env{'request.role'} =~ m{^au\./}) {
6087: $is_author = 1;
6088: } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
6089: ($audom,$auname) = ($1,$2);
6090: if (($audom ne '') && ($auname ne '')) {
6091: if (($env{'user.domain'} eq $audom) &&
6092: ($env{'user.name'} eq $auname)) {
6093: $is_author = 1;
6094: } else {
6095: $is_coauthor = 1;
6096: }
6097: }
6098: } elsif ($env{'request.course.id'}) {
6099: if ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
6100: ($audom,$auname) = ($1,$2);
6101: } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
6102: ($audom,$auname) = ($1,$2);
6103: } elsif (($uri eq '/daxesave') &&
6104: ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
6105: ($audom,$auname) = ($1,$2);
6106: }
6107: if (($audom ne '') && ($auname ne '')) {
6108: if (($env{'user.domain'} eq $audom) &&
6109: ($env{'user.name'} eq $auname)) {
6110: $is_author = 1;
6111: } else {
6112: $is_coauthor = 1;
6113: }
6114: }
6115: }
6116: if ($is_author) {
6117: if (exists($env{'environment.editors'})) {
6118: map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
6119: } else {
6120: %editors = ( edit => 1,
6121: xml => 1,
6122: );
6123: }
6124: } elsif ($is_coauthor) {
6125: if (exists($env{"environment.internal.editors./$audom/$auname"})) {
6126: map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
6127: } else {
6128: %editors = ( edit => 1,
6129: xml => 1,
6130: );
6131: }
6132: } else {
6133: %editors = ( edit => 1,
6134: xml => 1,
6135: );
6136: }
6137: return %editors;
6138: }
6139:
6140: ###############################################
6141: ###############################################
6142:
6143: =pod
6144:
6145: =back
6146:
6147: =head1 HTML Helpers
6148:
6149: =over 4
6150:
6151: =item * &bodytag()
6152:
6153: Returns a uniform header for LON-CAPA web pages.
6154:
6155: Inputs:
6156:
6157: =over 4
6158:
6159: =item * $title, A title to be displayed on the page.
6160:
6161: =item * $function, the current role (can be undef).
6162:
6163: =item * $addentries, extra parameters for the <body> tag.
6164:
6165: =item * $bodyonly, if defined, only return the <body> tag.
6166:
6167: =item * $domain, if defined, force a given domain.
6168:
6169: =item * $forcereg, if page should register as content page (relevant for
6170: text interface only)
6171:
6172: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
6173: navigational links
6174:
6175: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
6176:
6177: =item * $no_inline_link, if true and in remote mode, don't show the
6178: 'Switch To Inline Menu' link
6179:
6180: =item * $args, optional argument valid values are
6181: no_auto_mt_title -> prevents &mt()ing the title arg
6182: use_absolute -> for external resource or syllabus, this will
6183: contain https://<hostname> if server uses
6184: https (as per hosts.tab), but request is for http
6185: hostname -> hostname, from $r->hostname().
6186:
6187: =item * $advtoolsref, optional argument, ref to an array containing
6188: inlineremote items to be added in "Functions" menu below
6189: breadcrumbs.
6190:
6191: =item * $ltiscope, optional argument, will be one of: resource, map or
6192: course, if LON-CAPA is in LTI Provider context. Value is
6193: the scope of use, i.e., launch was for access to a single, a map
6194: or the entire course.
6195:
6196: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
6197: context, this will contain the URL for the landing item in
6198: the course, after launch from an LTI Consumer
6199:
6200: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
6201: context, this will contain a reference to hash of items
6202: to be included in the page header and/or inline menu.
6203:
6204: =item * $menucoll, optional argument, if specific menu collection is in
6205: effect, either set as the default for the course, or set for
6206: the deeplink paramater for $env{'request.deeplink.login'}
6207: then $menucoll will be the number of that collection.
6208:
6209: =item * $menuref, optional argument, reference to a hash, containing the
6210: menu options included for the menu in effect, based on the
6211: configuration for the numbered menu collection in use.
6212:
6213: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
6214: within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
6215: if so, $showncrumbsref is set there to 1, and will propagate back
6216: via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
6217: being called a second time.
6218:
6219: =back
6220:
6221: Returns: A uniform header for LON-CAPA web pages.
6222: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
6223: If $bodyonly is undef or zero, an html string containing a <body> tag and
6224: other decorations will be returned.
6225:
6226: =cut
6227:
6228: sub bodytag {
6229: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
6230: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
6231: $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
6232:
6233: my $public;
6234: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
6235: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
6236: $public = 1;
6237: }
6238: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6239: my $httphost = $args->{'use_absolute'};
6240: my $hostname = $args->{'hostname'};
6241:
6242: $function = &get_users_function() if (!$function);
6243: my $img = &designparm($function.'.img',$domain);
6244: my $font = &designparm($function.'.font',$domain);
6245: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
6246:
6247: my %design = ( 'style' => 'margin-top: 0',
6248: 'bgcolor' => $pgbg,
6249: 'text' => $font,
6250: 'alink' => &designparm($function.'.alink',$domain),
6251: 'vlink' => &designparm($function.'.vlink',$domain),
6252: 'link' => &designparm($function.'.link',$domain),);
6253: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
6254:
6255: # role and realm
6256: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
6257: if ($realm) {
6258: $realm = '/'.$realm;
6259: }
6260: if ($role eq 'ca') {
6261: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
6262: $realm = &plainname($rname,$rdom);
6263: }
6264: # realm
6265: my ($cid,$sec);
6266: if ($env{'request.course.id'}) {
6267: $cid = $env{'request.course.id'};
6268: if ($env{'request.course.sec'}) {
6269: $sec = $env{'request.course.sec'};
6270: }
6271: } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
6272: if (&Apache::lonnet::is_course($1,$2)) {
6273: $cid = $1.'_'.$2;
6274: $sec = $3;
6275: }
6276: }
6277: if ($cid) {
6278: if ($env{'request.role'} !~ /^cr/) {
6279: $role = &Apache::lonnet::plaintext($role,&course_type());
6280: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
6281: if ($env{'request.role.desc'}) {
6282: $role = $env{'request.role.desc'};
6283: } else {
6284: $role = &mt('Helpdesk[_1]',' '.$2);
6285: }
6286: } else {
6287: $role = (split(/\//,$role,4))[-1];
6288: }
6289: if ($sec) {
6290: $role .= (' 'x2).'- '.&mt('section:').' '.$sec;
6291: }
6292: $realm = $env{'course.'.$cid.'.description'};
6293: } else {
6294: $role = &Apache::lonnet::plaintext($role);
6295: }
6296:
6297: if (!$realm) { $realm=' '; }
6298:
6299: my $extra_body_attr = &make_attr_string($forcereg,\%design);
6300:
6301: # construct main body tag
6302: my $bodytag = "<body $extra_body_attr>".
6303: &Apache::lontexconvert::init_math_support();
6304:
6305: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6306:
6307: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
6308: return $bodytag;
6309: }
6310:
6311: if ($public) {
6312: undef($role);
6313: }
6314:
6315: my $showcrstitle = 1;
6316: if (($cid) && ($env{'request.lti.login'})) {
6317: if (ref($ltimenu) eq 'HASH') {
6318: unless ($ltimenu->{'role'}) {
6319: undef($role);
6320: }
6321: unless ($ltimenu->{'coursetitle'}) {
6322: $realm=' ';
6323: $showcrstitle = 0;
6324: }
6325: }
6326: } elsif (($cid) && ($menucoll)) {
6327: if (ref($menuref) eq 'HASH') {
6328: unless ($menuref->{'role'}) {
6329: undef($role);
6330: }
6331: unless ($menuref->{'crs'}) {
6332: $realm=' ';
6333: $showcrstitle = 0;
6334: }
6335: }
6336: }
6337:
6338: my $titleinfo = '<h1>'.$title.'</h1>';
6339: #
6340: # Extra info if you are the DC
6341: my $dc_info = '';
6342: if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
6343: (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
6344: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
6345: $dc_info =~ s/\s+$//;
6346: }
6347:
6348: my $crstype;
6349: if ($cid) {
6350: $crstype = $env{'course.'.$cid.'.type'};
6351: } elsif ($args->{'crstype'}) {
6352: $crstype = $args->{'crstype'};
6353: }
6354:
6355: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
6356:
6357: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
6358:
6359:
6360:
6361: my $funclist;
6362: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
6363: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
6364: Apache::lonmenu::serverform();
6365: my $forbodytag;
6366: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6367: $forcereg,$args->{'group'},
6368: $args->{'bread_crumbs'},
6369: $advtoolsref,'','',\$forbodytag);
6370: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6371: $funclist = $forbodytag;
6372: }
6373: } else {
6374:
6375: # if ($env{'request.state'} eq 'construct') {
6376: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
6377: # }
6378:
6379: $bodytag .= Apache::lonhtmlcommon::scripttag(
6380: Apache::lonmenu::utilityfunctions($httphost), 'start');
6381:
6382: if ($args->{'collapsible_header'} ne '') {
6383: my $alttext = &mt('menu state: collapsed');
6384: my $tooltip = &mt('display standard menus');
6385: $bodytag .= <<"END";
6386: <div id="LC_expandingContainer" style="display:inline;">
6387: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
6388: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/collapsed.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
6389: <div class="LC_menus_content hidden">
6390: END
6391: }
6392: unless ($args->{'no_primary_menu'}) {
6393: my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
6394: $args->{'links_disabled'},
6395: $args->{'links_target'},
6396: $args->{'collapsible_header'});
6397: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
6398: if ($dc_info) {
6399: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
6400: }
6401: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
6402: <em>$realm</em> $dc_info</div>|;
6403: return $bodytag;
6404: }
6405:
6406: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
6407: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
6408: }
6409:
6410: $bodytag .= $right;
6411:
6412: if ($dc_info) {
6413: $dc_info = &dc_courseid_toggle($dc_info);
6414: }
6415: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
6416: }
6417:
6418: #if directed to not display the secondary menu, don't.
6419: if ($args->{'no_secondary_menu'}) {
6420: return $bodytag;
6421: }
6422: #don't show menus for public users
6423: if (!$public){
6424: unless ($args->{'no_inline_menu'}) {
6425: $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
6426: $args->{'no_primary_menu'},
6427: $menucoll,$menuref,
6428: $args->{'links_disabled'},
6429: $args->{'links_target'});
6430: }
6431: $bodytag .= Apache::lonmenu::serverform();
6432: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6433: if ($env{'request.state'} eq 'construct') {
6434: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
6435: $args->{'bread_crumbs'},'','',$hostname,
6436: $ltiscope,$ltiuri,$showncrumbsref);
6437: } elsif ($forcereg) {
6438: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
6439: $args->{'group'},$args->{'hide_buttons'},
6440: $hostname,$ltiscope,$ltiuri,$showncrumbsref);
6441: } else {
6442: my $forbodytag;
6443: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6444: $forcereg,$args->{'group'},
6445: $args->{'bread_crumbs'},
6446: $advtoolsref,'',$hostname,
6447: \$forbodytag);
6448: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6449: $bodytag .= $forbodytag;
6450: }
6451: }
6452: }else{
6453: # this is to seperate menu from content when there's no secondary
6454: # menu. Especially needed for public accessible ressources.
6455: $bodytag .= '<hr style="clear:both" />';
6456: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6457: }
6458: if ($args->{'collapsible_header'} ne '') {
6459: $bodytag .= $args->{'collapsible_header'}.
6460: '<div id="LC_collapsible_separator"></div>'.
6461: '</div></div>';
6462: }
6463: return $bodytag;
6464: }
6465:
6466: #
6467: # Top frame rendering, Remote is up
6468: #
6469:
6470: my $imgsrc = $img;
6471: if ($img =~ /^\/adm/) {
6472: $imgsrc = &lonhttpdurl($img);
6473: }
6474: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
6475:
6476: my $help=($no_inline_link?''
6477: :&Apache::loncommon::top_nav_help('Help'));
6478:
6479: # Explicit link to get inline menu
6480: my $menu= ($no_inline_link?''
6481: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
6482:
6483: if ($dc_info) {
6484: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
6485: }
6486:
6487: my $name = &plainname($env{'user.name'},$env{'user.domain'});
6488: unless ($public) {
6489: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
6490: undef,'LC_menubuttons_link');
6491: }
6492:
6493: unless ($env{'form.inhibitmenu'}) {
6494: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
6495: <ol class="LC_primary_menu LC_floatright LC_right">
6496: <li>$help</li>
6497: <li>$menu</li>
6498: </ol><div id="LC_realm"> $realm $dc_info</div>|;
6499: }
6500: if ($env{'request.state'} eq 'construct') {
6501: if (!$public){
6502: if ($env{'request.state'} eq 'construct') {
6503: $funclist = &Apache::lonhtmlcommon::scripttag(
6504: &Apache::lonmenu::utilityfunctions($httphost), 'start').
6505: &Apache::lonhtmlcommon::scripttag('','end').
6506: &Apache::lonmenu::innerregister($forcereg,
6507: $args->{'bread_crumbs'});
6508: }
6509: }
6510: }
6511: return $bodytag."\n".$funclist;
6512: }
6513:
6514: sub dc_courseid_toggle {
6515: my ($dc_info) = @_;
6516: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
6517: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
6518: &mt('(More ...)').'</a></span>'.
6519: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
6520: }
6521:
6522: sub make_attr_string {
6523: my ($register,$attr_ref) = @_;
6524:
6525: if ($attr_ref && !ref($attr_ref)) {
6526: die("addentries Must be a hash ref ".
6527: join(':',caller(1))." ".
6528: join(':',caller(0))." ");
6529: }
6530:
6531: if ($register) {
6532: my ($on_load,$on_unload);
6533: foreach my $key (keys(%{$attr_ref})) {
6534: if (lc($key) eq 'onload') {
6535: $on_load.=$attr_ref->{$key}.';';
6536: delete($attr_ref->{$key});
6537:
6538: } elsif (lc($key) eq 'onunload') {
6539: $on_unload.=$attr_ref->{$key}.';';
6540: delete($attr_ref->{$key});
6541: }
6542: }
6543: if ($env{'environment.remote'} eq 'on') {
6544: $attr_ref->{'onload'} =
6545: &Apache::lonmenu::loadevents(). $on_load;
6546: $attr_ref->{'onunload'}=
6547: &Apache::lonmenu::unloadevents().$on_unload;
6548: } else {
6549: $attr_ref->{'onload'} = $on_load;
6550: $attr_ref->{'onunload'}= $on_unload;
6551: }
6552: }
6553:
6554: my $attr_string;
6555: foreach my $attr (sort(keys(%$attr_ref))) {
6556: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6557: }
6558: return $attr_string;
6559: }
6560:
6561:
6562: ###############################################
6563: ###############################################
6564:
6565: =pod
6566:
6567: =item * &endbodytag()
6568:
6569: Returns a uniform footer for LON-CAPA web pages.
6570:
6571: Inputs: 1 - optional reference to an args hash
6572: If in the hash, key for noredirectlink has a value which evaluates to true,
6573: a 'Continue' link is not displayed if the page contains an
6574: internal redirect in the <head></head> section,
6575: i.e., $env{'internal.head.redirect'} exists
6576:
6577: =cut
6578:
6579: sub endbodytag {
6580: my ($args) = @_;
6581: my $endbodytag;
6582: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6583: $endbodytag='</body>';
6584: }
6585: if ( exists( $env{'internal.head.redirect'} ) ) {
6586: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6587: my ($endbodyjs,$idattr);
6588: if ($env{'internal.head.to_opener'}) {
6589: my $linkid = 'LC_continue_link';
6590: $idattr = ' id="'.$linkid.'"';
6591: my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
6592: $endbodyjs=<<ENDJS;
6593: <script type="text/javascript">
6594: // <![CDATA[
6595: function ebFunction(evt) {
6596: evt.preventDefault();
6597: var dest = '$redirect_for_js';
6598: if (window.opener != null && !window.opener.closed) {
6599: window.opener.location.href=dest;
6600: window.close();
6601: } else {
6602: window.location.href=dest;
6603: }
6604: return false;
6605: }
6606:
6607: \$(document).ready(function () {
6608: if (document.getElementById('$linkid')) {
6609: var clickelem = document.getElementById('$linkid');
6610: clickelem.addEventListener('click',ebFunction,false);
6611: }
6612: });
6613: // ]]>
6614: </script>
6615: ENDJS
6616: }
6617: $endbodytag=
6618: "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
6619: &mt('Continue').'</a>'.
6620: $endbodytag;
6621: }
6622: }
6623: if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
6624: $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
6625: }
6626: return $endbodytag;
6627: }
6628:
6629: =pod
6630:
6631: =item * &standard_css()
6632:
6633: Returns a style sheet
6634:
6635: Inputs: (all optional)
6636: domain -> force to color decorate a page for a specific
6637: domain
6638: function -> force usage of a specific rolish color scheme
6639: bgcolor -> override the default page bgcolor
6640:
6641: =cut
6642:
6643: sub standard_css {
6644: my ($function,$domain,$bgcolor) = @_;
6645: $function = &get_users_function() if (!$function);
6646: my $img = &designparm($function.'.img', $domain);
6647: my $tabbg = &designparm($function.'.tabbg', $domain);
6648: my $font = &designparm($function.'.font', $domain);
6649: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6650: #second colour for later usage
6651: my $sidebg = &designparm($function.'.sidebg',$domain);
6652: my $pgbg_or_bgcolor =
6653: $bgcolor ||
6654: &designparm($function.'.pgbg', $domain);
6655: my $pgbg = &designparm($function.'.pgbg', $domain);
6656: my $alink = &designparm($function.'.alink', $domain);
6657: my $vlink = &designparm($function.'.vlink', $domain);
6658: my $link = &designparm($function.'.link', $domain);
6659:
6660: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6661: my $mono = 'monospace';
6662: my $data_table_head = $sidebg;
6663: my $data_table_light = '#FAFAFA';
6664: my $data_table_dark = '#E0E0E0';
6665: my $data_table_darker = '#CCCCCC';
6666: my $data_table_highlight = '#FFFF00';
6667: my $mail_new = '#FFBB77';
6668: my $mail_new_hover = '#DD9955';
6669: my $mail_read = '#BBBB77';
6670: my $mail_read_hover = '#999944';
6671: my $mail_replied = '#AAAA88';
6672: my $mail_replied_hover = '#888855';
6673: my $mail_other = '#99BBBB';
6674: my $mail_other_hover = '#669999';
6675: my $table_header = '#DDDDDD';
6676: my $feedback_link_bg = '#BBBBBB';
6677: my $lg_border_color = '#C8C8C8';
6678: my $button_hover = '#BF2317';
6679:
6680: my $border = ($env{'browser.type'} eq 'explorer' ||
6681: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6682: : '0 3px 0 4px';
6683:
6684:
6685: return <<END;
6686:
6687: /* needed for iframe to allow 100% height in FF */
6688: body, html {
6689: margin: 0;
6690: padding: 0 0.5%;
6691: height: 99%; /* to avoid scrollbars */
6692: }
6693:
6694: body {
6695: font-family: $sans;
6696: line-height:130%;
6697: font-size:0.83em;
6698: color:$font;
6699: }
6700:
6701: a:focus,
6702: a:focus img {
6703: color: red;
6704: }
6705:
6706: form, .inline {
6707: display: inline;
6708: }
6709:
6710: .LC_menus_content.shown{
6711: display: inline;
6712: }
6713:
6714: .LC_menus_content.hidden {
6715: display: none;
6716: }
6717:
6718: .LC_right {
6719: text-align:right;
6720: }
6721:
6722: .LC_middle {
6723: vertical-align:middle;
6724: }
6725:
6726: .LC_floatleft {
6727: float: left;
6728: }
6729:
6730: .LC_floatright {
6731: float: right;
6732: }
6733:
6734: .LC_400Box {
6735: width:400px;
6736: }
6737:
6738: #LC_collapsible_separator {
6739: border: 1px solid black;
6740: width: 99.9%;
6741: height: 0px;
6742: }
6743:
6744: .LC_iframecontainer {
6745: width: 98%;
6746: margin: 0;
6747: position: fixed;
6748: top: 8.5em;
6749: bottom: 0;
6750: }
6751:
6752: .LC_iframecontainer iframe{
6753: border: none;
6754: width: 100%;
6755: height: 100%;
6756: }
6757:
6758: .LC_filename {
6759: font-family: $mono;
6760: white-space:pre;
6761: font-size: 120%;
6762: }
6763:
6764: .LC_fileicon {
6765: border: none;
6766: height: 1.3em;
6767: vertical-align: text-bottom;
6768: margin-right: 0.3em;
6769: text-decoration:none;
6770: }
6771:
6772: .LC_setting {
6773: text-decoration:underline;
6774: }
6775:
6776: .LC_error {
6777: color: red;
6778: }
6779:
6780: .LC_warning {
6781: color: darkorange;
6782: }
6783:
6784: .LC_diff_removed {
6785: color: red;
6786: }
6787:
6788: .LC_info,
6789: .LC_success,
6790: .LC_diff_added {
6791: color: green;
6792: }
6793:
6794: div.LC_confirm_box {
6795: background-color: #FAFAFA;
6796: border: 1px solid $lg_border_color;
6797: margin-right: 0;
6798: padding: 5px;
6799: }
6800:
6801: div.LC_confirm_box .LC_error img,
6802: div.LC_confirm_box .LC_success img {
6803: vertical-align: middle;
6804: }
6805:
6806: .LC_maxwidth {
6807: max-width: 100%;
6808: height: auto;
6809: }
6810:
6811: .LC_textsize_mobile {
6812: \@media only screen and (max-device-width: 480px) {
6813: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
6814: }
6815: }
6816:
6817: .LC_icon {
6818: border: none;
6819: vertical-align: middle;
6820: }
6821:
6822: .LC_docs_spacer {
6823: width: 25px;
6824: height: 1px;
6825: border: none;
6826: }
6827:
6828: .LC_internal_info {
6829: color: #999999;
6830: }
6831:
6832: .LC_discussion {
6833: background: $data_table_dark;
6834: border: 1px solid black;
6835: margin: 2px;
6836: }
6837:
6838: .LC_disc_action_left {
6839: background: $sidebg;
6840: text-align: left;
6841: padding: 4px;
6842: margin: 2px;
6843: }
6844:
6845: .LC_disc_action_right {
6846: background: $sidebg;
6847: text-align: right;
6848: padding: 4px;
6849: margin: 2px;
6850: }
6851:
6852: .LC_disc_new_item {
6853: background: white;
6854: border: 2px solid red;
6855: margin: 4px;
6856: padding: 4px;
6857: }
6858:
6859: .LC_disc_old_item {
6860: background: white;
6861: margin: 4px;
6862: padding: 4px;
6863: }
6864:
6865: table.LC_pastsubmission {
6866: border: 1px solid black;
6867: margin: 2px;
6868: }
6869:
6870: table#LC_menubuttons {
6871: width: 100%;
6872: background: $pgbg;
6873: border: 2px;
6874: border-collapse: separate;
6875: padding: 0;
6876: }
6877:
6878: table#LC_title_bar a {
6879: color: $fontmenu;
6880: }
6881:
6882: table#LC_title_bar {
6883: clear: both;
6884: display: none;
6885: }
6886:
6887: table#LC_title_bar,
6888: table.LC_breadcrumbs, /* obsolete? */
6889: table#LC_title_bar.LC_with_remote {
6890: width: 100%;
6891: border-color: $pgbg;
6892: border-style: solid;
6893: border-width: $border;
6894: background: $pgbg;
6895: color: $fontmenu;
6896: border-collapse: collapse;
6897: padding: 0;
6898: margin: 0;
6899: }
6900:
6901: ul.LC_breadcrumb_tools_outerlist {
6902: margin: 0;
6903: padding: 0;
6904: position: relative;
6905: list-style: none;
6906: }
6907: ul.LC_breadcrumb_tools_outerlist li {
6908: display: inline;
6909: }
6910:
6911: .LC_breadcrumb_tools_navigation {
6912: padding: 0;
6913: margin: 0;
6914: float: left;
6915: }
6916: .LC_breadcrumb_tools_tools {
6917: padding: 0;
6918: margin: 0;
6919: float: right;
6920: }
6921:
6922: table#LC_title_bar td {
6923: background: $tabbg;
6924: }
6925:
6926: table#LC_menubuttons img {
6927: border: none;
6928: }
6929:
6930: .LC_breadcrumbs_component {
6931: float: right;
6932: margin: 0 1em;
6933: }
6934: .LC_breadcrumbs_component img {
6935: vertical-align: middle;
6936: }
6937:
6938: .LC_breadcrumbs_hoverable {
6939: background: $sidebg;
6940: }
6941:
6942: td.LC_table_cell_checkbox {
6943: text-align: center;
6944: }
6945:
6946: .LC_fontsize_small {
6947: font-size: 70%;
6948: }
6949:
6950: #LC_breadcrumbs {
6951: clear:both;
6952: background: $sidebg;
6953: border-bottom: 1px solid $lg_border_color;
6954: line-height: 2.5em;
6955: overflow: hidden;
6956: margin: 0;
6957: padding: 0;
6958: text-align: left;
6959: }
6960:
6961: .LC_head_subbox, .LC_actionbox {
6962: clear:both;
6963: background: #F8F8F8; /* $sidebg; */
6964: border: 1px solid $sidebg;
6965: margin: 0 0 10px 0;
6966: padding: 3px;
6967: text-align: left;
6968: }
6969:
6970: .LC_fontsize_medium {
6971: font-size: 85%;
6972: }
6973:
6974: .LC_fontsize_large {
6975: font-size: 120%;
6976: }
6977:
6978: .LC_menubuttons_inline_text {
6979: color: $font;
6980: font-size: 90%;
6981: padding-left:3px;
6982: }
6983:
6984: .LC_menubuttons_inline_text img{
6985: vertical-align: middle;
6986: }
6987:
6988: li.LC_menubuttons_inline_text img {
6989: cursor:pointer;
6990: text-decoration: none;
6991: }
6992:
6993: .LC_menubuttons_link {
6994: text-decoration: none;
6995: }
6996:
6997: .LC_menubuttons_category {
6998: color: $font;
6999: background: $pgbg;
7000: font-size: larger;
7001: font-weight: bold;
7002: }
7003:
7004: td.LC_menubuttons_text {
7005: color: $font;
7006: }
7007:
7008: .LC_current_location {
7009: background: $tabbg;
7010: }
7011:
7012: td.LC_zero_height {
7013: line-height: 0;
7014: cellpadding: 0;
7015: }
7016:
7017: table.LC_data_table {
7018: border: 1px solid #000000;
7019: border-collapse: separate;
7020: border-spacing: 1px;
7021: background: $pgbg;
7022: }
7023:
7024: .LC_data_table_dense {
7025: font-size: small;
7026: }
7027:
7028: table.LC_nested_outer {
7029: border: 1px solid #000000;
7030: border-collapse: collapse;
7031: border-spacing: 0;
7032: width: 100%;
7033: }
7034:
7035: table.LC_innerpickbox,
7036: table.LC_nested {
7037: border: none;
7038: border-collapse: collapse;
7039: border-spacing: 0;
7040: width: 100%;
7041: }
7042:
7043: table.LC_data_table tr th,
7044: table.LC_calendar tr th,
7045: table.LC_prior_tries tr th,
7046: table.LC_innerpickbox tr th {
7047: font-weight: bold;
7048: background-color: $data_table_head;
7049: color:$fontmenu;
7050: font-size:90%;
7051: }
7052:
7053: table.LC_innerpickbox tr th,
7054: table.LC_innerpickbox tr td {
7055: vertical-align: top;
7056: }
7057:
7058: table.LC_data_table tr.LC_info_row > td {
7059: background-color: #CCCCCC;
7060: font-weight: bold;
7061: text-align: left;
7062: }
7063:
7064: table.LC_data_table tr.LC_odd_row > td {
7065: background-color: $data_table_light;
7066: padding: 2px;
7067: vertical-align: top;
7068: }
7069:
7070: table.LC_pick_box tr > td.LC_odd_row {
7071: background-color: $data_table_light;
7072: vertical-align: top;
7073: }
7074:
7075: table.LC_data_table tr.LC_even_row > td {
7076: background-color: $data_table_dark;
7077: padding: 2px;
7078: vertical-align: top;
7079: }
7080:
7081: table.LC_pick_box tr > td.LC_even_row {
7082: background-color: $data_table_dark;
7083: vertical-align: top;
7084: }
7085:
7086: table.LC_data_table tr.LC_data_table_highlight td {
7087: background-color: $data_table_darker;
7088: }
7089:
7090: table.LC_data_table tr td.LC_leftcol_header {
7091: background-color: $data_table_head;
7092: font-weight: bold;
7093: }
7094:
7095: table.LC_data_table tr.LC_empty_row td,
7096: table.LC_nested tr.LC_empty_row td {
7097: font-weight: bold;
7098: font-style: italic;
7099: text-align: center;
7100: padding: 8px;
7101: }
7102:
7103: table.LC_data_table tr.LC_empty_row td,
7104: table.LC_data_table tr.LC_footer_row td {
7105: background-color: $sidebg;
7106: }
7107:
7108: table.LC_nested tr.LC_empty_row td {
7109: background-color: #FFFFFF;
7110: }
7111:
7112: table.LC_caption {
7113: }
7114:
7115: table.LC_nested tr.LC_empty_row td {
7116: padding: 4ex
7117: }
7118:
7119: table.LC_nested_outer tr th {
7120: font-weight: bold;
7121: color:$fontmenu;
7122: background-color: $data_table_head;
7123: font-size: small;
7124: border-bottom: 1px solid #000000;
7125: }
7126:
7127: table.LC_nested_outer tr td.LC_subheader {
7128: background-color: $data_table_head;
7129: font-weight: bold;
7130: font-size: small;
7131: border-bottom: 1px solid #000000;
7132: text-align: right;
7133: }
7134:
7135: table.LC_nested tr.LC_info_row td {
7136: background-color: #CCCCCC;
7137: font-weight: bold;
7138: font-size: small;
7139: text-align: center;
7140: }
7141:
7142: table.LC_nested tr.LC_info_row td.LC_left_item,
7143: table.LC_nested_outer tr th.LC_left_item {
7144: text-align: left;
7145: }
7146:
7147: table.LC_nested td {
7148: background-color: #FFFFFF;
7149: font-size: small;
7150: }
7151:
7152: table.LC_nested_outer tr th.LC_right_item,
7153: table.LC_nested tr.LC_info_row td.LC_right_item,
7154: table.LC_nested tr.LC_odd_row td.LC_right_item,
7155: table.LC_nested tr td.LC_right_item {
7156: text-align: right;
7157: }
7158:
7159: table.LC_nested tr.LC_odd_row td {
7160: background-color: #EEEEEE;
7161: }
7162:
7163: table.LC_createuser {
7164: }
7165:
7166: table.LC_createuser tr.LC_section_row td {
7167: font-size: small;
7168: }
7169:
7170: table.LC_createuser tr.LC_info_row td {
7171: background-color: #CCCCCC;
7172: font-weight: bold;
7173: text-align: center;
7174: }
7175:
7176: table.LC_calendar {
7177: border: 1px solid #000000;
7178: border-collapse: collapse;
7179: width: 98%;
7180: }
7181:
7182: table.LC_calendar_pickdate {
7183: font-size: xx-small;
7184: }
7185:
7186: table.LC_calendar tr td {
7187: border: 1px solid #000000;
7188: vertical-align: top;
7189: width: 14%;
7190: }
7191:
7192: table.LC_calendar tr td.LC_calendar_day_empty {
7193: background-color: $data_table_dark;
7194: }
7195:
7196: table.LC_calendar tr td.LC_calendar_day_current {
7197: background-color: $data_table_highlight;
7198: }
7199:
7200: table.LC_data_table tr td.LC_mail_new {
7201: background-color: $mail_new;
7202: }
7203:
7204: table.LC_data_table tr.LC_mail_new:hover {
7205: background-color: $mail_new_hover;
7206: }
7207:
7208: table.LC_data_table tr td.LC_mail_read {
7209: background-color: $mail_read;
7210: }
7211:
7212: /*
7213: table.LC_data_table tr.LC_mail_read:hover {
7214: background-color: $mail_read_hover;
7215: }
7216: */
7217:
7218: table.LC_data_table tr td.LC_mail_replied {
7219: background-color: $mail_replied;
7220: }
7221:
7222: /*
7223: table.LC_data_table tr.LC_mail_replied:hover {
7224: background-color: $mail_replied_hover;
7225: }
7226: */
7227:
7228: table.LC_data_table tr td.LC_mail_other {
7229: background-color: $mail_other;
7230: }
7231:
7232: /*
7233: table.LC_data_table tr.LC_mail_other:hover {
7234: background-color: $mail_other_hover;
7235: }
7236: */
7237:
7238: table.LC_data_table tr > td.LC_browser_file,
7239: table.LC_data_table tr > td.LC_browser_file_published {
7240: background: #AAEE77;
7241: }
7242:
7243: table.LC_data_table tr > td.LC_browser_file_locked,
7244: table.LC_data_table tr > td.LC_browser_file_unpublished {
7245: background: #FFAA99;
7246: }
7247:
7248: table.LC_data_table tr > td.LC_browser_file_obsolete {
7249: background: #888888;
7250: }
7251:
7252: table.LC_data_table tr > td.LC_browser_file_modified,
7253: table.LC_data_table tr > td.LC_browser_file_metamodified {
7254: background: #F8F866;
7255: }
7256:
7257: table.LC_data_table tr.LC_browser_folder > td {
7258: background: #E0E8FF;
7259: }
7260:
7261: table.LC_data_table tr > td.LC_roles_is {
7262: /* background: #77FF77; */
7263: }
7264:
7265: table.LC_data_table tr > td.LC_roles_future {
7266: border-right: 8px solid #FFFF77;
7267: }
7268:
7269: table.LC_data_table tr > td.LC_roles_will {
7270: border-right: 8px solid #FFAA77;
7271: }
7272:
7273: table.LC_data_table tr > td.LC_roles_expired {
7274: border-right: 8px solid #FF7777;
7275: }
7276:
7277: table.LC_data_table tr > td.LC_roles_will_not {
7278: border-right: 8px solid #AAFF77;
7279: }
7280:
7281: table.LC_data_table tr > td.LC_roles_selected {
7282: border-right: 8px solid #11CC55;
7283: }
7284:
7285: span.LC_current_location {
7286: font-size:larger;
7287: background: $pgbg;
7288: }
7289:
7290: span.LC_current_nav_location {
7291: font-weight:bold;
7292: background: $sidebg;
7293: }
7294:
7295: span.LC_parm_menu_item {
7296: font-size: larger;
7297: }
7298:
7299: span.LC_parm_scope_all {
7300: color: red;
7301: }
7302:
7303: span.LC_parm_scope_folder {
7304: color: green;
7305: }
7306:
7307: span.LC_parm_scope_resource {
7308: color: orange;
7309: }
7310:
7311: span.LC_parm_part {
7312: color: blue;
7313: }
7314:
7315: span.LC_parm_folder,
7316: span.LC_parm_symb {
7317: font-size: x-small;
7318: font-family: $mono;
7319: color: #AAAAAA;
7320: }
7321:
7322: ul.LC_parm_parmlist li {
7323: display: inline-block;
7324: padding: 0.3em 0.8em;
7325: vertical-align: top;
7326: width: 150px;
7327: border-top:1px solid $lg_border_color;
7328: }
7329:
7330: td.LC_parm_overview_level_menu,
7331: td.LC_parm_overview_map_menu,
7332: td.LC_parm_overview_parm_selectors,
7333: td.LC_parm_overview_restrictions {
7334: border: 1px solid black;
7335: border-collapse: collapse;
7336: }
7337:
7338: table.LC_parm_overview_restrictions td {
7339: border-width: 1px 4px 1px 4px;
7340: border-style: solid;
7341: border-color: $pgbg;
7342: text-align: center;
7343: }
7344:
7345: table.LC_parm_overview_restrictions th {
7346: background: $tabbg;
7347: border-width: 1px 4px 1px 4px;
7348: border-style: solid;
7349: border-color: $pgbg;
7350: }
7351:
7352: table#LC_helpmenu {
7353: border: none;
7354: height: 55px;
7355: border-spacing: 0;
7356: }
7357:
7358: table#LC_helpmenu fieldset legend {
7359: font-size: larger;
7360: }
7361:
7362: table#LC_helpmenu_links {
7363: width: 100%;
7364: border: 1px solid black;
7365: background: $pgbg;
7366: padding: 0;
7367: border-spacing: 1px;
7368: }
7369:
7370: table#LC_helpmenu_links tr td {
7371: padding: 1px;
7372: background: $tabbg;
7373: text-align: center;
7374: font-weight: bold;
7375: }
7376:
7377: table#LC_helpmenu_links a:link,
7378: table#LC_helpmenu_links a:visited,
7379: table#LC_helpmenu_links a:active {
7380: text-decoration: none;
7381: color: $font;
7382: }
7383:
7384: table#LC_helpmenu_links a:hover {
7385: text-decoration: underline;
7386: color: $vlink;
7387: }
7388:
7389: .LC_chrt_popup_exists {
7390: border: 1px solid #339933;
7391: margin: -1px;
7392: }
7393:
7394: .LC_chrt_popup_up {
7395: border: 1px solid yellow;
7396: margin: -1px;
7397: }
7398:
7399: .LC_chrt_popup {
7400: border: 1px solid #8888FF;
7401: background: #CCCCFF;
7402: }
7403:
7404: table.LC_pick_box {
7405: border-collapse: separate;
7406: background: white;
7407: border: 1px solid black;
7408: border-spacing: 1px;
7409: }
7410:
7411: table.LC_pick_box td.LC_pick_box_title {
7412: background: $sidebg;
7413: font-weight: bold;
7414: text-align: left;
7415: vertical-align: top;
7416: width: 184px;
7417: padding: 8px;
7418: }
7419:
7420: table.LC_pick_box td.LC_pick_box_value {
7421: text-align: left;
7422: padding: 8px;
7423: }
7424:
7425: table.LC_pick_box td.LC_pick_box_select {
7426: text-align: left;
7427: padding: 8px;
7428: }
7429:
7430: table.LC_pick_box td.LC_pick_box_separator {
7431: padding: 0;
7432: height: 1px;
7433: background: black;
7434: }
7435:
7436: table.LC_pick_box td.LC_pick_box_submit {
7437: text-align: right;
7438: }
7439:
7440: table.LC_pick_box td.LC_evenrow_value {
7441: text-align: left;
7442: padding: 8px;
7443: background-color: $data_table_light;
7444: }
7445:
7446: table.LC_pick_box td.LC_oddrow_value {
7447: text-align: left;
7448: padding: 8px;
7449: background-color: $data_table_light;
7450: }
7451:
7452: span.LC_helpform_receipt_cat {
7453: font-weight: bold;
7454: }
7455:
7456: table.LC_group_priv_box {
7457: background: white;
7458: border: 1px solid black;
7459: border-spacing: 1px;
7460: }
7461:
7462: table.LC_group_priv_box td.LC_pick_box_title {
7463: background: $tabbg;
7464: font-weight: bold;
7465: text-align: right;
7466: width: 184px;
7467: }
7468:
7469: table.LC_group_priv_box td.LC_groups_fixed {
7470: background: $data_table_light;
7471: text-align: center;
7472: }
7473:
7474: table.LC_group_priv_box td.LC_groups_optional {
7475: background: $data_table_dark;
7476: text-align: center;
7477: }
7478:
7479: table.LC_group_priv_box td.LC_groups_functionality {
7480: background: $data_table_darker;
7481: text-align: center;
7482: font-weight: bold;
7483: }
7484:
7485: table.LC_group_priv td {
7486: text-align: left;
7487: padding: 0;
7488: }
7489:
7490: .LC_navbuttons {
7491: margin: 2ex 0ex 2ex 0ex;
7492: }
7493:
7494: .LC_topic_bar {
7495: font-weight: bold;
7496: background: $tabbg;
7497: margin: 1em 0em 1em 2em;
7498: padding: 3px;
7499: font-size: 1.2em;
7500: }
7501:
7502: .LC_topic_bar span {
7503: left: 0.5em;
7504: position: absolute;
7505: vertical-align: middle;
7506: font-size: 1.2em;
7507: }
7508:
7509: table.LC_course_group_status {
7510: margin: 20px;
7511: }
7512:
7513: table.LC_status_selector td {
7514: vertical-align: top;
7515: text-align: center;
7516: padding: 4px;
7517: }
7518:
7519: div.LC_feedback_link {
7520: clear: both;
7521: background: $sidebg;
7522: width: 100%;
7523: padding-bottom: 10px;
7524: border: 1px $tabbg solid;
7525: height: 22px;
7526: line-height: 22px;
7527: padding-top: 5px;
7528: }
7529:
7530: div.LC_feedback_link img {
7531: height: 22px;
7532: vertical-align:middle;
7533: }
7534:
7535: div.LC_feedback_link a {
7536: text-decoration: none;
7537: }
7538:
7539: div.LC_comblock {
7540: display:inline;
7541: color:$font;
7542: font-size:90%;
7543: }
7544:
7545: div.LC_feedback_link div.LC_comblock {
7546: padding-left:5px;
7547: }
7548:
7549: div.LC_feedback_link div.LC_comblock a {
7550: color:$font;
7551: }
7552:
7553: span.LC_feedback_link {
7554: /* background: $feedback_link_bg; */
7555: font-size: larger;
7556: }
7557:
7558: span.LC_message_link {
7559: /* background: $feedback_link_bg; */
7560: font-size: larger;
7561: position: absolute;
7562: right: 1em;
7563: }
7564:
7565: table.LC_prior_tries {
7566: border: 1px solid #000000;
7567: border-collapse: separate;
7568: border-spacing: 1px;
7569: }
7570:
7571: table.LC_prior_tries td {
7572: padding: 2px;
7573: }
7574:
7575: .LC_answer_correct {
7576: background: lightgreen;
7577: color: darkgreen;
7578: padding: 6px;
7579: }
7580:
7581: .LC_answer_charged_try {
7582: background: #FFAAAA;
7583: color: darkred;
7584: padding: 6px;
7585: }
7586:
7587: .LC_answer_not_charged_try,
7588: .LC_answer_no_grade,
7589: .LC_answer_late {
7590: background: lightyellow;
7591: color: black;
7592: padding: 6px;
7593: }
7594:
7595: .LC_answer_previous {
7596: background: lightblue;
7597: color: darkblue;
7598: padding: 6px;
7599: }
7600:
7601: .LC_answer_no_message {
7602: background: #FFFFFF;
7603: color: black;
7604: padding: 6px;
7605: }
7606:
7607: .LC_answer_unknown,
7608: .LC_answer_warning {
7609: background: orange;
7610: color: black;
7611: padding: 6px;
7612: }
7613:
7614: span.LC_prior_numerical,
7615: span.LC_prior_string,
7616: span.LC_prior_custom,
7617: span.LC_prior_reaction,
7618: span.LC_prior_math {
7619: font-family: $mono;
7620: white-space: pre;
7621: }
7622:
7623: span.LC_prior_string {
7624: font-family: $mono;
7625: white-space: pre;
7626: }
7627:
7628: table.LC_prior_option {
7629: width: 100%;
7630: border-collapse: collapse;
7631: }
7632:
7633: table.LC_prior_rank,
7634: table.LC_prior_match {
7635: border-collapse: collapse;
7636: }
7637:
7638: table.LC_prior_option tr td,
7639: table.LC_prior_rank tr td,
7640: table.LC_prior_match tr td {
7641: border: 1px solid #000000;
7642: }
7643:
7644: .LC_nobreak {
7645: white-space: nowrap;
7646: }
7647:
7648: span.LC_cusr_emph {
7649: font-style: italic;
7650: }
7651:
7652: span.LC_cusr_subheading {
7653: font-weight: normal;
7654: font-size: 85%;
7655: }
7656:
7657: div.LC_docs_entry_move {
7658: border: 1px solid #BBBBBB;
7659: background: #DDDDDD;
7660: width: 22px;
7661: padding: 1px;
7662: margin: 0;
7663: }
7664:
7665: table.LC_data_table tr > td.LC_docs_entry_commands,
7666: table.LC_data_table tr > td.LC_docs_entry_parameter {
7667: font-size: x-small;
7668: }
7669:
7670: .LC_docs_entry_parameter {
7671: white-space: nowrap;
7672: }
7673:
7674: .LC_docs_copy {
7675: color: #000099;
7676: }
7677:
7678: .LC_docs_cut {
7679: color: #550044;
7680: }
7681:
7682: .LC_docs_rename {
7683: color: #009900;
7684: }
7685:
7686: .LC_docs_remove {
7687: color: #990000;
7688: }
7689:
7690: .LC_domprefs_email,
7691: .LC_docs_reinit_warn,
7692: .LC_docs_ext_edit {
7693: font-size: x-small;
7694: }
7695:
7696: table.LC_docs_adddocs td,
7697: table.LC_docs_adddocs th {
7698: border: 1px solid #BBBBBB;
7699: padding: 4px;
7700: background: #DDDDDD;
7701: }
7702:
7703: table.LC_sty_begin {
7704: background: #BBFFBB;
7705: }
7706:
7707: table.LC_sty_end {
7708: background: #FFBBBB;
7709: }
7710:
7711: table.LC_double_column {
7712: border-width: 0;
7713: border-collapse: collapse;
7714: width: 100%;
7715: padding: 2px;
7716: }
7717:
7718: table.LC_double_column tr td.LC_left_col {
7719: top: 2px;
7720: left: 2px;
7721: width: 47%;
7722: vertical-align: top;
7723: }
7724:
7725: table.LC_double_column tr td.LC_right_col {
7726: top: 2px;
7727: right: 2px;
7728: width: 47%;
7729: vertical-align: top;
7730: }
7731:
7732: div.LC_left_float {
7733: float: left;
7734: padding-right: 5%;
7735: padding-bottom: 4px;
7736: }
7737:
7738: div.LC_clear_float_header {
7739: padding-bottom: 2px;
7740: }
7741:
7742: div.LC_clear_float_footer {
7743: padding-top: 10px;
7744: clear: both;
7745: }
7746:
7747: div.LC_grade_show_user {
7748: /* border-left: 5px solid $sidebg; */
7749: border-top: 5px solid #000000;
7750: margin: 50px 0 0 0;
7751: padding: 15px 0 5px 10px;
7752: }
7753:
7754: div.LC_grade_show_user_odd_row {
7755: /* border-left: 5px solid #000000; */
7756: }
7757:
7758: div.LC_grade_show_user div.LC_Box {
7759: margin-right: 50px;
7760: }
7761:
7762: div.LC_grade_submissions,
7763: div.LC_grade_message_center,
7764: div.LC_grade_info_links {
7765: margin: 5px;
7766: width: 99%;
7767: background: #FFFFFF;
7768: }
7769:
7770: div.LC_grade_submissions_header,
7771: div.LC_grade_message_center_header {
7772: font-weight: bold;
7773: font-size: large;
7774: }
7775:
7776: div.LC_grade_submissions_body,
7777: div.LC_grade_message_center_body {
7778: border: 1px solid black;
7779: width: 99%;
7780: background: #FFFFFF;
7781: }
7782:
7783: table.LC_scantron_action {
7784: width: 100%;
7785: }
7786:
7787: table.LC_scantron_action tr th {
7788: font-weight:bold;
7789: font-style:normal;
7790: }
7791:
7792: .LC_edit_problem_header,
7793: div.LC_edit_problem_footer {
7794: font-weight: normal;
7795: font-size: medium;
7796: margin: 2px;
7797: background-color: $sidebg;
7798: }
7799:
7800: div.LC_edit_problem_header,
7801: div.LC_edit_problem_header div,
7802: div.LC_edit_problem_footer,
7803: div.LC_edit_problem_footer div,
7804: div.LC_edit_problem_editxml_header,
7805: div.LC_edit_problem_editxml_header div {
7806: z-index: 100;
7807: }
7808:
7809: div.LC_edit_problem_header_title {
7810: font-weight: bold;
7811: font-size: larger;
7812: background: $tabbg;
7813: padding: 3px;
7814: margin: 0 0 5px 0;
7815: }
7816:
7817: table.LC_edit_problem_header_title {
7818: width: 100%;
7819: background: $tabbg;
7820: }
7821:
7822: div.LC_edit_actionbar {
7823: background-color: $sidebg;
7824: margin: 0;
7825: padding: 0;
7826: line-height: 200%;
7827: }
7828:
7829: div.LC_edit_actionbar div{
7830: padding: 0;
7831: margin: 0;
7832: display: inline-block;
7833: }
7834:
7835: .LC_edit_opt {
7836: padding-left: 1em;
7837: white-space: nowrap;
7838: }
7839:
7840: .LC_edit_problem_latexhelper{
7841: text-align: right;
7842: }
7843:
7844: #LC_edit_problem_colorful div{
7845: margin-left: 40px;
7846: }
7847:
7848: #LC_edit_problem_codemirror div{
7849: margin-left: 0px;
7850: }
7851:
7852: img.stift {
7853: border-width: 0;
7854: vertical-align: middle;
7855: }
7856:
7857: table td.LC_mainmenu_col_fieldset {
7858: vertical-align: top;
7859: }
7860:
7861: div.LC_createcourse {
7862: margin: 10px 10px 10px 10px;
7863: }
7864:
7865: .LC_dccid {
7866: float: right;
7867: margin: 0.2em 0 0 0;
7868: padding: 0;
7869: font-size: 90%;
7870: display:none;
7871: }
7872:
7873: ol.LC_primary_menu a:hover,
7874: ol#LC_MenuBreadcrumbs a:hover,
7875: ol#LC_PathBreadcrumbs a:hover,
7876: ul#LC_secondary_menu a:hover,
7877: .LC_FormSectionClearButton input:hover
7878: ul.LC_TabContent li:hover a {
7879: color:$button_hover;
7880: text-decoration:none;
7881: }
7882:
7883: h1 {
7884: padding: 0;
7885: line-height:130%;
7886: }
7887:
7888: h2,
7889: h3,
7890: h4,
7891: h5,
7892: h6 {
7893: margin: 5px 0 5px 0;
7894: padding: 0;
7895: line-height:130%;
7896: }
7897:
7898: .LC_hcell {
7899: padding:3px 15px 3px 15px;
7900: margin: 0;
7901: background-color:$tabbg;
7902: color:$fontmenu;
7903: border-bottom:solid 1px $lg_border_color;
7904: }
7905:
7906: .LC_Box > .LC_hcell {
7907: margin: 0 -10px 10px -10px;
7908: }
7909:
7910: .LC_noBorder {
7911: border: 0;
7912: }
7913:
7914: .LC_FormSectionClearButton input {
7915: background-color:transparent;
7916: border: none;
7917: cursor:pointer;
7918: text-decoration:underline;
7919: }
7920:
7921: .LC_help_open_topic {
7922: color: #FFFFFF;
7923: background-color: #EEEEFF;
7924: margin: 1px;
7925: padding: 4px;
7926: border: 1px solid #000033;
7927: white-space: nowrap;
7928: /* vertical-align: middle; */
7929: }
7930:
7931: dl,
7932: ul,
7933: div,
7934: fieldset {
7935: margin: 10px 10px 10px 0;
7936: /* overflow: hidden; */
7937: }
7938:
7939: fieldset#LC_selectuser {
7940: margin: 0;
7941: padding: 0;
7942: }
7943:
7944: article.geogebraweb div {
7945: margin: 0;
7946: }
7947:
7948: fieldset > legend {
7949: font-weight: bold;
7950: padding: 0 5px 0 5px;
7951: }
7952:
7953: #LC_nav_bar {
7954: float: left;
7955: background-color: $pgbg_or_bgcolor;
7956: margin: 0 0 2px 0;
7957: }
7958:
7959: #LC_realm {
7960: margin: 0.2em 0 0 0;
7961: padding: 0;
7962: font-weight: bold;
7963: text-align: center;
7964: background-color: $pgbg_or_bgcolor;
7965: }
7966:
7967: #LC_nav_bar em {
7968: font-weight: bold;
7969: font-style: normal;
7970: }
7971:
7972: ol.LC_primary_menu {
7973: margin: 0;
7974: padding: 0;
7975: }
7976:
7977: ol#LC_PathBreadcrumbs {
7978: margin: 0;
7979: }
7980:
7981: ol.LC_primary_menu li {
7982: color: RGB(80, 80, 80);
7983: vertical-align: middle;
7984: text-align: left;
7985: list-style: none;
7986: position: relative;
7987: float: left;
7988: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7989: line-height: 1.5em;
7990: }
7991:
7992: ol.LC_primary_menu li a,
7993: ol.LC_primary_menu li p {
7994: display: block;
7995: margin: 0;
7996: padding: 0 5px 0 10px;
7997: text-decoration: none;
7998: }
7999:
8000: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
8001: display: inline-block;
8002: width: 95%;
8003: text-align: left;
8004: }
8005:
8006: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
8007: display: inline-block;
8008: width: 5%;
8009: float: right;
8010: text-align: right;
8011: font-size: 70%;
8012: }
8013:
8014: ol.LC_primary_menu ul {
8015: display: none;
8016: width: 15em;
8017: background-color: $data_table_light;
8018: position: absolute;
8019: top: 100%;
8020: }
8021:
8022: ol.LC_primary_menu ul ul {
8023: left: 100%;
8024: top: 0;
8025: }
8026:
8027: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
8028: display: block;
8029: position: absolute;
8030: margin: 0;
8031: padding: 0;
8032: z-index: 2;
8033: }
8034:
8035: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
8036: /* First Submenu -> size should be smaller than the menu title of the whole menu */
8037: font-size: 90%;
8038: vertical-align: top;
8039: float: none;
8040: border-left: 1px solid black;
8041: border-right: 1px solid black;
8042: /* A dark bottom border to visualize different menu options;
8043: overwritten in the create_submenu routine for the last border-bottom of the menu */
8044: border-bottom: 1px solid $data_table_dark;
8045: }
8046:
8047: ol.LC_primary_menu li li p:hover {
8048: color:$button_hover;
8049: text-decoration:none;
8050: background-color:$data_table_dark;
8051: }
8052:
8053: ol.LC_primary_menu li li a:hover {
8054: color:$button_hover;
8055: background-color:$data_table_dark;
8056: }
8057:
8058: /* Font-size equal to the size of the predecessors*/
8059: ol.LC_primary_menu li:hover li li {
8060: font-size: 100%;
8061: }
8062:
8063: ol.LC_primary_menu li img {
8064: vertical-align: bottom;
8065: height: 1.1em;
8066: margin: 0.2em 0 0 0;
8067: }
8068:
8069: ol.LC_primary_menu a {
8070: color: RGB(80, 80, 80);
8071: text-decoration: none;
8072: }
8073:
8074: ol.LC_primary_menu a.LC_new_message {
8075: font-weight:bold;
8076: color: darkred;
8077: }
8078:
8079: ol.LC_docs_parameters {
8080: margin-left: 0;
8081: padding: 0;
8082: list-style: none;
8083: }
8084:
8085: ol.LC_docs_parameters li {
8086: margin: 0;
8087: padding-right: 20px;
8088: display: inline;
8089: }
8090:
8091: ol.LC_docs_parameters li:before {
8092: content: "\\002022 \\0020";
8093: }
8094:
8095: li.LC_docs_parameters_title {
8096: font-weight: bold;
8097: }
8098:
8099: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
8100: content: "";
8101: }
8102:
8103: ul#LC_secondary_menu {
8104: clear: right;
8105: color: $fontmenu;
8106: background: $tabbg;
8107: list-style: none;
8108: padding: 0;
8109: margin: 0;
8110: width: 100%;
8111: text-align: left;
8112: float: left;
8113: }
8114:
8115: ul#LC_secondary_menu li {
8116: font-weight: bold;
8117: line-height: 1.8em;
8118: border-right: 1px solid black;
8119: float: left;
8120: }
8121:
8122: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
8123: background-color: $data_table_light;
8124: }
8125:
8126: ul#LC_secondary_menu li a {
8127: padding: 0 0.8em;
8128: }
8129:
8130: ul#LC_secondary_menu li ul {
8131: display: none;
8132: }
8133:
8134: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
8135: display: block;
8136: position: absolute;
8137: margin: 0;
8138: padding: 0;
8139: list-style:none;
8140: float: none;
8141: background-color: $data_table_light;
8142: z-index: 2;
8143: margin-left: -1px;
8144: }
8145:
8146: ul#LC_secondary_menu li ul li {
8147: font-size: 90%;
8148: vertical-align: top;
8149: border-left: 1px solid black;
8150: border-right: 1px solid black;
8151: background-color: $data_table_light;
8152: list-style:none;
8153: float: none;
8154: }
8155:
8156: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
8157: background-color: $data_table_dark;
8158: }
8159:
8160: ul.LC_TabContent {
8161: display:block;
8162: background: $sidebg;
8163: border-bottom: solid 1px $lg_border_color;
8164: list-style:none;
8165: margin: -1px -10px 0 -10px;
8166: padding: 0;
8167: }
8168:
8169: ul.LC_TabContent li,
8170: ul.LC_TabContentBigger li {
8171: float:left;
8172: }
8173:
8174: ul#LC_secondary_menu li a {
8175: color: $fontmenu;
8176: text-decoration: none;
8177: }
8178:
8179: ul.LC_TabContent {
8180: min-height:20px;
8181: }
8182:
8183: ul.LC_TabContent li {
8184: vertical-align:middle;
8185: padding: 0 16px 0 10px;
8186: background-color:$tabbg;
8187: border-bottom:solid 1px $lg_border_color;
8188: border-left: solid 1px $font;
8189: }
8190:
8191: ul.LC_TabContent .right {
8192: float:right;
8193: }
8194:
8195: ul.LC_TabContent li a,
8196: ul.LC_TabContent li {
8197: color:rgb(47,47,47);
8198: text-decoration:none;
8199: font-size:95%;
8200: font-weight:bold;
8201: min-height:20px;
8202: }
8203:
8204: ul.LC_TabContent li a:hover,
8205: ul.LC_TabContent li a:focus {
8206: color: $button_hover;
8207: background:none;
8208: outline:none;
8209: }
8210:
8211: ul.LC_TabContent li:hover {
8212: color: $button_hover;
8213: cursor:pointer;
8214: }
8215:
8216: ul.LC_TabContent li.active {
8217: color: $font;
8218: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
8219: border-bottom:solid 1px #FFFFFF;
8220: cursor: default;
8221: }
8222:
8223: ul.LC_TabContent li.active a {
8224: color:$font;
8225: background:#FFFFFF;
8226: outline: none;
8227: }
8228:
8229: ul.LC_TabContent li.goback {
8230: float: left;
8231: border-left: none;
8232: }
8233:
8234: #maincoursedoc {
8235: clear:both;
8236: }
8237:
8238: ul.LC_TabContentBigger {
8239: display:block;
8240: list-style:none;
8241: padding: 0;
8242: }
8243:
8244: ul.LC_TabContentBigger li {
8245: vertical-align:bottom;
8246: height: 30px;
8247: font-size:110%;
8248: font-weight:bold;
8249: color: #737373;
8250: }
8251:
8252: ul.LC_TabContentBigger li.active {
8253: position: relative;
8254: top: 1px;
8255: }
8256:
8257: ul.LC_TabContentBigger li a {
8258: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
8259: height: 30px;
8260: line-height: 30px;
8261: text-align: center;
8262: display: block;
8263: text-decoration: none;
8264: outline: none;
8265: }
8266:
8267: ul.LC_TabContentBigger li.active a {
8268: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
8269: color:$font;
8270: }
8271:
8272: ul.LC_TabContentBigger li b {
8273: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
8274: display: block;
8275: float: left;
8276: padding: 0 30px;
8277: border-bottom: 1px solid $lg_border_color;
8278: }
8279:
8280: ul.LC_TabContentBigger li:hover b {
8281: color:$button_hover;
8282: }
8283:
8284: ul.LC_TabContentBigger li.active b {
8285: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
8286: color:$font;
8287: border: 0;
8288: }
8289:
8290:
8291: ul.LC_CourseBreadcrumbs {
8292: background: $sidebg;
8293: height: 2em;
8294: padding-left: 10px;
8295: margin: 0;
8296: list-style-position: inside;
8297: }
8298:
8299: ol#LC_MenuBreadcrumbs,
8300: ol#LC_PathBreadcrumbs {
8301: padding-left: 10px;
8302: margin: 0;
8303: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
8304: }
8305:
8306: ol#LC_MenuBreadcrumbs li,
8307: ol#LC_PathBreadcrumbs li,
8308: ul.LC_CourseBreadcrumbs li {
8309: display: inline;
8310: white-space: normal;
8311: }
8312:
8313: ol#LC_MenuBreadcrumbs li a,
8314: ul.LC_CourseBreadcrumbs li a {
8315: text-decoration: none;
8316: font-size:90%;
8317: }
8318:
8319: ol#LC_MenuBreadcrumbs h1 {
8320: display: inline;
8321: font-size: 90%;
8322: line-height: 2.5em;
8323: margin: 0;
8324: padding: 0;
8325: }
8326:
8327: ol#LC_PathBreadcrumbs li a {
8328: text-decoration:none;
8329: font-size:100%;
8330: font-weight:bold;
8331: }
8332:
8333: .LC_Box {
8334: border: solid 1px $lg_border_color;
8335: padding: 0 10px 10px 10px;
8336: }
8337:
8338: .LC_DocsBox {
8339: border: solid 1px $lg_border_color;
8340: padding: 0 0 10px 10px;
8341: }
8342:
8343: .LC_AboutMe_Image {
8344: float:left;
8345: margin-right:10px;
8346: }
8347:
8348: .LC_Clear_AboutMe_Image {
8349: clear:left;
8350: }
8351:
8352: dl.LC_ListStyleClean dt {
8353: padding-right: 5px;
8354: display: table-header-group;
8355: }
8356:
8357: dl.LC_ListStyleClean dd {
8358: display: table-row;
8359: }
8360:
8361: .LC_ListStyleClean,
8362: .LC_ListStyleSimple,
8363: .LC_ListStyleNormal,
8364: .LC_ListStyleSpecial {
8365: /* display:block; */
8366: list-style-position: inside;
8367: list-style-type: none;
8368: overflow: hidden;
8369: padding: 0;
8370: }
8371:
8372: .LC_ListStyleSimple li,
8373: .LC_ListStyleSimple dd,
8374: .LC_ListStyleNormal li,
8375: .LC_ListStyleNormal dd,
8376: .LC_ListStyleSpecial li,
8377: .LC_ListStyleSpecial dd {
8378: margin: 0;
8379: padding: 5px 5px 5px 10px;
8380: clear: both;
8381: }
8382:
8383: .LC_ListStyleClean li,
8384: .LC_ListStyleClean dd {
8385: padding-top: 0;
8386: padding-bottom: 0;
8387: }
8388:
8389: .LC_ListStyleSimple dd,
8390: .LC_ListStyleSimple li {
8391: border-bottom: solid 1px $lg_border_color;
8392: }
8393:
8394: .LC_ListStyleSpecial li,
8395: .LC_ListStyleSpecial dd {
8396: list-style-type: none;
8397: background-color: RGB(220, 220, 220);
8398: margin-bottom: 4px;
8399: }
8400:
8401: table.LC_SimpleTable {
8402: margin:5px;
8403: border:solid 1px $lg_border_color;
8404: }
8405:
8406: table.LC_SimpleTable tr {
8407: padding: 0;
8408: border:solid 1px $lg_border_color;
8409: }
8410:
8411: table.LC_SimpleTable thead {
8412: background:rgb(220,220,220);
8413: }
8414:
8415: div.LC_columnSection {
8416: display: block;
8417: clear: both;
8418: overflow: hidden;
8419: margin: 0;
8420: }
8421:
8422: div.LC_columnSection>* {
8423: float: left;
8424: margin: 10px 20px 10px 0;
8425: overflow:hidden;
8426: }
8427:
8428: table em {
8429: font-weight: bold;
8430: font-style: normal;
8431: }
8432:
8433: table.LC_tableBrowseRes,
8434: table.LC_tableOfContent {
8435: border:none;
8436: border-spacing: 1px;
8437: padding: 3px;
8438: background-color: #FFFFFF;
8439: font-size: 90%;
8440: }
8441:
8442: table.LC_tableOfContent {
8443: border-collapse: collapse;
8444: }
8445:
8446: table.LC_tableBrowseRes a,
8447: table.LC_tableOfContent a {
8448: background-color: transparent;
8449: text-decoration: none;
8450: }
8451:
8452: table.LC_tableOfContent img {
8453: border: none;
8454: height: 1.3em;
8455: vertical-align: text-bottom;
8456: margin-right: 0.3em;
8457: }
8458:
8459: a#LC_content_toolbar_firsthomework {
8460: background-image:url(/res/adm/pages/open-first-problem.gif);
8461: }
8462:
8463: a#LC_content_toolbar_everything {
8464: background-image:url(/res/adm/pages/show-all.gif);
8465: }
8466:
8467: a#LC_content_toolbar_uncompleted {
8468: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
8469: }
8470:
8471: #LC_content_toolbar_clearbubbles {
8472: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
8473: }
8474:
8475: a#LC_content_toolbar_changefolder {
8476: background : url(/res/adm/pages/close-all-folders.gif) top center ;
8477: }
8478:
8479: a#LC_content_toolbar_changefolder_toggled {
8480: background-image:url(/res/adm/pages/open-all-folders.gif);
8481: }
8482:
8483: a#LC_content_toolbar_edittoplevel {
8484: background-image:url(/res/adm/pages/edittoplevel.gif);
8485: }
8486:
8487: a#LC_content_toolbar_printout {
8488: background-image:url(/res/adm/pages/printout.gif);
8489: }
8490:
8491: ul#LC_toolbar li a:hover {
8492: background-position: bottom center;
8493: }
8494:
8495: ul#LC_toolbar {
8496: padding: 0;
8497: margin: 2px;
8498: list-style:none;
8499: position:relative;
8500: background-color:white;
8501: overflow: auto;
8502: }
8503:
8504: ul#LC_toolbar li {
8505: border:1px solid white;
8506: padding: 0;
8507: margin: 0;
8508: float: left;
8509: display:inline;
8510: vertical-align:middle;
8511: white-space: nowrap;
8512: }
8513:
8514:
8515: a.LC_toolbarItem {
8516: display:block;
8517: padding: 0;
8518: margin: 0;
8519: height: 32px;
8520: width: 32px;
8521: color:white;
8522: border: none;
8523: background-repeat:no-repeat;
8524: background-color:transparent;
8525: }
8526:
8527: ul.LC_funclist {
8528: margin: 0;
8529: padding: 0.5em 1em 0.5em 0;
8530: }
8531:
8532: ul.LC_funclist > li:first-child {
8533: font-weight:bold;
8534: margin-left:0.8em;
8535: }
8536:
8537: ul.LC_funclist + ul.LC_funclist {
8538: /*
8539: left border as a seperator if we have more than
8540: one list
8541: */
8542: border-left: 1px solid $sidebg;
8543: /*
8544: this hides the left border behind the border of the
8545: outer box if element is wrapped to the next 'line'
8546: */
8547: margin-left: -1px;
8548: }
8549:
8550: ul.LC_funclist li {
8551: display: inline;
8552: white-space: nowrap;
8553: margin: 0 0 0 25px;
8554: line-height: 150%;
8555: }
8556:
8557: .LC_hidden {
8558: display: none;
8559: }
8560:
8561: .LCmodal-overlay {
8562: position:fixed;
8563: top:0;
8564: right:0;
8565: bottom:0;
8566: left:0;
8567: height:100%;
8568: width:100%;
8569: margin:0;
8570: padding:0;
8571: background:#999;
8572: opacity:.75;
8573: filter: alpha(opacity=75);
8574: -moz-opacity: 0.75;
8575: z-index:101;
8576: }
8577:
8578: * html .LCmodal-overlay {
8579: position: absolute;
8580: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
8581: }
8582:
8583: .LCmodal-window {
8584: position:fixed;
8585: top:50%;
8586: left:50%;
8587: margin:0;
8588: padding:0;
8589: z-index:102;
8590: }
8591:
8592: * html .LCmodal-window {
8593: position:absolute;
8594: }
8595:
8596: .LCclose-window {
8597: position:absolute;
8598: width:32px;
8599: height:32px;
8600: right:8px;
8601: top:8px;
8602: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
8603: text-indent:-99999px;
8604: overflow:hidden;
8605: cursor:pointer;
8606: }
8607:
8608: .LCisDisabled {
8609: cursor: not-allowed;
8610: opacity: 0.5;
8611: }
8612:
8613: a[aria-disabled="true"] {
8614: color: currentColor;
8615: display: inline-block; /* For IE11/ MS Edge bug */
8616: pointer-events: none;
8617: text-decoration: none;
8618: }
8619:
8620: pre.LC_wordwrap {
8621: white-space: pre-wrap;
8622: white-space: -moz-pre-wrap;
8623: white-space: -pre-wrap;
8624: white-space: -o-pre-wrap;
8625: word-wrap: break-word;
8626: }
8627:
8628: /*
8629: styles used for response display
8630: */
8631: div.LC_radiofoil, div.LC_rankfoil {
8632: margin: .5em 0em .5em 0em;
8633: }
8634: table.LC_itemgroup {
8635: margin-top: 1em;
8636: }
8637:
8638: /*
8639: styles used by TTH when "Default set of options to pass to tth/m
8640: when converting TeX" in course settings has been set
8641:
8642: option passed: -t
8643:
8644: */
8645:
8646: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8647: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8648: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8649: td div.norm {line-height:normal;}
8650:
8651: /*
8652: option passed -y3
8653: */
8654:
8655: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8656: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8657: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8658:
8659: /*
8660: sections with roles, for content only
8661: */
8662: section[class^="role-"] {
8663: padding-left: 10px;
8664: padding-right: 5px;
8665: margin-top: 8px;
8666: margin-bottom: 8px;
8667: border: 1px solid #2A4;
8668: border-radius: 5px;
8669: box-shadow: 0px 1px 1px #BBB;
8670: }
8671: section[class^="role-"]>h1 {
8672: position: relative;
8673: margin: 0px;
8674: padding-top: 10px;
8675: padding-left: 40px;
8676: }
8677: section[class^="role-"]>h1:before {
8678: position: absolute;
8679: left: -5px;
8680: top: 5px;
8681: }
8682: section.role-activity>h1:before {
8683: content:url('/adm/daxe/images/section_icons/activity.png');
8684: }
8685: section.role-advice>h1:before {
8686: content:url('/adm/daxe/images/section_icons/advice.png');
8687: }
8688: section.role-bibliography>h1:before {
8689: content:url('/adm/daxe/images/section_icons/bibliography.png');
8690: }
8691: section.role-citation>h1:before {
8692: content:url('/adm/daxe/images/section_icons/citation.png');
8693: }
8694: section.role-conclusion>h1:before {
8695: content:url('/adm/daxe/images/section_icons/conclusion.png');
8696: }
8697: section.role-definition>h1:before {
8698: content:url('/adm/daxe/images/section_icons/definition.png');
8699: }
8700: section.role-demonstration>h1:before {
8701: content:url('/adm/daxe/images/section_icons/demonstration.png');
8702: }
8703: section.role-example>h1:before {
8704: content:url('/adm/daxe/images/section_icons/example.png');
8705: }
8706: section.role-explanation>h1:before {
8707: content:url('/adm/daxe/images/section_icons/explanation.png');
8708: }
8709: section.role-introduction>h1:before {
8710: content:url('/adm/daxe/images/section_icons/introduction.png');
8711: }
8712: section.role-method>h1:before {
8713: content:url('/adm/daxe/images/section_icons/method.png');
8714: }
8715: section.role-more_information>h1:before {
8716: content:url('/adm/daxe/images/section_icons/more_information.png');
8717: }
8718: section.role-objectives>h1:before {
8719: content:url('/adm/daxe/images/section_icons/objectives.png');
8720: }
8721: section.role-prerequisites>h1:before {
8722: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8723: }
8724: section.role-remark>h1:before {
8725: content:url('/adm/daxe/images/section_icons/remark.png');
8726: }
8727: section.role-reminder>h1:before {
8728: content:url('/adm/daxe/images/section_icons/reminder.png');
8729: }
8730: section.role-summary>h1:before {
8731: content:url('/adm/daxe/images/section_icons/summary.png');
8732: }
8733: section.role-syntax>h1:before {
8734: content:url('/adm/daxe/images/section_icons/syntax.png');
8735: }
8736: section.role-warning>h1:before {
8737: content:url('/adm/daxe/images/section_icons/warning.png');
8738: }
8739:
8740: #LC_minitab_header {
8741: float:left;
8742: width:100%;
8743: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
8744: font-size:93%;
8745: line-height:normal;
8746: margin: 0.5em 0 0.5em 0;
8747: }
8748: #LC_minitab_header ul {
8749: margin:0;
8750: padding:10px 10px 0;
8751: list-style:none;
8752: }
8753: #LC_minitab_header li {
8754: float:left;
8755: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
8756: margin:0;
8757: padding:0 0 0 9px;
8758: }
8759: #LC_minitab_header a {
8760: display:block;
8761: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
8762: padding:5px 15px 4px 6px;
8763: }
8764: #LC_minitab_header #LC_current_minitab {
8765: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
8766: }
8767: #LC_minitab_header #LC_current_minitab a {
8768: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
8769: padding-bottom:5px;
8770: }
8771:
8772:
8773: END
8774: }
8775:
8776: =pod
8777:
8778: =item * &headtag()
8779:
8780: Returns a uniform footer for LON-CAPA web pages.
8781:
8782: Inputs: $title - optional title for the head
8783: $head_extra - optional extra HTML to put inside the <head>
8784: $args - optional arguments
8785: force_register - if is true call registerurl so the remote is
8786: informed
8787: redirect -> array ref of
8788: 1- seconds before redirect occurs
8789: 2- url to redirect to
8790: 3- whether the side effect should occur
8791: (side effect of setting
8792: $env{'internal.head.redirect'} to the url
8793: redirected to)
8794: 4- whether the redirect target should be
8795: the opener of the current (pop-up)
8796: window (side effect of setting
8797: $env{'internal.head.to_opener'} to
8798: 1, if true.
8799: 5- whether encrypt check should be skipped
8800: domain -> force to color decorate a page for a specific
8801: domain
8802: function -> force usage of a specific rolish color scheme
8803: bgcolor -> override the default page bgcolor
8804: no_auto_mt_title
8805: -> prevent &mt()ing the title arg
8806:
8807: =cut
8808:
8809: sub headtag {
8810: my ($title,$head_extra,$args) = @_;
8811:
8812: my $function = $args->{'function'} || &get_users_function();
8813: my $domain = $args->{'domain'} || &determinedomain();
8814: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
8815: my $httphost = $args->{'use_absolute'};
8816: my $url = join(':',$env{'user.name'},$env{'user.domain'},
8817: $Apache::lonnet::perlvar{'lonVersion'},
8818: #time(),
8819: $env{'environment.color.timestamp'},
8820: $function,$domain,$bgcolor);
8821:
8822: $url = '/adm/css/'.&escape($url).'.css';
8823:
8824: my $result =
8825: '<head>'.
8826: &font_settings($args);
8827:
8828: my $inhibitprint;
8829: if ($args->{'print_suppress'}) {
8830: $inhibitprint = &print_suppression();
8831: }
8832:
8833: if (!$args->{'frameset'}) {
8834: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
8835: }
8836: if ($args->{'force_register'}) {
8837: $result .= &Apache::lonmenu::registerurl(1);
8838: }
8839: if (!$args->{'no_nav_bar'}
8840: && !$args->{'only_body'}
8841: && !$args->{'frameset'}) {
8842: $result .= &help_menu_js($httphost);
8843: $result.=&modal_window();
8844: $result.=&togglebox_script();
8845: $result.=&wishlist_window();
8846: $result.=&LCprogressbarUpdate_script();
8847: } else {
8848: if ($args->{'add_modal'}) {
8849: $result.=&modal_window();
8850: }
8851: if ($args->{'add_wishlist'}) {
8852: $result.=&wishlist_window();
8853: }
8854: if ($args->{'add_togglebox'}) {
8855: $result.=&togglebox_script();
8856: }
8857: if ($args->{'add_progressbar'}) {
8858: $result.=&LCprogressbarUpdate_script();
8859: }
8860: }
8861: if (ref($args->{'redirect'})) {
8862: my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
8863: if (!$skip_enc_check) {
8864: $url = &Apache::lonenc::check_encrypt($url);
8865: }
8866: if (!$inhibit_continue) {
8867: $env{'internal.head.redirect'} = $url;
8868: }
8869: $result.=<<"ADDMETA";
8870: <meta http-equiv="pragma" content="no-cache" />
8871: ADDMETA
8872: if ($to_opener) {
8873: $env{'internal.head.to_opener'} = 1;
8874: my $dest = &js_escape($url);
8875: my $timeout = int($time * 1000);
8876: $result .=<<"ENDJS";
8877: <script type="text/javascript">
8878: // <![CDATA[
8879: function LC_To_Opener() {
8880: var dest = '$dest';
8881: if (dest != '') {
8882: if (window.opener != null && !window.opener.closed) {
8883: window.opener.location.href=dest;
8884: window.close();
8885: } else {
8886: window.location.href=dest;
8887: }
8888: }
8889: }
8890: \$(document).ready(function () {
8891: setTimeout('LC_To_Opener()',$timeout);
8892: });
8893: // ]]>
8894: </script>
8895: ENDJS
8896: } else {
8897: $result.=<<"ADDMETA";
8898: <meta http-equiv="Refresh" content="$time; url=$url" />
8899: ADDMETA
8900: }
8901: } else {
8902: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
8903: my $requrl = $env{'request.uri'};
8904: if ($requrl eq '') {
8905: $requrl = $ENV{'REQUEST_URI'};
8906: $requrl =~ s/\?.+$//;
8907: }
8908: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
8909: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
8910: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
8911: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
8912: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
8913: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
8914: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
8915: my ($offload,$offloadoth);
8916: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
8917: if ($domdefs{'offloadnow'}{$lonhost}) {
8918: $offload = 1;
8919: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
8920: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
8921: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
8922: $offloadoth = 1;
8923: $dom_in_use = $env{'user.domain'};
8924: }
8925: }
8926: }
8927: }
8928: unless ($offload) {
8929: if (ref($domdefs{'offloadoth'}) eq 'HASH') {
8930: if ($domdefs{'offloadoth'}{$lonhost}) {
8931: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
8932: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
8933: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
8934: $offload = 1;
8935: $offloadoth = 1;
8936: $dom_in_use = $env{'user.domain'};
8937: }
8938: }
8939: }
8940: }
8941: }
8942: if ($offload) {
8943: my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
8944: if (($newserver eq '') && ($offloadoth)) {
8945: my @domains = &Apache::lonnet::current_machine_domains();
8946: if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
8947: ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
8948: }
8949: }
8950: if (($newserver) && ($newserver ne $lonhost)) {
8951: my $numsec = 5;
8952: my $timeout = $numsec * 1000;
8953: my ($newurl,$locknum,%locks,$msg);
8954: if ($env{'request.role.adv'}) {
8955: ($locknum,%locks) = &Apache::lonnet::get_locks();
8956: }
8957: my $disable_submit = 0;
8958: if ($requrl =~ /$LONCAPA::assess_re/) {
8959: $disable_submit = 1;
8960: }
8961: if ($locknum) {
8962: my @lockinfo = sort(values(%locks));
8963: $msg = &mt('Once the following tasks are complete:')." \n".
8964: join(", ",sort(values(%locks)))."\n";
8965: if (&show_course()) {
8966: $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
8967: } else {
8968: $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
8969: }
8970: } else {
8971: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
8972: $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
8973: }
8974: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
8975: $newurl = '/adm/switchserver?otherserver='.$newserver;
8976: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
8977: $newurl .= '&role='.$env{'request.role'};
8978: }
8979: if ($env{'request.symb'}) {
8980: my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
8981: if ($shownsymb =~ m{^/enc/}) {
8982: my $reqdmajor = 2;
8983: my $reqdminor = 11;
8984: my $reqdsubminor = 3;
8985: my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
8986: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
8987: my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
8988: if (($major eq '' && $minor eq '') ||
8989: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
8990: (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
8991: ($reqdsubminor > $subminor))))) {
8992: undef($shownsymb);
8993: }
8994: }
8995: if ($shownsymb) {
8996: &js_escape(\$shownsymb);
8997: $newurl .= '&symb='.$shownsymb;
8998: }
8999: } else {
9000: my $shownurl = &Apache::lonenc::check_encrypt($requrl);
9001: &js_escape(\$shownurl);
9002: $newurl .= '&origurl='.$shownurl;
9003: }
9004: }
9005: &js_escape(\$msg);
9006: $result.=<<OFFLOAD
9007: <meta http-equiv="pragma" content="no-cache" />
9008: <script type="text/javascript">
9009: // <![CDATA[
9010: function LC_Offload_Now() {
9011: var dest = "$newurl";
9012: if (dest != '') {
9013: window.location.href="$newurl";
9014: }
9015: }
9016: \$(document).ready(function () {
9017: window.alert('$msg');
9018: if ($disable_submit) {
9019: \$(".LC_hwk_submit").prop("disabled", true);
9020: \$( ".LC_textline" ).prop( "readonly", "readonly");
9021: }
9022: setTimeout('LC_Offload_Now()', $timeout);
9023: });
9024: // ]]>
9025: </script>
9026: OFFLOAD
9027: }
9028: }
9029: }
9030: }
9031: }
9032: }
9033: if (!defined($title)) {
9034: $title = 'The LearningOnline Network with CAPA';
9035: }
9036: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
9037: $result .= '<title> LON-CAPA '.$title.'</title>'
9038: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
9039: if (!$args->{'frameset'}) {
9040: $result .= ' /';
9041: }
9042: $result .= '>'
9043: .$inhibitprint
9044: .$head_extra;
9045: my $clientmobile;
9046: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
9047: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
9048: } else {
9049: $clientmobile = $env{'browser.mobile'};
9050: }
9051: if ($clientmobile) {
9052: $result .= '
9053: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
9054: <meta name="apple-mobile-web-app-capable" content="yes" />';
9055: }
9056: $result .= '<meta name="google" content="notranslate" />'."\n";
9057: return $result.'</head>';
9058: }
9059:
9060: =pod
9061:
9062: =item * &font_settings()
9063:
9064: Returns neccessary <meta> to set the proper encoding
9065:
9066: Inputs: optional reference to HASH -- $args passed to &headtag()
9067:
9068: =cut
9069:
9070: sub font_settings {
9071: my ($args) = @_;
9072: my $headerstring='';
9073: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
9074: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
9075: $headerstring.=
9076: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
9077: if (!$args->{'frameset'}) {
9078: $headerstring.= ' /';
9079: }
9080: $headerstring .= '>'."\n";
9081: }
9082: return $headerstring;
9083: }
9084:
9085: =pod
9086:
9087: =item * &print_suppression()
9088:
9089: In course context returns css which causes the body to be blank when media="print",
9090: if printout generation is unavailable for the current resource.
9091:
9092: This could be because:
9093:
9094: (a) printstartdate is in the future
9095:
9096: (b) printenddate is in the past
9097:
9098: (c) there is an active exam block with "printout"
9099: functionality blocked
9100:
9101: Users with pav, pfo or evb privileges are exempt.
9102:
9103: Inputs: none
9104:
9105: =cut
9106:
9107:
9108: sub print_suppression {
9109: my $noprint;
9110: if ($env{'request.course.id'}) {
9111: my $scope = $env{'request.course.id'};
9112: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9113: (&Apache::lonnet::allowed('pfo',$scope))) {
9114: return;
9115: }
9116: if ($env{'request.course.sec'} ne '') {
9117: $scope .= "/$env{'request.course.sec'}";
9118: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9119: (&Apache::lonnet::allowed('pfo',$scope))) {
9120: return;
9121: }
9122: }
9123: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9124: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9125: my $clientip = &Apache::lonnet::get_requestor_ip();
9126: my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
9127: if ($blocked) {
9128: my $checkrole = "cm./$cdom/$cnum";
9129: if ($env{'request.course.sec'} ne '') {
9130: $checkrole .= "/$env{'request.course.sec'}";
9131: }
9132: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
9133: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
9134: $noprint = 1;
9135: }
9136: }
9137: unless ($noprint) {
9138: my $symb = &Apache::lonnet::symbread();
9139: if ($symb ne '') {
9140: my $navmap = Apache::lonnavmaps::navmap->new();
9141: if (ref($navmap)) {
9142: my $res = $navmap->getBySymb($symb);
9143: if (ref($res)) {
9144: if (!$res->resprintable()) {
9145: $noprint = 1;
9146: }
9147: }
9148: }
9149: }
9150: }
9151: if ($noprint) {
9152: return <<"ENDSTYLE";
9153: <style type="text/css" media="print">
9154: body { display:none }
9155: </style>
9156: ENDSTYLE
9157: }
9158: }
9159: return;
9160: }
9161:
9162: =pod
9163:
9164: =item * &xml_begin()
9165:
9166: Returns the needed doctype and <html>
9167:
9168: Inputs: none
9169:
9170: =cut
9171:
9172: sub xml_begin {
9173: my ($is_frameset) = @_;
9174: my $output='';
9175:
9176: if ($env{'browser.mathml'}) {
9177: $output='<?xml version="1.0"?>'
9178: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
9179: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
9180:
9181: # .'<!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">] >'
9182: .'<!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">'
9183: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
9184: .'xmlns="http://www.w3.org/1999/xhtml">';
9185: } elsif ($is_frameset) {
9186: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
9187: '<html>'."\n";
9188: } else {
9189: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
9190: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
9191: }
9192: return $output;
9193: }
9194:
9195: =pod
9196:
9197: =item * &start_page()
9198:
9199: Returns a complete <html> .. <body> section for LON-CAPA web pages.
9200:
9201: Inputs:
9202:
9203: =over 4
9204:
9205: $title - optional title for the page
9206:
9207: $head_extra - optional extra HTML to incude inside the <head>
9208:
9209: $args - additional optional args supported are:
9210:
9211: =over 8
9212:
9213: only_body -> is true will set &bodytag() onlybodytag
9214: arg on
9215: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
9216: add_entries -> additional attributes to add to the <body>
9217: domain -> force to color decorate a page for a
9218: specific domain
9219: function -> force usage of a specific rolish color
9220: scheme
9221: redirect -> see &headtag()
9222: bgcolor -> override the default page bg color
9223: js_ready -> return a string ready for being used in
9224: a javascript writeln
9225: html_encode -> return a string ready for being used in
9226: a html attribute
9227: force_register -> if is true will turn on the &bodytag()
9228: $forcereg arg
9229: frameset -> if true will start with a <frameset>
9230: rather than <body>
9231: skip_phases -> hash ref of
9232: head -> skip the <html><head> generation
9233: body -> skip all <body> generation
9234: no_inline_link -> if true and in remote mode, don't show the
9235: 'Switch To Inline Menu' link
9236: no_auto_mt_title -> prevent &mt()ing the title arg
9237: bread_crumbs -> Array containing breadcrumbs
9238: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
9239: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
9240: to lonhtmlcommon::breadcrumbs
9241: group -> includes the current group, if page is for a
9242: specific group
9243: use_absolute -> for request for external resource or syllabus, this
9244: will contain https://<hostname> if server uses
9245: https (as per hosts.tab), but request is for http
9246: hostname -> hostname, originally from $r->hostname(), (optional).
9247: links_disabled -> Links in primary and secondary menus are disabled
9248: (Can enable them once page has loaded - see lonroles.pm
9249: for an example).
9250: links_target -> Target for links, e.g., _parent (optional).
9251:
9252: =back
9253:
9254: =back
9255:
9256: =cut
9257:
9258: sub start_page {
9259: my ($title,$head_extra,$args) = @_;
9260: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
9261:
9262: $env{'internal.start_page'}++;
9263: my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
9264:
9265: if (! exists($args->{'skip_phases'}{'head'}) ) {
9266: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
9267: }
9268:
9269: if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
9270: if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
9271: unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
9272: $args->{'no_primary_menu'} = 1;
9273: }
9274: unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
9275: $args->{'no_inline_menu'} = 1;
9276: }
9277: if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
9278: map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
9279: }
9280: } else {
9281: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9282: my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
9283: if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
9284: unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
9285: $args->{'no_primary_menu'} = 1;
9286: }
9287: unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
9288: $args->{'no_inline_menu'} = 1;
9289: }
9290: if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
9291: map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
9292: }
9293: }
9294: }
9295: ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
9296: $env{'course.'.$env{'request.course.id'}.'.domain'},
9297: $env{'course.'.$env{'request.course.id'}.'.num'});
9298: } elsif ($env{'request.course.id'}) {
9299: my $expiretime=600;
9300: if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
9301: &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
9302: }
9303: my ($deeplinkmenu,$menuref);
9304: ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
9305: if ($menucoll) {
9306: if (ref($menuref) eq 'HASH') {
9307: %menu = %{$menuref};
9308: }
9309: if ($menu{'top'} eq 'n') {
9310: $args->{'no_primary_menu'} = 1;
9311: }
9312: if ($menu{'inline'} eq 'n') {
9313: unless (&Apache::lonnet::allowed('opa')) {
9314: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9315: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9316: my $crstype = &course_type();
9317: my $now = time;
9318: my $ccrole;
9319: if ($crstype eq 'Community') {
9320: $ccrole = 'co';
9321: } else {
9322: $ccrole = 'cc';
9323: }
9324: if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
9325: my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
9326: if ((($start) && ($start<0)) ||
9327: (($end) && ($end<$now)) ||
9328: (($start) && ($now<$start))) {
9329: $args->{'no_inline_menu'} = 1;
9330: }
9331: } else {
9332: $args->{'no_inline_menu'} = 1;
9333: }
9334: }
9335: }
9336: }
9337: }
9338:
9339: my $showncrumbs;
9340: if (! exists($args->{'skip_phases'}{'body'}) ) {
9341: if ($args->{'frameset'}) {
9342: my $attr_string = &make_attr_string($args->{'force_register'},
9343: $args->{'add_entries'});
9344: $result .= "\n<frameset $attr_string>\n";
9345: } else {
9346: $result .=
9347: &bodytag($title,
9348: $args->{'function'}, $args->{'add_entries'},
9349: $args->{'only_body'}, $args->{'domain'},
9350: $args->{'force_register'}, $args->{'no_nav_bar'},
9351: $args->{'bgcolor'}, $args->{'no_inline_link'},
9352: $args, \@advtools,
9353: $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
9354: }
9355: }
9356:
9357: if ($args->{'js_ready'}) {
9358: $result = &js_ready($result);
9359: }
9360: if ($args->{'html_encode'}) {
9361: $result = &html_encode($result);
9362: }
9363:
9364: # Preparation for new and consistent functionlist at top of screen
9365: # if ($args->{'functionlist'}) {
9366: # $result .= &build_functionlist();
9367: #}
9368:
9369: # Don't add anything more if only_body wanted or in const space
9370: return $result if $args->{'only_body'}
9371: || $env{'request.state'} eq 'construct';
9372:
9373: #Breadcrumbs
9374: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
9375: unless ($showncrumbs) {
9376: &Apache::lonhtmlcommon::clear_breadcrumbs();
9377: #if any br links exists, add them to the breadcrumbs
9378: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
9379: foreach my $crumb (@{$args->{'bread_crumbs'}}){
9380: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
9381: }
9382: }
9383: # if @advtools array contains items add then to the breadcrumbs
9384: if (@advtools > 0) {
9385: &Apache::lonmenu::advtools_crumbs(@advtools);
9386: }
9387: my $menulink;
9388: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
9389: if ((exists($args->{'bread_crumbs_nomenu'})) ||
9390: ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
9391: $menulink = 0;
9392: } else {
9393: undef($menulink);
9394: }
9395: my $linkprotout;
9396: if ($env{'request.deeplink.login'}) {
9397: my $linkprotout = &Apache::lonmenu::linkprot_exit();
9398: if ($linkprotout) {
9399: &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
9400: }
9401: }
9402: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
9403: if(exists($args->{'bread_crumbs_component'})){
9404: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
9405: } else {
9406: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
9407: }
9408: }
9409: } elsif (($env{'environment.remote'} eq 'on') &&
9410: ($env{'form.inhibitmenu'} ne 'yes') &&
9411: ($env{'request.noversionuri'} =~ m{^/res/}) &&
9412: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
9413: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
9414: }
9415: return $result;
9416: }
9417:
9418: sub end_page {
9419: my ($args) = @_;
9420: $env{'internal.end_page'}++;
9421: my $result;
9422: if ($args->{'discussion'}) {
9423: my ($target,$parser);
9424: if (ref($args->{'discussion'})) {
9425: ($target,$parser) =($args->{'discussion'}{'target'},
9426: $args->{'discussion'}{'parser'});
9427: }
9428: $result .= &Apache::lonxml::xmlend($target,$parser);
9429: }
9430: if ($args->{'frameset'}) {
9431: $result .= '</frameset>';
9432: } else {
9433: $result .= &endbodytag($args);
9434: }
9435: unless ($args->{'notbody'}) {
9436: $result .= "\n</html>";
9437: }
9438:
9439: if ($args->{'js_ready'}) {
9440: $result = &js_ready($result);
9441: }
9442:
9443: if ($args->{'html_encode'}) {
9444: $result = &html_encode($result);
9445: }
9446:
9447: return $result;
9448: }
9449:
9450: sub menucoll_in_effect {
9451: my ($menucoll,$deeplinkmenu,%menu);
9452: if ($env{'request.course.id'}) {
9453: $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
9454: if ($env{'request.deeplink.login'}) {
9455: my ($deeplink_symb,$deeplink,$check_login_symb);
9456: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9457: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9458: if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
9459: if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
9460: my $navmap = Apache::lonnavmaps::navmap->new();
9461: if (ref($navmap)) {
9462: $deeplink = $navmap->get_mapparam(undef,
9463: &Apache::lonnet::declutter($env{'request.noversionuri'}),
9464: '0.deeplink');
9465: } else {
9466: $check_login_symb = 1;
9467: }
9468: } else {
9469: my $symb=&Apache::lonnet::symbread();
9470: if ($symb) {
9471: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
9472: } else {
9473: $check_login_symb = 1;
9474: }
9475: }
9476: } else {
9477: $check_login_symb = 1;
9478: }
9479: if ($check_login_symb) {
9480: $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
9481: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9482: my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
9483: my $navmap = Apache::lonnavmaps::navmap->new();
9484: if (ref($navmap)) {
9485: $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
9486: }
9487: } else {
9488: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
9489: }
9490: }
9491: if ($deeplink ne '') {
9492: my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
9493: if ($display =~ /^\d+$/) {
9494: $deeplinkmenu = 1;
9495: $menucoll = $display;
9496: }
9497: }
9498: }
9499: if ($menucoll) {
9500: %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
9501: }
9502: }
9503: return ($menucoll,$deeplinkmenu,\%menu);
9504: }
9505:
9506: sub deeplink_login_symb {
9507: my ($cnum,$cdom) = @_;
9508: my $login_symb;
9509: if ($env{'request.deeplink.login'}) {
9510: $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
9511: }
9512: return $login_symb;
9513: }
9514:
9515: sub symb_from_tinyurl {
9516: my ($url,$cnum,$cdom) = @_;
9517: if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
9518: my $key = $1;
9519: my ($tinyurl,$login);
9520: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
9521: if (defined($cached)) {
9522: $tinyurl = $result;
9523: } else {
9524: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
9525: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
9526: if ($currtiny{$key} ne '') {
9527: $tinyurl = $currtiny{$key};
9528: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
9529: }
9530: }
9531: if ($tinyurl ne '') {
9532: my ($cnumreq,$symb) = split(/\&/,$tinyurl);
9533: if (wantarray) {
9534: return ($cnumreq,$symb);
9535: } elsif ($cnumreq eq $cnum) {
9536: return $symb;
9537: }
9538: }
9539: }
9540: if (wantarray) {
9541: return ();
9542: } else {
9543: return;
9544: }
9545: }
9546:
9547: sub usable_exttools {
9548: my %tooltypes;
9549: if ($env{'request.course.id'}) {
9550: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
9551: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
9552: %tooltypes = (
9553: crs => 1,
9554: dom => 1,
9555: );
9556: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
9557: $tooltypes{'crs'} = 1;
9558: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
9559: $tooltypes{'dom'} = 1;
9560: }
9561: } else {
9562: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9563: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9564: my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
9565: if ($crstype eq '') {
9566: $crstype = 'course';
9567: }
9568: if ($crstype eq 'course') {
9569: if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
9570: $crstype = 'official';
9571: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
9572: $crstype = 'textbook';
9573: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
9574: $crstype = 'lti';
9575: } else {
9576: $crstype = 'unofficial';
9577: }
9578: }
9579: my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
9580: if ($domdefaults{$crstype.'domexttool'}) {
9581: $tooltypes{'dom'} = 1;
9582: }
9583: if ($domdefaults{$crstype.'exttool'}) {
9584: $tooltypes{'crs'} = 1;
9585: }
9586: }
9587: }
9588: return %tooltypes;
9589: }
9590:
9591: sub wishlist_window {
9592: return(<<'ENDWISHLIST');
9593: <script type="text/javascript">
9594: // <![CDATA[
9595: // <!-- BEGIN LON-CAPA Internal
9596: function set_wishlistlink(title, path) {
9597: if (!title) {
9598: title = document.title;
9599: title = title.replace(/^LON-CAPA /,'');
9600: }
9601: title = encodeURIComponent(title);
9602: title = title.replace("'","\\\'");
9603: if (!path) {
9604: path = location.pathname;
9605: }
9606: path = encodeURIComponent(path);
9607: path = path.replace("'","\\\'");
9608: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
9609: 'wishlistNewLink','width=560,height=350,scrollbars=0');
9610: }
9611: // END LON-CAPA Internal -->
9612: // ]]>
9613: </script>
9614: ENDWISHLIST
9615: }
9616:
9617: sub modal_window {
9618: return(<<'ENDMODAL');
9619: <script type="text/javascript">
9620: // <![CDATA[
9621: // <!-- BEGIN LON-CAPA Internal
9622: var modalWindow = {
9623: parent:"body",
9624: windowId:null,
9625: content:null,
9626: width:null,
9627: height:null,
9628: close:function()
9629: {
9630: $(".LCmodal-window").remove();
9631: $(".LCmodal-overlay").remove();
9632: },
9633: open:function()
9634: {
9635: var modal = "";
9636: modal += "<div class=\"LCmodal-overlay\"></div>";
9637: 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;\">";
9638: modal += this.content;
9639: modal += "</div>";
9640:
9641: $(this.parent).append(modal);
9642:
9643: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
9644: $(".LCclose-window").click(function(){modalWindow.close();});
9645: $(".LCmodal-overlay").click(function(){modalWindow.close();});
9646: }
9647: };
9648: var openMyModal = function(source,width,height,scrolling,transparency,style)
9649: {
9650: source = source.replace(/'/g,"'");
9651: modalWindow.windowId = "myModal";
9652: modalWindow.width = width;
9653: modalWindow.height = height;
9654: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
9655: modalWindow.open();
9656: };
9657: // END LON-CAPA Internal -->
9658: // ]]>
9659: </script>
9660: ENDMODAL
9661: }
9662:
9663: sub modal_link {
9664: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
9665: unless ($width) { $width=480; }
9666: unless ($height) { $height=400; }
9667: unless ($scrolling) { $scrolling='yes'; }
9668: unless ($transparency) { $transparency='true'; }
9669:
9670: my $target_attr;
9671: if (defined($target)) {
9672: $target_attr = 'target="'.$target.'"';
9673: }
9674: return <<"ENDLINK";
9675: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
9676: ENDLINK
9677: }
9678:
9679: sub modal_adhoc_script {
9680: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9681: my $mathjax;
9682: if ($possmathjax) {
9683: $mathjax = <<'ENDJAX';
9684: if (typeof MathJax == 'object') {
9685: MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
9686: }
9687: ENDJAX
9688: }
9689: return (<<ENDADHOC);
9690: <script type="text/javascript">
9691: // <![CDATA[
9692: var $funcname = function()
9693: {
9694: modalWindow.windowId = "myModal";
9695: modalWindow.width = $width;
9696: modalWindow.height = $height;
9697: modalWindow.content = '$content';
9698: modalWindow.open();
9699: $mathjax
9700: };
9701: // ]]>
9702: </script>
9703: ENDADHOC
9704: }
9705:
9706: sub modal_adhoc_inner {
9707: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9708: my $innerwidth=$width-20;
9709: $content=&js_ready(
9710: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
9711: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
9712: $content.
9713: &end_scrollbox().
9714: &end_page()
9715: );
9716: return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
9717: }
9718:
9719: sub modal_adhoc_window {
9720: my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
9721: return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
9722: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
9723: }
9724:
9725: sub modal_adhoc_launch {
9726: my ($funcname,$width,$height,$content)=@_;
9727: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
9728: <script type="text/javascript">
9729: // <![CDATA[
9730: $funcname();
9731: // ]]>
9732: </script>
9733: ENDLAUNCH
9734: }
9735:
9736: sub modal_adhoc_close {
9737: return (<<ENDCLOSE);
9738: <script type="text/javascript">
9739: // <![CDATA[
9740: modalWindow.close();
9741: // ]]>
9742: </script>
9743: ENDCLOSE
9744: }
9745:
9746: sub togglebox_script {
9747: return(<<ENDTOGGLE);
9748: <script type="text/javascript">
9749: // <![CDATA[
9750: function LCtoggleDisplay(id,hidetext,showtext) {
9751: link = document.getElementById(id + "link").childNodes[0];
9752: with (document.getElementById(id).style) {
9753: if (display == "none" ) {
9754: display = "inline";
9755: link.nodeValue = hidetext;
9756: } else {
9757: display = "none";
9758: link.nodeValue = showtext;
9759: }
9760: }
9761: }
9762: // ]]>
9763: </script>
9764: ENDTOGGLE
9765: }
9766:
9767: sub start_togglebox {
9768: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
9769: unless ($heading) { $heading=''; } else { $heading.=' '; }
9770: unless ($showtext) { $showtext=&mt('show'); }
9771: unless ($hidetext) { $hidetext=&mt('hide'); }
9772: unless ($headerbg) { $headerbg='#FFFFFF'; }
9773: return &start_data_table().
9774: &start_data_table_header_row().
9775: '<td bgcolor="'.$headerbg.'">'.$heading.
9776: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
9777: $showtext.'\')">'.$showtext.'</a>]</td>'.
9778: &end_data_table_header_row().
9779: '<tr id="'.$id.'" style="display:none""><td>';
9780: }
9781:
9782: sub end_togglebox {
9783: return '</td></tr>'.&end_data_table();
9784: }
9785:
9786: sub LCprogressbar_script {
9787: my ($id,$number_to_do)=@_;
9788: if ($number_to_do) {
9789: return(<<ENDPROGRESS);
9790: <script type="text/javascript">
9791: // <![CDATA[
9792: \$('#progressbar$id').progressbar({
9793: value: 0,
9794: change: function(event, ui) {
9795: var newVal = \$(this).progressbar('option', 'value');
9796: \$('.pblabel', this).text(LCprogressTxt);
9797: }
9798: });
9799: // ]]>
9800: </script>
9801: ENDPROGRESS
9802: } else {
9803: return(<<ENDPROGRESS);
9804: <script type="text/javascript">
9805: // <![CDATA[
9806: \$('#progressbar$id').progressbar({
9807: value: false,
9808: create: function(event, ui) {
9809: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
9810: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
9811: }
9812: });
9813: // ]]>
9814: </script>
9815: ENDPROGRESS
9816: }
9817: }
9818:
9819: sub LCprogressbarUpdate_script {
9820: return(<<ENDPROGRESSUPDATE);
9821: <style type="text/css">
9822: .ui-progressbar { position:relative; }
9823: .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%; }
9824: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
9825: </style>
9826: <script type="text/javascript">
9827: // <![CDATA[
9828: var LCprogressTxt='---';
9829:
9830: function LCupdateProgress(percent,progresstext,id,maxnum) {
9831: LCprogressTxt=progresstext;
9832: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
9833: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
9834: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
9835: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
9836: } else {
9837: \$('#progressbar'+id).progressbar('value',percent);
9838: }
9839: }
9840: // ]]>
9841: </script>
9842: ENDPROGRESSUPDATE
9843: }
9844:
9845: my $LClastpercent;
9846: my $LCidcnt;
9847: my $LCcurrentid;
9848:
9849: sub LCprogressbar {
9850: my ($r,$number_to_do,$preamble)=@_;
9851: $LClastpercent=0;
9852: $LCidcnt++;
9853: $LCcurrentid=$$.'_'.$LCidcnt;
9854: my ($starting,$content);
9855: if ($number_to_do) {
9856: $starting=&mt('Starting');
9857: $content=(<<ENDPROGBAR);
9858: $preamble
9859: <div id="progressbar$LCcurrentid">
9860: <span class="pblabel">$starting</span>
9861: </div>
9862: ENDPROGBAR
9863: } else {
9864: $starting=&mt('Loading...');
9865: $LClastpercent='false';
9866: $content=(<<ENDPROGBAR);
9867: $preamble
9868: <div id="progressbar$LCcurrentid">
9869: <div class="progress-label">$starting</div>
9870: </div>
9871: ENDPROGBAR
9872: }
9873: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
9874: }
9875:
9876: sub LCprogressbarUpdate {
9877: my ($r,$val,$text,$number_to_do)=@_;
9878: if ($number_to_do) {
9879: unless ($val) {
9880: if ($LClastpercent) {
9881: $val=$LClastpercent;
9882: } else {
9883: $val=0;
9884: }
9885: }
9886: if ($val<0) { $val=0; }
9887: if ($val>100) { $val=0; }
9888: $LClastpercent=$val;
9889: unless ($text) { $text=$val.'%'; }
9890: } else {
9891: $val = 'false';
9892: }
9893: $text=&js_ready($text);
9894: &r_print($r,<<ENDUPDATE);
9895: <script type="text/javascript">
9896: // <![CDATA[
9897: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
9898: // ]]>
9899: </script>
9900: ENDUPDATE
9901: }
9902:
9903: sub LCprogressbarClose {
9904: my ($r)=@_;
9905: $LClastpercent=0;
9906: &r_print($r,<<ENDCLOSE);
9907: <script type="text/javascript">
9908: // <![CDATA[
9909: \$("#progressbar$LCcurrentid").hide('slow');
9910: // ]]>
9911: </script>
9912: ENDCLOSE
9913: }
9914:
9915: sub r_print {
9916: my ($r,$to_print)=@_;
9917: if ($r) {
9918: $r->print($to_print);
9919: $r->rflush();
9920: } else {
9921: print($to_print);
9922: }
9923: }
9924:
9925: sub html_encode {
9926: my ($result) = @_;
9927:
9928: $result = &HTML::Entities::encode($result,'<>&"');
9929:
9930: return $result;
9931: }
9932:
9933: sub js_ready {
9934: my ($result) = @_;
9935:
9936: $result =~ s/[\n\r]/ /xmsg;
9937: $result =~ s/\\/\\\\/xmsg;
9938: $result =~ s/'/\\'/xmsg;
9939: $result =~ s{</}{<\\/}xmsg;
9940:
9941: return $result;
9942: }
9943:
9944: sub validate_page {
9945: if ( exists($env{'internal.start_page'})
9946: && $env{'internal.start_page'} > 1) {
9947: &Apache::lonnet::logthis('start_page called multiple times '.
9948: $env{'internal.start_page'}.' '.
9949: $ENV{'request.filename'});
9950: }
9951: if ( exists($env{'internal.end_page'})
9952: && $env{'internal.end_page'} > 1) {
9953: &Apache::lonnet::logthis('end_page called multiple times '.
9954: $env{'internal.end_page'}.' '.
9955: $env{'request.filename'});
9956: }
9957: if ( exists($env{'internal.start_page'})
9958: && ! exists($env{'internal.end_page'})) {
9959: &Apache::lonnet::logthis('start_page called without end_page '.
9960: $env{'request.filename'});
9961: }
9962: if ( ! exists($env{'internal.start_page'})
9963: && exists($env{'internal.end_page'})) {
9964: &Apache::lonnet::logthis('end_page called without start_page'.
9965: $env{'request.filename'});
9966: }
9967: }
9968:
9969:
9970: sub start_scrollbox {
9971: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
9972: unless ($outerwidth) { $outerwidth='520px'; }
9973: unless ($width) { $width='500px'; }
9974: unless ($height) { $height='200px'; }
9975: my ($table_id,$div_id,$tdcol);
9976: if ($id ne '') {
9977: $table_id = ' id="table_'.$id.'"';
9978: $div_id = ' id="div_'.$id.'"';
9979: }
9980: if ($bgcolor ne '') {
9981: $tdcol = "background-color: $bgcolor;";
9982: }
9983: my $nicescroll_js;
9984: if ($env{'browser.mobile'}) {
9985: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
9986: }
9987: return <<"END";
9988: $nicescroll_js
9989:
9990: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
9991: <div style="overflow:auto; width:$width; height:$height;"$div_id>
9992: END
9993: }
9994:
9995: sub end_scrollbox {
9996: return '</div></td></tr></table>';
9997: }
9998:
9999: sub nicescroll_javascript {
10000: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10001: my %options;
10002: if (ref($cursor) eq 'HASH') {
10003: %options = %{$cursor};
10004: }
10005: unless ($options{'railalign'} =~ /^left|right$/) {
10006: $options{'railalign'} = 'left';
10007: }
10008: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10009: my $function = &get_users_function();
10010: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10011: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10012: $options{'cursorcolor'} = '#00F';
10013: }
10014: }
10015: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10016: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10017: $options{'cursoropacity'}='1.0';
10018: }
10019: } else {
10020: $options{'cursoropacity'}='1.0';
10021: }
10022: if ($options{'cursorfixedheight'} eq 'none') {
10023: delete($options{'cursorfixedheight'});
10024: } else {
10025: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10026: }
10027: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10028: delete($options{'railoffset'});
10029: }
10030: my @niceoptions;
10031: while (my($key,$value) = each(%options)) {
10032: if ($value =~ /^\{.+\}$/) {
10033: push(@niceoptions,$key.':'.$value);
10034: } else {
10035: push(@niceoptions,$key.':"'.$value.'"');
10036: }
10037: }
10038: my $nicescroll_js = '
10039: $(document).ready(
10040: function() {
10041: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10042: }
10043: );
10044: ';
10045: if ($framecheck) {
10046: $nicescroll_js .= '
10047: function expand_div(caller) {
10048: if (top === self) {
10049: document.getElementById("'.$id.'").style.width = "auto";
10050: document.getElementById("'.$id.'").style.height = "auto";
10051: } else {
10052: try {
10053: if (parent.frames) {
10054: if (parent.frames.length > 1) {
10055: var framesrc = parent.frames[1].location.href;
10056: var currsrc = framesrc.replace(/\#.*$/,"");
10057: if ((caller == "search") || (currsrc == "'.$location.'")) {
10058: document.getElementById("'.$id.'").style.width = "auto";
10059: document.getElementById("'.$id.'").style.height = "auto";
10060: }
10061: }
10062: }
10063: } catch (e) {
10064: return;
10065: }
10066: }
10067: return;
10068: }
10069: ';
10070: }
10071: if ($needjsready) {
10072: $nicescroll_js = '
10073: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10074: } else {
10075: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10076: }
10077: return $nicescroll_js;
10078: }
10079:
10080: sub simple_error_page {
10081: my ($r,$title,$msg,$args) = @_;
10082: my %displayargs;
10083: if (ref($args) eq 'HASH') {
10084: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10085: if ($args->{'only_body'}) {
10086: $displayargs{'only_body'} = 1;
10087: }
10088: if ($args->{'no_nav_bar'}) {
10089: $displayargs{'no_nav_bar'} = 1;
10090: }
10091: } else {
10092: $msg = &mt($msg);
10093: }
10094:
10095: my $page =
10096: &Apache::loncommon::start_page($title,'',\%displayargs).
10097: '<p class="LC_error">'.$msg.'</p>'.
10098: &Apache::loncommon::end_page();
10099: if (ref($r)) {
10100: $r->print($page);
10101: return;
10102: }
10103: return $page;
10104: }
10105:
10106: {
10107: my @row_count;
10108:
10109: sub start_data_table_count {
10110: unshift(@row_count, 0);
10111: return;
10112: }
10113:
10114: sub end_data_table_count {
10115: shift(@row_count);
10116: return;
10117: }
10118:
10119: sub start_data_table {
10120: my ($add_class,$id) = @_;
10121: my $css_class = (join(' ','LC_data_table',$add_class));
10122: my $table_id;
10123: if (defined($id)) {
10124: $table_id = ' id="'.$id.'"';
10125: }
10126: &start_data_table_count();
10127: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10128: }
10129:
10130: sub end_data_table {
10131: &end_data_table_count();
10132: return '</table>'."\n";;
10133: }
10134:
10135: sub start_data_table_row {
10136: my ($add_class, $id) = @_;
10137: $row_count[0]++;
10138: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10139: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10140: $id = (' id="'.$id.'"') unless ($id eq '');
10141: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10142: }
10143:
10144: sub continue_data_table_row {
10145: my ($add_class, $id) = @_;
10146: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10147: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10148: $id = (' id="'.$id.'"') unless ($id eq '');
10149: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10150: }
10151:
10152: sub end_data_table_row {
10153: return '</tr>'."\n";;
10154: }
10155:
10156: sub start_data_table_empty_row {
10157: # $row_count[0]++;
10158: return '<tr class="LC_empty_row" >'."\n";;
10159: }
10160:
10161: sub end_data_table_empty_row {
10162: return '</tr>'."\n";;
10163: }
10164:
10165: sub start_data_table_header_row {
10166: return '<tr class="LC_header_row">'."\n";;
10167: }
10168:
10169: sub end_data_table_header_row {
10170: return '</tr>'."\n";;
10171: }
10172:
10173: sub data_table_caption {
10174: my $caption = shift;
10175: return "<caption class=\"LC_caption\">$caption</caption>";
10176: }
10177: }
10178:
10179: =pod
10180:
10181: =item * &inhibit_menu_check($arg)
10182:
10183: Checks for a inhibitmenu state and generates output to preserve it
10184:
10185: Inputs: $arg - can be any of
10186: - undef - in which case the return value is a string
10187: to add into arguments list of a uri
10188: - 'input' - in which case the return value is a HTML
10189: <form> <input> field of type hidden to
10190: preserve the value
10191: - a url - in which case the return value is the url with
10192: the neccesary cgi args added to preserve the
10193: inhibitmenu state
10194: - a ref to a url - no return value, but the string is
10195: updated to include the neccessary cgi
10196: args to preserve the inhibitmenu state
10197:
10198: =cut
10199:
10200: sub inhibit_menu_check {
10201: my ($arg) = @_;
10202: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10203: if ($arg eq 'input') {
10204: if ($env{'form.inhibitmenu'}) {
10205: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10206: } else {
10207: return
10208: }
10209: }
10210: if ($env{'form.inhibitmenu'}) {
10211: if (ref($arg)) {
10212: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10213: } elsif ($arg eq '') {
10214: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10215: } else {
10216: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10217: }
10218: }
10219: if (!ref($arg)) {
10220: return $arg;
10221: }
10222: }
10223:
10224: ###############################################
10225:
10226: =pod
10227:
10228: =back
10229:
10230: =head1 User Information Routines
10231:
10232: =over 4
10233:
10234: =item * &get_users_function()
10235:
10236: Used by &bodytag to determine the current users primary role.
10237: Returns either 'student','coordinator','admin', or 'author'.
10238:
10239: =cut
10240:
10241: ###############################################
10242: sub get_users_function {
10243: my $function = 'norole';
10244: if ($env{'request.role'}=~/^(st)/) {
10245: $function='student';
10246: }
10247: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10248: $function='coordinator';
10249: }
10250: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10251: $function='admin';
10252: }
10253: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10254: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10255: $function='author';
10256: }
10257: return $function;
10258: }
10259:
10260: ###############################################
10261:
10262: =pod
10263:
10264: =item * &show_course()
10265:
10266: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10267: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10268:
10269: Inputs:
10270: None
10271:
10272: Outputs:
10273: Scalar: 1 if 'Course' to be used, 0 otherwise.
10274:
10275: =cut
10276:
10277: ###############################################
10278: sub show_course {
10279: my $course = !$env{'user.adv'};
10280: if (!$env{'user.adv'}) {
10281: foreach my $env (keys(%env)) {
10282: next if ($env !~ m/^user\.priv\./);
10283: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10284: $course = 0;
10285: last;
10286: }
10287: }
10288: }
10289: return $course;
10290: }
10291:
10292: ###############################################
10293:
10294: =pod
10295:
10296: =item * &check_user_status()
10297:
10298: Determines current status of supplied role for a
10299: specific user. Roles can be active, previous or future.
10300:
10301: Inputs:
10302: user's domain, user's username, course's domain,
10303: course's number, optional section ID.
10304:
10305: Outputs:
10306: role status: active, previous or future.
10307:
10308: =cut
10309:
10310: sub check_user_status {
10311: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10312: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10313: my @uroles = keys(%userinfo);
10314: my $srchstr;
10315: my $active_chk = 'none';
10316: my $now = time;
10317: if (@uroles > 0) {
10318: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10319: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10320: } else {
10321: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10322: }
10323: if (grep/^\Q$srchstr\E$/,@uroles) {
10324: my $role_end = 0;
10325: my $role_start = 0;
10326: $active_chk = 'active';
10327: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10328: $role_end = $1;
10329: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10330: $role_start = $1;
10331: }
10332: }
10333: if ($role_start > 0) {
10334: if ($now < $role_start) {
10335: $active_chk = 'future';
10336: }
10337: }
10338: if ($role_end > 0) {
10339: if ($now > $role_end) {
10340: $active_chk = 'previous';
10341: }
10342: }
10343: }
10344: }
10345: return $active_chk;
10346: }
10347:
10348: ###############################################
10349:
10350: =pod
10351:
10352: =item * &get_sections()
10353:
10354: Determines all the sections for a course including
10355: sections with students and sections containing other roles.
10356: Incoming parameters:
10357:
10358: 1. domain
10359: 2. course number
10360: 3. reference to array containing roles for which sections should
10361: be gathered (optional).
10362: 4. reference to array containing status types for which sections
10363: should be gathered (optional).
10364:
10365: If the third argument is undefined, sections are gathered for any role.
10366: If the fourth argument is undefined, sections are gathered for any status.
10367: Permissible values are 'active' or 'future' or 'previous'.
10368:
10369: Returns section hash (keys are section IDs, values are
10370: number of users in each section), subject to the
10371: optional roles filter, optional status filter
10372:
10373: =cut
10374:
10375: ###############################################
10376: sub get_sections {
10377: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10378: if (!defined($cdom) || !defined($cnum)) {
10379: my $cid = $env{'request.course.id'};
10380:
10381: return if (!defined($cid));
10382:
10383: $cdom = $env{'course.'.$cid.'.domain'};
10384: $cnum = $env{'course.'.$cid.'.num'};
10385: }
10386:
10387: my %sectioncount;
10388: my $now = time;
10389:
10390: my $check_students = 1;
10391: my $only_students = 0;
10392: if (ref($possible_roles) eq 'ARRAY') {
10393: if (grep(/^st$/,@{$possible_roles})) {
10394: if (@{$possible_roles} == 1) {
10395: $only_students = 1;
10396: }
10397: } else {
10398: $check_students = 0;
10399: }
10400: }
10401:
10402: if ($check_students) {
10403: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10404: my $sec_index = &Apache::loncoursedata::CL_SECTION();
10405: my $status_index = &Apache::loncoursedata::CL_STATUS();
10406: my $start_index = &Apache::loncoursedata::CL_START();
10407: my $end_index = &Apache::loncoursedata::CL_END();
10408: my $status;
10409: while (my ($student,$data) = each(%$classlist)) {
10410: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10411: $data->[$status_index],
10412: $data->[$start_index],
10413: $data->[$end_index]);
10414: if ($stu_status eq 'Active') {
10415: $status = 'active';
10416: } elsif ($end < $now) {
10417: $status = 'previous';
10418: } elsif ($start > $now) {
10419: $status = 'future';
10420: }
10421: if ($section ne '-1' && $section !~ /^\s*$/) {
10422: if ((!defined($possible_status)) || (($status ne '') &&
10423: (grep/^\Q$status\E$/,@{$possible_status}))) {
10424: $sectioncount{$section}++;
10425: }
10426: }
10427: }
10428: }
10429: if ($only_students) {
10430: return %sectioncount;
10431: }
10432: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10433: foreach my $user (sort(keys(%courseroles))) {
10434: if ($user !~ /^(\w{2})/) { next; }
10435: my ($role) = ($user =~ /^(\w{2})/);
10436: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10437: my ($section,$status);
10438: if ($role eq 'cr' &&
10439: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10440: $section=$1;
10441: }
10442: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10443: if (!defined($section) || $section eq '-1') { next; }
10444: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10445: if ($end == -1 && $start == -1) {
10446: next; #deleted role
10447: }
10448: if (!defined($possible_status)) {
10449: $sectioncount{$section}++;
10450: } else {
10451: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10452: $status = 'active';
10453: } elsif ($end < $now) {
10454: $status = 'future';
10455: } elsif ($start > $now) {
10456: $status = 'previous';
10457: }
10458: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10459: $sectioncount{$section}++;
10460: }
10461: }
10462: }
10463: return %sectioncount;
10464: }
10465:
10466: ###############################################
10467:
10468: =pod
10469:
10470: =item * &get_course_users()
10471:
10472: Retrieves usernames:domains for users in the specified course
10473: with specific role(s), and access status.
10474:
10475: Incoming parameters:
10476: 1. course domain
10477: 2. course number
10478: 3. access status: users must have - either active,
10479: previous, future, or all.
10480: 4. reference to array of permissible roles
10481: 5. reference to array of section restrictions (optional)
10482: 6. reference to results object (hash of hashes).
10483: 7. reference to optional userdata hash
10484: 8. reference to optional statushash
10485: 9. flag if privileged users (except those set to unhide in
10486: course settings) should be excluded
10487: Keys of top level results hash are roles.
10488: Keys of inner hashes are username:domain, with
10489: values set to access type.
10490: Optional userdata hash returns an array with arguments in the
10491: same order as loncoursedata::get_classlist() for student data.
10492:
10493: Optional statushash returns
10494:
10495: Entries for end, start, section and status are blank because
10496: of the possibility of multiple values for non-student roles.
10497:
10498: =cut
10499:
10500: ###############################################
10501:
10502: sub get_course_users {
10503: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10504: my %idx = ();
10505: my %seclists;
10506:
10507: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10508: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
10509: $idx{end} = &Apache::loncoursedata::CL_END();
10510: $idx{start} = &Apache::loncoursedata::CL_START();
10511: $idx{id} = &Apache::loncoursedata::CL_ID();
10512: $idx{section} = &Apache::loncoursedata::CL_SECTION();
10513: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10514: $idx{status} = &Apache::loncoursedata::CL_STATUS();
10515:
10516: if (grep(/^st$/,@{$roles})) {
10517: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10518: my $now = time;
10519: foreach my $student (keys(%{$classlist})) {
10520: my $match = 0;
10521: my $secmatch = 0;
10522: my $section = $$classlist{$student}[$idx{section}];
10523: my $status = $$classlist{$student}[$idx{status}];
10524: if ($section eq '') {
10525: $section = 'none';
10526: }
10527: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10528: if (grep(/^all$/,@{$sections})) {
10529: $secmatch = 1;
10530: } elsif ($$classlist{$student}[$idx{section}] eq '') {
10531: if (grep(/^none$/,@{$sections})) {
10532: $secmatch = 1;
10533: }
10534: } else {
10535: if (grep(/^\Q$section\E$/,@{$sections})) {
10536: $secmatch = 1;
10537: }
10538: }
10539: if (!$secmatch) {
10540: next;
10541: }
10542: }
10543: if (defined($$types{'active'})) {
10544: if ($$classlist{$student}[$idx{status}] eq 'Active') {
10545: push(@{$$users{st}{$student}},'active');
10546: $match = 1;
10547: }
10548: }
10549: if (defined($$types{'previous'})) {
10550: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10551: push(@{$$users{st}{$student}},'previous');
10552: $match = 1;
10553: }
10554: }
10555: if (defined($$types{'future'})) {
10556: if ($$classlist{$student}[$idx{status}] eq 'Future') {
10557: push(@{$$users{st}{$student}},'future');
10558: $match = 1;
10559: }
10560: }
10561: if ($match) {
10562: push(@{$seclists{$student}},$section);
10563: if (ref($userdata) eq 'HASH') {
10564: $$userdata{$student} = $$classlist{$student};
10565: }
10566: if (ref($statushash) eq 'HASH') {
10567: $statushash->{$student}{'st'}{$section} = $status;
10568: }
10569: }
10570: }
10571: }
10572: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10573: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10574: my $now = time;
10575: my %displaystatus = ( previous => 'Expired',
10576: active => 'Active',
10577: future => 'Future',
10578: );
10579: my (%nothide,@possdoms);
10580: if ($hidepriv) {
10581: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10582: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10583: if ($user !~ /:/) {
10584: $nothide{join(':',split(/[\@]/,$user))}=1;
10585: } else {
10586: $nothide{$user} = 1;
10587: }
10588: }
10589: my @possdoms = ($cdom);
10590: if ($coursehash{'checkforpriv'}) {
10591: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10592: }
10593: }
10594: foreach my $person (sort(keys(%coursepersonnel))) {
10595: my $match = 0;
10596: my $secmatch = 0;
10597: my $status;
10598: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10599: $user =~ s/:$//;
10600: my ($end,$start) = split(/:/,$coursepersonnel{$person});
10601: if ($end == -1 || $start == -1) {
10602: next;
10603: }
10604: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10605: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10606: my ($uname,$udom) = split(/:/,$user);
10607: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10608: if (grep(/^all$/,@{$sections})) {
10609: $secmatch = 1;
10610: } elsif ($usec eq '') {
10611: if (grep(/^none$/,@{$sections})) {
10612: $secmatch = 1;
10613: }
10614: } else {
10615: if (grep(/^\Q$usec\E$/,@{$sections})) {
10616: $secmatch = 1;
10617: }
10618: }
10619: if (!$secmatch) {
10620: next;
10621: }
10622: }
10623: if ($usec eq '') {
10624: $usec = 'none';
10625: }
10626: if ($uname ne '' && $udom ne '') {
10627: if ($hidepriv) {
10628: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10629: (!$nothide{$uname.':'.$udom})) {
10630: next;
10631: }
10632: }
10633: if ($end > 0 && $end < $now) {
10634: $status = 'previous';
10635: } elsif ($start > $now) {
10636: $status = 'future';
10637: } else {
10638: $status = 'active';
10639: }
10640: foreach my $type (keys(%{$types})) {
10641: if ($status eq $type) {
10642: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10643: push(@{$$users{$role}{$user}},$type);
10644: }
10645: $match = 1;
10646: }
10647: }
10648: if (($match) && (ref($userdata) eq 'HASH')) {
10649: if (!exists($$userdata{$uname.':'.$udom})) {
10650: &get_user_info($udom,$uname,\%idx,$userdata);
10651: }
10652: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10653: push(@{$seclists{$uname.':'.$udom}},$usec);
10654: }
10655: if (ref($statushash) eq 'HASH') {
10656: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10657: }
10658: }
10659: }
10660: }
10661: }
10662: if (grep(/^ow$/,@{$roles})) {
10663: if ((defined($cdom)) && (defined($cnum))) {
10664: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10665: if ( defined($csettings{'internal.courseowner'}) ) {
10666: my $owner = $csettings{'internal.courseowner'};
10667: next if ($owner eq '');
10668: my ($ownername,$ownerdom);
10669: if ($owner =~ /^([^:]+):([^:]+)$/) {
10670: $ownername = $1;
10671: $ownerdom = $2;
10672: } else {
10673: $ownername = $owner;
10674: $ownerdom = $cdom;
10675: $owner = $ownername.':'.$ownerdom;
10676: }
10677: @{$$users{'ow'}{$owner}} = 'any';
10678: if (defined($userdata) &&
10679: !exists($$userdata{$owner})) {
10680: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
10681: if (!grep(/^none$/,@{$seclists{$owner}})) {
10682: push(@{$seclists{$owner}},'none');
10683: }
10684: if (ref($statushash) eq 'HASH') {
10685: $statushash->{$owner}{'ow'}{'none'} = 'Any';
10686: }
10687: }
10688: }
10689: }
10690: }
10691: foreach my $user (keys(%seclists)) {
10692: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10693: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10694: }
10695: }
10696: return;
10697: }
10698:
10699: sub get_user_info {
10700: my ($udom,$uname,$idx,$userdata) = @_;
10701: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
10702: &plainname($uname,$udom,'lastname');
10703: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10704: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10705: my %idhash = &Apache::lonnet::idrget($udom,($uname));
10706: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
10707: return;
10708: }
10709:
10710: ###############################################
10711:
10712: =pod
10713:
10714: =item * &get_user_quota()
10715:
10716: Retrieves quota assigned for storage of user files.
10717: Default is to report quota for portfolio files.
10718:
10719: Incoming parameters:
10720: 1. user's username
10721: 2. user's domain
10722: 3. quota name - portfolio, author, or course
10723: (if no quota name provided, defaults to portfolio).
10724: 4. crstype - official, unofficial, textbook or community, if quota name is
10725: course
10726:
10727: Returns:
10728: 1. Disk quota (in MB) assigned to student.
10729: 2. (Optional) Type of setting: custom or default
10730: (individually assigned or default for user's
10731: institutional status).
10732: 3. (Optional) - User's institutional status (e.g., faculty, staff
10733: or student - types as defined in localenroll::inst_usertypes
10734: for user's domain, which determines default quota for user.
10735: 4. (Optional) - Default quota which would apply to the user.
10736:
10737: If a value has been stored in the user's environment,
10738: it will return that, otherwise it returns the maximal default
10739: defined for the user's institutional status(es) in the domain.
10740:
10741: =cut
10742:
10743: ###############################################
10744:
10745:
10746: sub get_user_quota {
10747: my ($uname,$udom,$quotaname,$crstype) = @_;
10748: my ($quota,$quotatype,$settingstatus,$defquota);
10749: if (!defined($udom)) {
10750: $udom = $env{'user.domain'};
10751: }
10752: if (!defined($uname)) {
10753: $uname = $env{'user.name'};
10754: }
10755: if (($udom eq '' || $uname eq '') ||
10756: ($udom eq 'public') && ($uname eq 'public')) {
10757: $quota = 0;
10758: $quotatype = 'default';
10759: $defquota = 0;
10760: } else {
10761: my $inststatus;
10762: if ($quotaname eq 'course') {
10763: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10764: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10765: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10766: } else {
10767: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10768: $quota = $cenv{'internal.uploadquota'};
10769: }
10770: } else {
10771: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10772: if ($quotaname eq 'author') {
10773: $quota = $env{'environment.authorquota'};
10774: } else {
10775: $quota = $env{'environment.portfolioquota'};
10776: }
10777: $inststatus = $env{'environment.inststatus'};
10778: } else {
10779: my %userenv =
10780: &Apache::lonnet::get('environment',['portfolioquota',
10781: 'authorquota','inststatus'],$udom,$uname);
10782: my ($tmp) = keys(%userenv);
10783: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10784: if ($quotaname eq 'author') {
10785: $quota = $userenv{'authorquota'};
10786: } else {
10787: $quota = $userenv{'portfolioquota'};
10788: }
10789: $inststatus = $userenv{'inststatus'};
10790: } else {
10791: undef(%userenv);
10792: }
10793: }
10794: }
10795: if ($quota eq '' || wantarray) {
10796: if ($quotaname eq 'course') {
10797: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10798: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10799: ($crstype eq 'community') || ($crstype eq 'textbook')) {
10800: $defquota = $domdefs{$crstype.'quota'};
10801: }
10802: if ($defquota eq '') {
10803: $defquota = 500;
10804: }
10805: } else {
10806: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10807: }
10808: if ($quota eq '') {
10809: $quota = $defquota;
10810: $quotatype = 'default';
10811: } else {
10812: $quotatype = 'custom';
10813: }
10814: }
10815: }
10816: if (wantarray) {
10817: return ($quota,$quotatype,$settingstatus,$defquota);
10818: } else {
10819: return $quota;
10820: }
10821: }
10822:
10823: ###############################################
10824:
10825: =pod
10826:
10827: =item * &default_quota()
10828:
10829: Retrieves default quota assigned for storage of user portfolio files,
10830: given an (optional) user's institutional status.
10831:
10832: Incoming parameters:
10833:
10834: 1. domain
10835: 2. (Optional) institutional status(es). This is a : separated list of
10836: status types (e.g., faculty, staff, student etc.)
10837: which apply to the user for whom the default is being retrieved.
10838: If the institutional status string in undefined, the domain
10839: default quota will be returned.
10840: 3. quota name - portfolio, author, or course
10841: (if no quota name provided, defaults to portfolio).
10842:
10843: Returns:
10844:
10845: 1. Default disk quota (in MB) for user portfolios in the domain.
10846: 2. (Optional) institutional type which determined the value of the
10847: default quota.
10848:
10849: If a value has been stored in the domain's configuration db,
10850: it will return that, otherwise it returns 20 (for backwards
10851: compatibility with domains which have not set up a configuration
10852: db file; the original statically defined portfolio quota was 20 MB).
10853:
10854: If the user's status includes multiple types (e.g., staff and student),
10855: the largest default quota which applies to the user determines the
10856: default quota returned.
10857:
10858: =cut
10859:
10860: ###############################################
10861:
10862:
10863: sub default_quota {
10864: my ($udom,$inststatus,$quotaname) = @_;
10865: my ($defquota,$settingstatus);
10866: my %quotahash = &Apache::lonnet::get_dom('configuration',
10867: ['quotas'],$udom);
10868: my $key = 'defaultquota';
10869: if ($quotaname eq 'author') {
10870: $key = 'authorquota';
10871: }
10872: if (ref($quotahash{'quotas'}) eq 'HASH') {
10873: if ($inststatus ne '') {
10874: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10875: foreach my $item (@statuses) {
10876: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10877: if ($quotahash{'quotas'}{$key}{$item} ne '') {
10878: if ($defquota eq '') {
10879: $defquota = $quotahash{'quotas'}{$key}{$item};
10880: $settingstatus = $item;
10881: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10882: $defquota = $quotahash{'quotas'}{$key}{$item};
10883: $settingstatus = $item;
10884: }
10885: }
10886: } elsif ($key eq 'defaultquota') {
10887: if ($quotahash{'quotas'}{$item} ne '') {
10888: if ($defquota eq '') {
10889: $defquota = $quotahash{'quotas'}{$item};
10890: $settingstatus = $item;
10891: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10892: $defquota = $quotahash{'quotas'}{$item};
10893: $settingstatus = $item;
10894: }
10895: }
10896: }
10897: }
10898: }
10899: if ($defquota eq '') {
10900: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10901: $defquota = $quotahash{'quotas'}{$key}{'default'};
10902: } elsif ($key eq 'defaultquota') {
10903: $defquota = $quotahash{'quotas'}{'default'};
10904: }
10905: $settingstatus = 'default';
10906: if ($defquota eq '') {
10907: if ($quotaname eq 'author') {
10908: $defquota = 500;
10909: }
10910: }
10911: }
10912: } else {
10913: $settingstatus = 'default';
10914: if ($quotaname eq 'author') {
10915: $defquota = 500;
10916: } else {
10917: $defquota = 20;
10918: }
10919: }
10920: if (wantarray) {
10921: return ($defquota,$settingstatus);
10922: } else {
10923: return $defquota;
10924: }
10925: }
10926:
10927: ###############################################
10928:
10929: =pod
10930:
10931: =item * &excess_filesize_warning()
10932:
10933: Returns warning message if upload of file to authoring space, or copying
10934: of existing file within authoring space will cause quota for the authoring
10935: space to be exceeded.
10936:
10937: Same, if upload of a file directly to a course/community via Course Editor
10938: will cause quota for uploaded content for the course to be exceeded.
10939:
10940: Inputs: 7
10941: 1. username or coursenum
10942: 2. domain
10943: 3. context ('author' or 'course')
10944: 4. filename of file for which action is being requested
10945: 5. filesize (kB) of file
10946: 6. action being taken: copy or upload.
10947: 7. quotatype (in course context -- official, unofficial, community or textbook).
10948:
10949: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10950: otherwise return null.
10951:
10952: =back
10953:
10954: =cut
10955:
10956: sub excess_filesize_warning {
10957: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10958: my $current_disk_usage = 0;
10959: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10960: if ($context eq 'author') {
10961: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10962: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10963: } else {
10964: foreach my $subdir ('docs','supplemental') {
10965: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10966: }
10967: }
10968: $disk_quota = int($disk_quota * 1000);
10969: if (($current_disk_usage + $filesize) > $disk_quota) {
10970: return '<p class="LC_warning">'.
10971: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10972: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10973: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10974: $disk_quota,$current_disk_usage).
10975: '</p>';
10976: }
10977: return;
10978: }
10979:
10980: ###############################################
10981:
10982:
10983: sub get_secgrprole_info {
10984: my ($cdom,$cnum,$needroles,$type) = @_;
10985: my %sections_count = &get_sections($cdom,$cnum);
10986: my @sections = (sort {$a <=> $b} keys(%sections_count));
10987: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10988: my @groups = sort(keys(%curr_groups));
10989: my $allroles = [];
10990: my $rolehash;
10991: my $accesshash = {
10992: active => 'Currently has access',
10993: future => 'Will have future access',
10994: previous => 'Previously had access',
10995: };
10996: if ($needroles) {
10997: $rolehash = {'all' => 'all'};
10998: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10999: if (&Apache::lonnet::error(%user_roles)) {
11000: undef(%user_roles);
11001: }
11002: foreach my $item (keys(%user_roles)) {
11003: my ($role)=split(/\:/,$item,2);
11004: if ($role eq 'cr') { next; }
11005: if ($role =~ /^cr/) {
11006: $$rolehash{$role} = (split('/',$role))[3];
11007: } else {
11008: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11009: }
11010: }
11011: foreach my $key (sort(keys(%{$rolehash}))) {
11012: push(@{$allroles},$key);
11013: }
11014: push (@{$allroles},'st');
11015: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11016: }
11017: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11018: }
11019:
11020: sub user_picker {
11021: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11022: my $currdom = $dom;
11023: my @alldoms = &Apache::lonnet::all_domains();
11024: if (@alldoms == 1) {
11025: my %domsrch = &Apache::lonnet::get_dom('configuration',
11026: ['directorysrch'],$alldoms[0]);
11027: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11028: my $showdom = $domdesc;
11029: if ($showdom eq '') {
11030: $showdom = $dom;
11031: }
11032: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11033: if ((!$domsrch{'directorysrch'}{'available'}) &&
11034: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11035: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11036: }
11037: }
11038: }
11039: my %curr_selected = (
11040: srchin => 'dom',
11041: srchby => 'lastname',
11042: );
11043: my $srchterm;
11044: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11045: if ($srch->{'srchby'} ne '') {
11046: $curr_selected{'srchby'} = $srch->{'srchby'};
11047: }
11048: if ($srch->{'srchin'} ne '') {
11049: $curr_selected{'srchin'} = $srch->{'srchin'};
11050: }
11051: if ($srch->{'srchtype'} ne '') {
11052: $curr_selected{'srchtype'} = $srch->{'srchtype'};
11053: }
11054: if ($srch->{'srchdomain'} ne '') {
11055: $currdom = $srch->{'srchdomain'};
11056: }
11057: $srchterm = $srch->{'srchterm'};
11058: }
11059: my %html_lt=&Apache::lonlocal::texthash(
11060: 'usr' => 'Search criteria',
11061: 'doma' => 'Domain/institution to search',
11062: 'uname' => 'username',
11063: 'lastname' => 'last name',
11064: 'lastfirst' => 'last name, first name',
11065: 'crs' => 'in this course',
11066: 'dom' => 'in selected LON-CAPA domain',
11067: 'alc' => 'all LON-CAPA',
11068: 'instd' => 'in institutional directory for selected domain',
11069: 'exact' => 'is',
11070: 'contains' => 'contains',
11071: 'begins' => 'begins with',
11072: );
11073: my %js_lt=&Apache::lonlocal::texthash(
11074: 'youm' => "You must include some text to search for.",
11075: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11076: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11077: 'yomc' => "You must choose a domain when using an institutional directory search.",
11078: 'ymcd' => "You must choose a domain when using a domain search.",
11079: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
11080: 'whse' => "When searching by last,first you must include at least one character in the first name.",
11081: 'thfo' => "The following need to be corrected before the search can be run:",
11082: );
11083: &html_escape(\%html_lt);
11084: &js_escape(\%js_lt);
11085: my $domform;
11086: my $allow_blank = 1;
11087: if ($fixeddom) {
11088: $allow_blank = 0;
11089: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11090: } else {
11091: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
11092: }
11093: my $srchinsel = ' <select name="srchin">';
11094:
11095: my @srchins = ('crs','dom','alc','instd');
11096:
11097: foreach my $option (@srchins) {
11098: # FIXME 'alc' option unavailable until
11099: # loncreateuser::print_user_query_page()
11100: # has been completed.
11101: next if ($option eq 'alc');
11102: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
11103: next if ($option eq 'crs' && !$env{'request.course.id'});
11104: next if (($option eq 'instd') && ($noinstd));
11105: if ($curr_selected{'srchin'} eq $option) {
11106: $srchinsel .= '
11107: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11108: } else {
11109: $srchinsel .= '
11110: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11111: }
11112: }
11113: $srchinsel .= "\n </select>\n";
11114:
11115: my $srchbysel = ' <select name="srchby">';
11116: foreach my $option ('lastname','lastfirst','uname') {
11117: if ($curr_selected{'srchby'} eq $option) {
11118: $srchbysel .= '
11119: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11120: } else {
11121: $srchbysel .= '
11122: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11123: }
11124: }
11125: $srchbysel .= "\n </select>\n";
11126:
11127: my $srchtypesel = ' <select name="srchtype">';
11128: foreach my $option ('begins','contains','exact') {
11129: if ($curr_selected{'srchtype'} eq $option) {
11130: $srchtypesel .= '
11131: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11132: } else {
11133: $srchtypesel .= '
11134: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11135: }
11136: }
11137: $srchtypesel .= "\n </select>\n";
11138:
11139: my ($newuserscript,$new_user_create);
11140: my $context_dom = $env{'request.role.domain'};
11141: if ($context eq 'requestcrs') {
11142: if ($env{'form.coursedom'} ne '') {
11143: $context_dom = $env{'form.coursedom'};
11144: }
11145: }
11146: if ($forcenewuser) {
11147: if (ref($srch) eq 'HASH') {
11148: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11149: if ($cancreate) {
11150: $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>';
11151: } else {
11152: my $helplink = 'javascript:helpMenu('."'display'".')';
11153: my %usertypetext = (
11154: official => 'institutional',
11155: unofficial => 'non-institutional',
11156: );
11157: $new_user_create = '<p class="LC_warning">'
11158: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11159: .' '
11160: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11161: ,'<a href="'.$helplink.'">','</a>')
11162: .'</p><br />';
11163: }
11164: }
11165: }
11166:
11167: $newuserscript = <<"ENDSCRIPT";
11168:
11169: function setSearch(createnew,callingForm) {
11170: if (createnew == 1) {
11171: for (var i=0; i<callingForm.srchby.length; i++) {
11172: if (callingForm.srchby.options[i].value == 'uname') {
11173: callingForm.srchby.selectedIndex = i;
11174: }
11175: }
11176: for (var i=0; i<callingForm.srchin.length; i++) {
11177: if ( callingForm.srchin.options[i].value == 'dom') {
11178: callingForm.srchin.selectedIndex = i;
11179: }
11180: }
11181: for (var i=0; i<callingForm.srchtype.length; i++) {
11182: if (callingForm.srchtype.options[i].value == 'exact') {
11183: callingForm.srchtype.selectedIndex = i;
11184: }
11185: }
11186: for (var i=0; i<callingForm.srchdomain.length; i++) {
11187: if (callingForm.srchdomain.options[i].value == '$context_dom') {
11188: callingForm.srchdomain.selectedIndex = i;
11189: }
11190: }
11191: }
11192: }
11193: ENDSCRIPT
11194:
11195: }
11196:
11197: my $output = <<"END_BLOCK";
11198: <script type="text/javascript">
11199: // <![CDATA[
11200: function validateEntry(callingForm) {
11201:
11202: var checkok = 1;
11203: var srchin;
11204: for (var i=0; i<callingForm.srchin.length; i++) {
11205: if ( callingForm.srchin[i].checked ) {
11206: srchin = callingForm.srchin[i].value;
11207: }
11208: }
11209:
11210: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11211: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11212: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11213: var srchterm = callingForm.srchterm.value;
11214: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11215: var msg = "";
11216:
11217: if (srchterm == "") {
11218: checkok = 0;
11219: msg += "$js_lt{'youm'}\\n";
11220: }
11221:
11222: if (srchtype== 'begins') {
11223: if (srchterm.length < 2) {
11224: checkok = 0;
11225: msg += "$js_lt{'thte'}\\n";
11226: }
11227: }
11228:
11229: if (srchtype== 'contains') {
11230: if (srchterm.length < 3) {
11231: checkok = 0;
11232: msg += "$js_lt{'thet'}\\n";
11233: }
11234: }
11235: if (srchin == 'instd') {
11236: if (srchdomain == '') {
11237: checkok = 0;
11238: msg += "$js_lt{'yomc'}\\n";
11239: }
11240: }
11241: if (srchin == 'dom') {
11242: if (srchdomain == '') {
11243: checkok = 0;
11244: msg += "$js_lt{'ymcd'}\\n";
11245: }
11246: }
11247: if (srchby == 'lastfirst') {
11248: if (srchterm.indexOf(",") == -1) {
11249: checkok = 0;
11250: msg += "$js_lt{'whus'}\\n";
11251: }
11252: if (srchterm.indexOf(",") == srchterm.length -1) {
11253: checkok = 0;
11254: msg += "$js_lt{'whse'}\\n";
11255: }
11256: }
11257: if (checkok == 0) {
11258: alert("$js_lt{'thfo'}\\n"+msg);
11259: return;
11260: }
11261: if (checkok == 1) {
11262: callingForm.submit();
11263: }
11264: }
11265:
11266: $newuserscript
11267:
11268: // ]]>
11269: </script>
11270:
11271: $new_user_create
11272:
11273: END_BLOCK
11274:
11275: $output .= &Apache::lonhtmlcommon::start_pick_box().
11276: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11277: $domform.
11278: &Apache::lonhtmlcommon::row_closure().
11279: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11280: $srchbysel.
11281: $srchtypesel.
11282: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11283: $srchinsel.
11284: &Apache::lonhtmlcommon::row_closure(1).
11285: &Apache::lonhtmlcommon::end_pick_box().
11286: '<br />';
11287: return ($output,1);
11288: }
11289:
11290: sub user_rule_check {
11291: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11292: my ($response,%inst_response);
11293: if (ref($usershash) eq 'HASH') {
11294: if (keys(%{$usershash}) > 1) {
11295: my (%by_username,%by_id,%userdoms);
11296: my $checkid;
11297: if (ref($checks) eq 'HASH') {
11298: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11299: $checkid = 1;
11300: }
11301: }
11302: foreach my $user (keys(%{$usershash})) {
11303: my ($uname,$udom) = split(/:/,$user);
11304: if ($checkid) {
11305: if (ref($usershash->{$user}) eq 'HASH') {
11306: if ($usershash->{$user}->{'id'} ne '') {
11307: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
11308: $userdoms{$udom} = 1;
11309: if (ref($inst_results) eq 'HASH') {
11310: $inst_results->{$uname.':'.$udom} = {};
11311: }
11312: }
11313: }
11314: } else {
11315: $by_username{$udom}{$uname} = 1;
11316: $userdoms{$udom} = 1;
11317: if (ref($inst_results) eq 'HASH') {
11318: $inst_results->{$uname.':'.$udom} = {};
11319: }
11320: }
11321: }
11322: foreach my $udom (keys(%userdoms)) {
11323: if (!$got_rules->{$udom}) {
11324: my %domconfig = &Apache::lonnet::get_dom('configuration',
11325: ['usercreation'],$udom);
11326: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11327: foreach my $item ('username','id') {
11328: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11329: $$curr_rules{$udom}{$item} =
11330: $domconfig{'usercreation'}{$item.'_rule'};
11331: }
11332: }
11333: }
11334: $got_rules->{$udom} = 1;
11335: }
11336: }
11337: if ($checkid) {
11338: foreach my $udom (keys(%by_id)) {
11339: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11340: if ($outcome eq 'ok') {
11341: foreach my $id (keys(%{$by_id{$udom}})) {
11342: my $uname = $by_id{$udom}{$id};
11343: $inst_response{$uname.':'.$udom} = $outcome;
11344: }
11345: if (ref($results) eq 'HASH') {
11346: foreach my $uname (keys(%{$results})) {
11347: if (exists($inst_response{$uname.':'.$udom})) {
11348: $inst_response{$uname.':'.$udom} = $outcome;
11349: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11350: }
11351: }
11352: }
11353: }
11354: }
11355: } else {
11356: foreach my $udom (keys(%by_username)) {
11357: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11358: if ($outcome eq 'ok') {
11359: foreach my $uname (keys(%{$by_username{$udom}})) {
11360: $inst_response{$uname.':'.$udom} = $outcome;
11361: }
11362: if (ref($results) eq 'HASH') {
11363: foreach my $uname (keys(%{$results})) {
11364: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11365: }
11366: }
11367: }
11368: }
11369: }
11370: } elsif (keys(%{$usershash}) == 1) {
11371: my $user = (keys(%{$usershash}))[0];
11372: my ($uname,$udom) = split(/:/,$user);
11373: if (($udom ne '') && ($uname ne '')) {
11374: if (ref($usershash->{$user}) eq 'HASH') {
11375: if (ref($checks) eq 'HASH') {
11376: if (defined($checks->{'username'})) {
11377: ($inst_response{$user},%{$inst_results->{$user}}) =
11378: &Apache::lonnet::get_instuser($udom,$uname);
11379: } elsif (defined($checks->{'id'})) {
11380: if ($usershash->{$user}->{'id'} ne '') {
11381: ($inst_response{$user},%{$inst_results->{$user}}) =
11382: &Apache::lonnet::get_instuser($udom,undef,
11383: $usershash->{$user}->{'id'});
11384: } else {
11385: ($inst_response{$user},%{$inst_results->{$user}}) =
11386: &Apache::lonnet::get_instuser($udom,$uname);
11387: }
11388: }
11389: } else {
11390: ($inst_response{$user},%{$inst_results->{$user}}) =
11391: &Apache::lonnet::get_instuser($udom,$uname);
11392: return;
11393: }
11394: if (!$got_rules->{$udom}) {
11395: my %domconfig = &Apache::lonnet::get_dom('configuration',
11396: ['usercreation'],$udom);
11397: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11398: foreach my $item ('username','id') {
11399: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11400: $$curr_rules{$udom}{$item} =
11401: $domconfig{'usercreation'}{$item.'_rule'};
11402: }
11403: }
11404: }
11405: $got_rules->{$udom} = 1;
11406: }
11407: }
11408: } else {
11409: return;
11410: }
11411: } else {
11412: return;
11413: }
11414: foreach my $user (keys(%{$usershash})) {
11415: my ($uname,$udom) = split(/:/,$user);
11416: next if (($udom eq '') || ($uname eq ''));
11417: my $id;
11418: if (ref($inst_results) eq 'HASH') {
11419: if (ref($inst_results->{$user}) eq 'HASH') {
11420: $id = $inst_results->{$user}->{'id'};
11421: }
11422: }
11423: if ($id eq '') {
11424: if (ref($usershash->{$user})) {
11425: $id = $usershash->{$user}->{'id'};
11426: }
11427: }
11428: foreach my $item (keys(%{$checks})) {
11429: if (ref($$curr_rules{$udom}) eq 'HASH') {
11430: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11431: if (@{$$curr_rules{$udom}{$item}} > 0) {
11432: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11433: $$curr_rules{$udom}{$item});
11434: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11435: if ($rule_check{$rule}) {
11436: $$rulematch{$user}{$item} = $rule;
11437: if ($inst_response{$user} eq 'ok') {
11438: if (ref($inst_results) eq 'HASH') {
11439: if (ref($inst_results->{$user}) eq 'HASH') {
11440: if (keys(%{$inst_results->{$user}}) == 0) {
11441: $$alerts{$item}{$udom}{$uname} = 1;
11442: } elsif ($item eq 'id') {
11443: if ($inst_results->{$user}->{'id'} eq '') {
11444: $$alerts{$item}{$udom}{$uname} = 1;
11445: }
11446: }
11447: }
11448: }
11449: }
11450: last;
11451: }
11452: }
11453: }
11454: }
11455: }
11456: }
11457: }
11458: }
11459: return;
11460: }
11461:
11462: sub user_rule_formats {
11463: my ($domain,$domdesc,$curr_rules,$check) = @_;
11464: my %text = (
11465: 'username' => 'Usernames',
11466: 'id' => 'IDs',
11467: );
11468: my $output;
11469: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11470: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11471: if (@{$ruleorder} > 0) {
11472: $output = '<br />'.
11473: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11474: '<span class="LC_cusr_emph">','</span>',$domdesc).
11475: ' <ul>';
11476: foreach my $rule (@{$ruleorder}) {
11477: if (ref($curr_rules) eq 'ARRAY') {
11478: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11479: if (ref($rules->{$rule}) eq 'HASH') {
11480: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11481: $rules->{$rule}{'desc'}.'</li>';
11482: }
11483: }
11484: }
11485: }
11486: $output .= '</ul>';
11487: }
11488: }
11489: return $output;
11490: }
11491:
11492: sub instrule_disallow_msg {
11493: my ($checkitem,$domdesc,$count,$mode) = @_;
11494: my $response;
11495: my %text = (
11496: item => 'username',
11497: items => 'usernames',
11498: match => 'matches',
11499: do => 'does',
11500: action => 'a username',
11501: one => 'one',
11502: );
11503: if ($count > 1) {
11504: $text{'item'} = 'usernames';
11505: $text{'match'} ='match';
11506: $text{'do'} = 'do';
11507: $text{'action'} = 'usernames',
11508: $text{'one'} = 'ones';
11509: }
11510: if ($checkitem eq 'id') {
11511: $text{'items'} = 'IDs';
11512: $text{'item'} = 'ID';
11513: $text{'action'} = 'an ID';
11514: if ($count > 1) {
11515: $text{'item'} = 'IDs';
11516: $text{'action'} = 'IDs';
11517: }
11518: }
11519: $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 />';
11520: if ($mode eq 'upload') {
11521: if ($checkitem eq 'username') {
11522: $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'}.");
11523: } elsif ($checkitem eq 'id') {
11524: $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.");
11525: }
11526: } elsif ($mode eq 'selfcreate') {
11527: if ($checkitem eq 'id') {
11528: $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.");
11529: }
11530: } else {
11531: if ($checkitem eq 'username') {
11532: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11533: } elsif ($checkitem eq 'id') {
11534: $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.");
11535: }
11536: }
11537: return $response;
11538: }
11539:
11540: sub personal_data_fieldtitles {
11541: my %fieldtitles = &Apache::lonlocal::texthash (
11542: id => 'Student/Employee ID',
11543: permanentemail => 'E-mail address',
11544: lastname => 'Last Name',
11545: firstname => 'First Name',
11546: middlename => 'Middle Name',
11547: generation => 'Generation',
11548: gen => 'Generation',
11549: inststatus => 'Affiliation',
11550: );
11551: return %fieldtitles;
11552: }
11553:
11554: sub sorted_inst_types {
11555: my ($dom) = @_;
11556: my ($usertypes,$order);
11557: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11558: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11559: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11560: $order = $domdefaults{'inststatus'}{'inststatusorder'};
11561: } else {
11562: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11563: }
11564: my $othertitle = &mt('All users');
11565: if ($env{'request.course.id'}) {
11566: $othertitle = &mt('Any users');
11567: }
11568: my @types;
11569: if (ref($order) eq 'ARRAY') {
11570: @types = @{$order};
11571: }
11572: if (@types == 0) {
11573: if (ref($usertypes) eq 'HASH') {
11574: @types = sort(keys(%{$usertypes}));
11575: }
11576: }
11577: if (keys(%{$usertypes}) > 0) {
11578: $othertitle = &mt('Other users');
11579: }
11580: return ($othertitle,$usertypes,\@types);
11581: }
11582:
11583: sub get_institutional_codes {
11584: my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11585: # Get complete list of course sections to update
11586: my @currsections = ();
11587: my @currxlists = ();
11588: my (%unclutteredsec,%unclutteredlcsec);
11589: my $coursecode = $$settings{'internal.coursecode'};
11590: my $crskey = $crs.':'.$coursecode;
11591: @{$unclutteredsec{$crskey}} = ();
11592: @{$unclutteredlcsec{$crskey}} = ();
11593:
11594: if ($$settings{'internal.sectionnums'} ne '') {
11595: @currsections = split(/,/,$$settings{'internal.sectionnums'});
11596: }
11597:
11598: if ($$settings{'internal.crosslistings'} ne '') {
11599: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11600: }
11601:
11602: if (@currxlists > 0) {
11603: foreach my $xl (@currxlists) {
11604: if ($xl =~ /^([^:]+):(\w*)$/) {
11605: unless (grep/^$1$/,@{$allcourses}) {
11606: push(@{$allcourses},$1);
11607: $$LC_code{$1} = $2;
11608: }
11609: }
11610: }
11611: }
11612:
11613: if (@currsections > 0) {
11614: foreach my $sec (@currsections) {
11615: if ($sec =~ m/^(\w+):(\w*)$/ ) {
11616: my $instsec = $1;
11617: my $lc_sec = $2;
11618: unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11619: push(@{$unclutteredsec{$crskey}},$instsec);
11620: push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11621: }
11622: }
11623: }
11624: }
11625:
11626: if (@{$unclutteredsec{$crskey}} > 0) {
11627: my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11628: if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11629: for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11630: my $sec = $coursecode.$formattedsec{$crskey}[$i];
11631: unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11632: push(@{$allcourses},$sec);
11633: $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11634: }
11635: }
11636: }
11637: }
11638: return;
11639: }
11640:
11641: sub get_standard_codeitems {
11642: return ('Year','Semester','Department','Number','Section');
11643: }
11644:
11645: =pod
11646:
11647: =head1 Slot Helpers
11648:
11649: =over 4
11650:
11651: =item * sorted_slots()
11652:
11653: Sorts an array of slot names in order of an optional sort key,
11654: default sort is by slot start time (earliest first).
11655:
11656: Inputs:
11657:
11658: =over 4
11659:
11660: slotsarr - Reference to array of unsorted slot names.
11661:
11662: slots - Reference to hash of hash, where outer hash keys are slot names.
11663:
11664: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
11665:
11666: =back
11667:
11668: Returns:
11669:
11670: =over 4
11671:
11672: sorted - An array of slot names sorted by a specified sort key
11673: (default sort key is start time of the slot).
11674:
11675: =back
11676:
11677: =cut
11678:
11679:
11680: sub sorted_slots {
11681: my ($slotsarr,$slots,$sortkey) = @_;
11682: if ($sortkey eq '') {
11683: $sortkey = 'starttime';
11684: }
11685: my @sorted;
11686: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11687: @sorted =
11688: sort {
11689: if (ref($slots->{$a}) && ref($slots->{$b})) {
11690: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11691: }
11692: if (ref($slots->{$a})) { return -1;}
11693: if (ref($slots->{$b})) { return 1;}
11694: return 0;
11695: } @{$slotsarr};
11696: }
11697: return @sorted;
11698: }
11699:
11700: =pod
11701:
11702: =item * get_future_slots()
11703:
11704: Inputs:
11705:
11706: =over 4
11707:
11708: cnum - course number
11709:
11710: cdom - course domain
11711:
11712: now - current UNIX time
11713:
11714: symb - optional symb
11715:
11716: =back
11717:
11718: Returns:
11719:
11720: =over 4
11721:
11722: sorted_reservable - ref to array of student_schedulable slots currently
11723: reservable, ordered by end date of reservation period.
11724:
11725: reservable_now - ref to hash of student_schedulable slots currently
11726: reservable.
11727:
11728: Keys in inner hash are:
11729: (a) symb: either blank or symb to which slot use is restricted.
11730: (b) endreserve: end date of reservation period.
11731: (c) uniqueperiod: start,end dates when slot is to be uniquely
11732: selected.
11733:
11734: sorted_future - ref to array of student_schedulable slots reservable in
11735: the future, ordered by start date of reservation period.
11736:
11737: future_reservable - ref to hash of student_schedulable slots reservable
11738: in the future.
11739:
11740: Keys in inner hash are:
11741: (a) symb: either blank or symb to which slot use is restricted.
11742: (b) startreserve: start date of reservation period.
11743: (c) uniqueperiod: start,end dates when slot is to be uniquely
11744: selected.
11745:
11746: =back
11747:
11748: =cut
11749:
11750: sub get_future_slots {
11751: my ($cnum,$cdom,$now,$symb) = @_;
11752: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11753: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11754: foreach my $slot (keys(%slots)) {
11755: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11756: if ($symb) {
11757: next if (($slots{$slot}->{'symb'} ne '') &&
11758: ($slots{$slot}->{'symb'} ne $symb));
11759: }
11760: if (($slots{$slot}->{'starttime'} > $now) &&
11761: ($slots{$slot}->{'endtime'} > $now)) {
11762: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11763: my $userallowed = 0;
11764: if ($slots{$slot}->{'allowedsections'}) {
11765: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11766: if (!defined($env{'request.role.sec'})
11767: && grep(/^No section assigned$/,@allowed_sec)) {
11768: $userallowed=1;
11769: } else {
11770: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11771: $userallowed=1;
11772: }
11773: }
11774: unless ($userallowed) {
11775: if (defined($env{'request.course.groups'})) {
11776: my @groups = split(/:/,$env{'request.course.groups'});
11777: foreach my $group (@groups) {
11778: if (grep(/^\Q$group\E$/,@allowed_sec)) {
11779: $userallowed=1;
11780: last;
11781: }
11782: }
11783: }
11784: }
11785: }
11786: if ($slots{$slot}->{'allowedusers'}) {
11787: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11788: my $user = $env{'user.name'}.':'.$env{'user.domain'};
11789: if (grep(/^\Q$user\E$/,@allowed_users)) {
11790: $userallowed = 1;
11791: }
11792: }
11793: next unless($userallowed);
11794: }
11795: my $startreserve = $slots{$slot}->{'startreserve'};
11796: my $endreserve = $slots{$slot}->{'endreserve'};
11797: my $symb = $slots{$slot}->{'symb'};
11798: my $uniqueperiod;
11799: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11800: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11801: }
11802: if (($startreserve < $now) &&
11803: (!$endreserve || $endreserve > $now)) {
11804: my $lastres = $endreserve;
11805: if (!$lastres) {
11806: $lastres = $slots{$slot}->{'starttime'};
11807: }
11808: $reservable_now{$slot} = {
11809: symb => $symb,
11810: endreserve => $lastres,
11811: uniqueperiod => $uniqueperiod,
11812: };
11813: } elsif (($startreserve > $now) &&
11814: (!$endreserve || $endreserve > $startreserve)) {
11815: $future_reservable{$slot} = {
11816: symb => $symb,
11817: startreserve => $startreserve,
11818: uniqueperiod => $uniqueperiod,
11819: };
11820: }
11821: }
11822: }
11823: my @unsorted_reservable = keys(%reservable_now);
11824: if (@unsorted_reservable > 0) {
11825: @sorted_reservable =
11826: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11827: }
11828: my @unsorted_future = keys(%future_reservable);
11829: if (@unsorted_future > 0) {
11830: @sorted_future =
11831: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11832: }
11833: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11834: }
11835:
11836: =pod
11837:
11838: =back
11839:
11840: =head1 HTTP Helpers
11841:
11842: =over 4
11843:
11844: =item * &get_unprocessed_cgi($query,$possible_names)
11845:
11846: Modify the %env hash to contain unprocessed CGI form parameters held in
11847: $query. The parameters listed in $possible_names (an array reference),
11848: will be set in $env{'form.name'} if they do not already exist.
11849:
11850: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
11851: $possible_names is an ref to an array of form element names. As an example:
11852: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11853: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11854:
11855: =cut
11856:
11857: sub get_unprocessed_cgi {
11858: my ($query,$possible_names)= @_;
11859: # $Apache::lonxml::debug=1;
11860: foreach my $pair (split(/&/,$query)) {
11861: my ($name, $value) = split(/=/,$pair);
11862: $name = &unescape($name);
11863: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11864: $value =~ tr/+/ /;
11865: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11866: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11867: }
11868: }
11869: }
11870:
11871: =pod
11872:
11873: =item * &cacheheader()
11874:
11875: returns cache-controlling header code
11876:
11877: =cut
11878:
11879: sub cacheheader {
11880: unless ($env{'request.method'} eq 'GET') { return ''; }
11881: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11882: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11883: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11884: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11885: return $output;
11886: }
11887:
11888: =pod
11889:
11890: =item * &no_cache($r)
11891:
11892: specifies header code to not have cache
11893:
11894: =cut
11895:
11896: sub no_cache {
11897: my ($r) = @_;
11898: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11899: $env{'request.method'} ne 'GET') { return ''; }
11900: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11901: $r->no_cache(1);
11902: $r->header_out("Expires" => $date);
11903: $r->header_out("Pragma" => "no-cache");
11904: }
11905:
11906: sub content_type {
11907: my ($r,$type,$charset) = @_;
11908: if ($r) {
11909: # Note that printout.pl calls this with undef for $r.
11910: &no_cache($r);
11911: }
11912: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11913: unless ($charset) {
11914: $charset=&Apache::lonlocal::current_encoding;
11915: }
11916: if ($charset) { $type.='; charset='.$charset; }
11917: if ($r) {
11918: $r->content_type($type);
11919: } else {
11920: print("Content-type: $type\n\n");
11921: }
11922: }
11923:
11924: =pod
11925:
11926: =item * &add_to_env($name,$value)
11927:
11928: adds $name to the %env hash with value
11929: $value, if $name already exists, the entry is converted to an array
11930: reference and $value is added to the array.
11931:
11932: =cut
11933:
11934: sub add_to_env {
11935: my ($name,$value)=@_;
11936: if (defined($env{$name})) {
11937: if (ref($env{$name})) {
11938: #already have multiple values
11939: push(@{ $env{$name} },$value);
11940: } else {
11941: #first time seeing multiple values, convert hash entry to an arrayref
11942: my $first=$env{$name};
11943: undef($env{$name});
11944: push(@{ $env{$name} },$first,$value);
11945: }
11946: } else {
11947: $env{$name}=$value;
11948: }
11949: }
11950:
11951: =pod
11952:
11953: =item * &get_env_multiple($name)
11954:
11955: gets $name from the %env hash, it seemlessly handles the cases where multiple
11956: values may be defined and end up as an array ref.
11957:
11958: returns an array of values
11959:
11960: =cut
11961:
11962: sub get_env_multiple {
11963: my ($name) = @_;
11964: my @values;
11965: if (defined($env{$name})) {
11966: # exists is it an array
11967: if (ref($env{$name})) {
11968: @values=@{ $env{$name} };
11969: } else {
11970: $values[0]=$env{$name};
11971: }
11972: }
11973: return(@values);
11974: }
11975:
11976: sub ask_for_embedded_content {
11977: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11978: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11979: %currsubfile,%unused,$rem);
11980: my $counter = 0;
11981: my $numnew = 0;
11982: my $numremref = 0;
11983: my $numinvalid = 0;
11984: my $numpathchg = 0;
11985: my $numexisting = 0;
11986: my $numunused = 0;
11987: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11988: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11989: my $heading = &mt('Upload embedded files');
11990: my $buttontext = &mt('Upload');
11991:
11992: if ($env{'request.course.id'}) {
11993: if ($actionurl eq '/adm/dependencies') {
11994: $navmap = Apache::lonnavmaps::navmap->new();
11995: }
11996: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11997: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11998: }
11999: if (($actionurl eq '/adm/portfolio') ||
12000: ($actionurl eq '/adm/coursegrp_portfolio')) {
12001: my $current_path='/';
12002: if ($env{'form.currentpath'}) {
12003: $current_path = $env{'form.currentpath'};
12004: }
12005: if ($actionurl eq '/adm/coursegrp_portfolio') {
12006: $udom = $cdom;
12007: $uname = $cnum;
12008: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12009: } else {
12010: $udom = $env{'user.domain'};
12011: $uname = $env{'user.name'};
12012: $url = '/userfiles/portfolio';
12013: }
12014: $toplevel = $url.'/';
12015: $url .= $current_path;
12016: $getpropath = 1;
12017: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12018: ($actionurl eq '/adm/imsimport')) {
12019: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12020: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12021: $toplevel = $url;
12022: if ($rest ne '') {
12023: $url .= $rest;
12024: }
12025: } elsif ($actionurl eq '/adm/coursedocs') {
12026: if (ref($args) eq 'HASH') {
12027: $url = $args->{'docs_url'};
12028: $toplevel = $url;
12029: if ($args->{'context'} eq 'paste') {
12030: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12031: ($path) =
12032: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12033: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12034: $fileloc =~ s{^/}{};
12035: }
12036: }
12037: } elsif ($actionurl eq '/adm/dependencies') {
12038: if ($env{'request.course.id'} ne '') {
12039: if (ref($args) eq 'HASH') {
12040: $url = $args->{'docs_url'};
12041: $title = $args->{'docs_title'};
12042: $toplevel = $url;
12043: unless ($toplevel =~ m{^/}) {
12044: $toplevel = "/$url";
12045: }
12046: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12047: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12048: $path = $1;
12049: } else {
12050: ($path) =
12051: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12052: }
12053: if ($toplevel=~/^\/*(uploaded|editupload)/) {
12054: $fileloc = $toplevel;
12055: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12056: my ($udom,$uname,$fname) =
12057: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12058: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12059: } else {
12060: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12061: }
12062: $fileloc =~ s{^/}{};
12063: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12064: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12065: }
12066: }
12067: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12068: $udom = $cdom;
12069: $uname = $cnum;
12070: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12071: $toplevel = $url;
12072: $path = $url;
12073: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12074: $fileloc =~ s{^/}{};
12075: }
12076: foreach my $file (keys(%{$allfiles})) {
12077: my $embed_file;
12078: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12079: $embed_file = $1;
12080: } else {
12081: $embed_file = $file;
12082: }
12083: my ($absolutepath,$cleaned_file);
12084: if ($embed_file =~ m{^\w+://}) {
12085: $cleaned_file = $embed_file;
12086: $newfiles{$cleaned_file} = 1;
12087: $mapping{$cleaned_file} = $embed_file;
12088: } else {
12089: $cleaned_file = &clean_path($embed_file);
12090: if ($embed_file =~ m{^/}) {
12091: $absolutepath = $embed_file;
12092: }
12093: if ($cleaned_file =~ m{/}) {
12094: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12095: $path = &check_for_traversal($path,$url,$toplevel);
12096: my $item = $fname;
12097: if ($path ne '') {
12098: $item = $path.'/'.$fname;
12099: $subdependencies{$path}{$fname} = 1;
12100: } else {
12101: $dependencies{$item} = 1;
12102: }
12103: if ($absolutepath) {
12104: $mapping{$item} = $absolutepath;
12105: } else {
12106: $mapping{$item} = $embed_file;
12107: }
12108: } else {
12109: $dependencies{$embed_file} = 1;
12110: if ($absolutepath) {
12111: $mapping{$cleaned_file} = $absolutepath;
12112: } else {
12113: $mapping{$cleaned_file} = $embed_file;
12114: }
12115: }
12116: }
12117: }
12118: my $dirptr = 16384;
12119: foreach my $path (keys(%subdependencies)) {
12120: $currsubfile{$path} = {};
12121: if (($actionurl eq '/adm/portfolio') ||
12122: ($actionurl eq '/adm/coursegrp_portfolio')) {
12123: my ($sublistref,$listerror) =
12124: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12125: if (ref($sublistref) eq 'ARRAY') {
12126: foreach my $line (@{$sublistref}) {
12127: my ($file_name,$rest) = split(/\&/,$line,2);
12128: $currsubfile{$path}{$file_name} = 1;
12129: }
12130: }
12131: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12132: if (opendir(my $dir,$url.'/'.$path)) {
12133: my @subdir_list = grep(!/^\./,readdir($dir));
12134: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12135: }
12136: } elsif (($actionurl eq '/adm/dependencies') ||
12137: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12138: ($args->{'context'} eq 'paste')) ||
12139: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12140: if ($env{'request.course.id'} ne '') {
12141: my $dir;
12142: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12143: $dir = $fileloc;
12144: } else {
12145: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12146: }
12147: if ($dir ne '') {
12148: my ($sublistref,$listerror) =
12149: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12150: if (ref($sublistref) eq 'ARRAY') {
12151: foreach my $line (@{$sublistref}) {
12152: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12153: undef,$mtime)=split(/\&/,$line,12);
12154: unless (($testdir&$dirptr) ||
12155: ($file_name =~ /^\.\.?$/)) {
12156: $currsubfile{$path}{$file_name} = [$size,$mtime];
12157: }
12158: }
12159: }
12160: }
12161: }
12162: }
12163: foreach my $file (keys(%{$subdependencies{$path}})) {
12164: if (exists($currsubfile{$path}{$file})) {
12165: my $item = $path.'/'.$file;
12166: unless ($mapping{$item} eq $item) {
12167: $pathchanges{$item} = 1;
12168: }
12169: $existing{$item} = 1;
12170: $numexisting ++;
12171: } else {
12172: $newfiles{$path.'/'.$file} = 1;
12173: }
12174: }
12175: if ($actionurl eq '/adm/dependencies') {
12176: foreach my $path (keys(%currsubfile)) {
12177: if (ref($currsubfile{$path}) eq 'HASH') {
12178: foreach my $file (keys(%{$currsubfile{$path}})) {
12179: unless ($subdependencies{$path}{$file}) {
12180: next if (($rem ne '') &&
12181: (($env{"httpref.$rem"."$path/$file"} ne '') ||
12182: (ref($navmap) &&
12183: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12184: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12185: ($navmap->getResourceByUrl($rem."$path/$1")))))));
12186: $unused{$path.'/'.$file} = 1;
12187: }
12188: }
12189: }
12190: }
12191: }
12192: }
12193: my %currfile;
12194: if (($actionurl eq '/adm/portfolio') ||
12195: ($actionurl eq '/adm/coursegrp_portfolio')) {
12196: my ($dirlistref,$listerror) =
12197: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12198: if (ref($dirlistref) eq 'ARRAY') {
12199: foreach my $line (@{$dirlistref}) {
12200: my ($file_name,$rest) = split(/\&/,$line,2);
12201: $currfile{$file_name} = 1;
12202: }
12203: }
12204: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12205: if (opendir(my $dir,$url)) {
12206: my @dir_list = grep(!/^\./,readdir($dir));
12207: map {$currfile{$_} = 1;} @dir_list;
12208: }
12209: } elsif (($actionurl eq '/adm/dependencies') ||
12210: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12211: ($args->{'context'} eq 'paste')) ||
12212: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12213: if ($env{'request.course.id'} ne '') {
12214: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12215: if ($dir ne '') {
12216: my ($dirlistref,$listerror) =
12217: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12218: if (ref($dirlistref) eq 'ARRAY') {
12219: foreach my $line (@{$dirlistref}) {
12220: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12221: $size,undef,$mtime)=split(/\&/,$line,12);
12222: unless (($testdir&$dirptr) ||
12223: ($file_name =~ /^\.\.?$/)) {
12224: $currfile{$file_name} = [$size,$mtime];
12225: }
12226: }
12227: }
12228: }
12229: }
12230: }
12231: foreach my $file (keys(%dependencies)) {
12232: if (exists($currfile{$file})) {
12233: unless ($mapping{$file} eq $file) {
12234: $pathchanges{$file} = 1;
12235: }
12236: $existing{$file} = 1;
12237: $numexisting ++;
12238: } else {
12239: $newfiles{$file} = 1;
12240: }
12241: }
12242: foreach my $file (keys(%currfile)) {
12243: unless (($file eq $filename) ||
12244: ($file eq $filename.'.bak') ||
12245: ($dependencies{$file})) {
12246: if ($actionurl eq '/adm/dependencies') {
12247: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12248: next if (($rem ne '') &&
12249: (($env{"httpref.$rem".$file} ne '') ||
12250: (ref($navmap) &&
12251: (($navmap->getResourceByUrl($rem.$file) ne '') ||
12252: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12253: ($navmap->getResourceByUrl($rem.$1)))))));
12254: }
12255: }
12256: $unused{$file} = 1;
12257: }
12258: }
12259: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12260: ($args->{'context'} eq 'paste')) {
12261: $counter = scalar(keys(%existing));
12262: $numpathchg = scalar(keys(%pathchanges));
12263: return ($output,$counter,$numpathchg,\%existing);
12264: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
12265: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12266: $counter = scalar(keys(%existing));
12267: $numpathchg = scalar(keys(%pathchanges));
12268: return ($output,$counter,$numpathchg,\%existing,\%mapping);
12269: }
12270: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12271: if ($actionurl eq '/adm/dependencies') {
12272: next if ($embed_file =~ m{^\w+://});
12273: }
12274: $upload_output .= &start_data_table_row().
12275: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12276: '<span class="LC_filename">'.$embed_file.'</span>';
12277: unless ($mapping{$embed_file} eq $embed_file) {
12278: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12279: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12280: }
12281: $upload_output .= '</td>';
12282: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
12283: $upload_output.='<td align="right">'.
12284: '<span class="LC_info LC_fontsize_medium">'.
12285: &mt("URL points to web address").'</span>';
12286: $numremref++;
12287: } elsif ($args->{'error_on_invalid_names'}
12288: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12289: $upload_output.='<td align="right"><span class="LC_warning">'.
12290: &mt('Invalid characters').'</span>';
12291: $numinvalid++;
12292: } else {
12293: $upload_output .= '<td>'.
12294: &embedded_file_element('upload_embedded',$counter,
12295: $embed_file,\%mapping,
12296: $allfiles,$codebase,'upload');
12297: $counter ++;
12298: $numnew ++;
12299: }
12300: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12301: }
12302: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12303: if ($actionurl eq '/adm/dependencies') {
12304: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12305: $modify_output .= &start_data_table_row().
12306: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12307: '<img src="'.&icon($embed_file).'" border="0" />'.
12308: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
12309: '<td>'.$size.'</td>'.
12310: '<td>'.$mtime.'</td>'.
12311: '<td><label><input type="checkbox" name="mod_upload_dep" '.
12312: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12313: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12314: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12315: &embedded_file_element('upload_embedded',$counter,
12316: $embed_file,\%mapping,
12317: $allfiles,$codebase,'modify').
12318: '</div></td>'.
12319: &end_data_table_row()."\n";
12320: $counter ++;
12321: } else {
12322: $upload_output .= &start_data_table_row().
12323: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12324: '<span class="LC_filename">'.$embed_file.'</span></td>'.
12325: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12326: &Apache::loncommon::end_data_table_row()."\n";
12327: }
12328: }
12329: my $delidx = $counter;
12330: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12331: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12332: $delete_output .= &start_data_table_row().
12333: '<td><img src="'.&icon($oldfile).'" />'.
12334: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
12335: '<td>'.$size.'</td>'.
12336: '<td>'.$mtime.'</td>'.
12337: '<td><label><input type="checkbox" name="del_upload_dep" '.
12338: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12339: &embedded_file_element('upload_embedded',$delidx,
12340: $oldfile,\%mapping,$allfiles,
12341: $codebase,'delete').'</td>'.
12342: &end_data_table_row()."\n";
12343: $numunused ++;
12344: $delidx ++;
12345: }
12346: if ($upload_output) {
12347: $upload_output = &start_data_table().
12348: $upload_output.
12349: &end_data_table()."\n";
12350: }
12351: if ($modify_output) {
12352: $modify_output = &start_data_table().
12353: &start_data_table_header_row().
12354: '<th>'.&mt('File').'</th>'.
12355: '<th>'.&mt('Size (KB)').'</th>'.
12356: '<th>'.&mt('Modified').'</th>'.
12357: '<th>'.&mt('Upload replacement?').'</th>'.
12358: &end_data_table_header_row().
12359: $modify_output.
12360: &end_data_table()."\n";
12361: }
12362: if ($delete_output) {
12363: $delete_output = &start_data_table().
12364: &start_data_table_header_row().
12365: '<th>'.&mt('File').'</th>'.
12366: '<th>'.&mt('Size (KB)').'</th>'.
12367: '<th>'.&mt('Modified').'</th>'.
12368: '<th>'.&mt('Delete?').'</th>'.
12369: &end_data_table_header_row().
12370: $delete_output.
12371: &end_data_table()."\n";
12372: }
12373: my $applies = 0;
12374: if ($numremref) {
12375: $applies ++;
12376: }
12377: if ($numinvalid) {
12378: $applies ++;
12379: }
12380: if ($numexisting) {
12381: $applies ++;
12382: }
12383: if ($counter || $numunused) {
12384: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12385: ' method="post" enctype="multipart/form-data">'."\n".
12386: $state.'<h3>'.$heading.'</h3>';
12387: if ($actionurl eq '/adm/dependencies') {
12388: if ($numnew) {
12389: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12390: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12391: $upload_output.'<br />'."\n";
12392: }
12393: if ($numexisting) {
12394: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12395: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12396: $modify_output.'<br />'."\n";
12397: $buttontext = &mt('Save changes');
12398: }
12399: if ($numunused) {
12400: $output .= '<h4>'.&mt('Unused files').'</h4>'.
12401: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12402: $delete_output.'<br />'."\n";
12403: $buttontext = &mt('Save changes');
12404: }
12405: } else {
12406: $output .= $upload_output.'<br />'."\n";
12407: }
12408: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12409: $counter.'" />'."\n";
12410: if ($actionurl eq '/adm/dependencies') {
12411: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12412: $numnew.'" />'."\n";
12413: } elsif ($actionurl eq '') {
12414: $output .= '<input type="hidden" name="phase" value="three" />';
12415: }
12416: } elsif ($applies) {
12417: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12418: if ($applies > 1) {
12419: $output .=
12420: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12421: if ($numremref) {
12422: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12423: }
12424: if ($numinvalid) {
12425: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12426: }
12427: if ($numexisting) {
12428: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12429: }
12430: $output .= '</ul><br />';
12431: } elsif ($numremref) {
12432: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12433: } elsif ($numinvalid) {
12434: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12435: } elsif ($numexisting) {
12436: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12437: }
12438: $output .= $upload_output.'<br />';
12439: }
12440: my ($pathchange_output,$chgcount);
12441: $chgcount = $counter;
12442: if (keys(%pathchanges) > 0) {
12443: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12444: if ($counter) {
12445: $output .= &embedded_file_element('pathchange',$chgcount,
12446: $embed_file,\%mapping,
12447: $allfiles,$codebase,'change');
12448: } else {
12449: $pathchange_output .=
12450: &start_data_table_row().
12451: '<td><input type ="checkbox" name="namechange" value="'.
12452: $chgcount.'" checked="checked" /></td>'.
12453: '<td>'.$mapping{$embed_file}.'</td>'.
12454: '<td>'.$embed_file.
12455: &embedded_file_element('pathchange',$numpathchg,$embed_file,
12456: \%mapping,$allfiles,$codebase,'change').
12457: '</td>'.&end_data_table_row();
12458: }
12459: $numpathchg ++;
12460: $chgcount ++;
12461: }
12462: }
12463: if (($counter) || ($numunused)) {
12464: if ($numpathchg) {
12465: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12466: $numpathchg.'" />'."\n";
12467: }
12468: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12469: ($actionurl eq '/adm/imsimport')) {
12470: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12471: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12472: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12473: } elsif ($actionurl eq '/adm/dependencies') {
12474: $output .= '<input type="hidden" name="action" value="process_changes" />';
12475: }
12476: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12477: } elsif ($numpathchg) {
12478: my %pathchange = ();
12479: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12480: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12481: $output .= '<p>'.&mt('or').'</p>';
12482: }
12483: }
12484: return ($output,$counter,$numpathchg);
12485: }
12486:
12487: =pod
12488:
12489: =item * clean_path($name)
12490:
12491: Performs clean-up of directories, subdirectories and filename in an
12492: embedded object, referenced in an HTML file which is being uploaded
12493: to a course or portfolio, where
12494: "Upload embedded images/multimedia files if HTML file" checkbox was
12495: checked.
12496:
12497: Clean-up is similar to replacements in lonnet::clean_filename()
12498: except each / between sub-directory and next level is preserved.
12499:
12500: =cut
12501:
12502: sub clean_path {
12503: my ($embed_file) = @_;
12504: $embed_file =~s{^/+}{};
12505: my @contents;
12506: if ($embed_file =~ m{/}) {
12507: @contents = split(/\//,$embed_file);
12508: } else {
12509: @contents = ($embed_file);
12510: }
12511: my $lastidx = scalar(@contents)-1;
12512: for (my $i=0; $i<=$lastidx; $i++) {
12513: $contents[$i]=~s{\\}{/}g;
12514: $contents[$i]=~s/\s+/\_/g;
12515: $contents[$i]=~s{[^/\w\.\-]}{}g;
12516: if ($i == $lastidx) {
12517: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12518: }
12519: }
12520: if ($lastidx > 0) {
12521: return join('/',@contents);
12522: } else {
12523: return $contents[0];
12524: }
12525: }
12526:
12527: sub embedded_file_element {
12528: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12529: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12530: (ref($codebase) eq 'HASH'));
12531: my $output;
12532: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12533: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12534: }
12535: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12536: &escape($embed_file).'" />';
12537: unless (($context eq 'upload_embedded') &&
12538: ($mapping->{$embed_file} eq $embed_file)) {
12539: $output .='
12540: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12541: }
12542: my $attrib;
12543: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12544: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12545: }
12546: $output .=
12547: "\n\t\t".
12548: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12549: $attrib.'" />';
12550: if (exists($codebase->{$mapping->{$embed_file}})) {
12551: $output .=
12552: "\n\t\t".
12553: '<input name="codebase_'.$num.'" type="hidden" value="'.
12554: &escape($codebase->{$mapping->{$embed_file}}).'" />';
12555: }
12556: return $output;
12557: }
12558:
12559: sub get_dependency_details {
12560: my ($currfile,$currsubfile,$embed_file) = @_;
12561: my ($size,$mtime,$showsize,$showmtime);
12562: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12563: if ($embed_file =~ m{/}) {
12564: my ($path,$fname) = split(/\//,$embed_file);
12565: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12566: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12567: }
12568: } else {
12569: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12570: ($size,$mtime) = @{$currfile->{$embed_file}};
12571: }
12572: }
12573: $showsize = $size/1024.0;
12574: $showsize = sprintf("%.1f",$showsize);
12575: if ($mtime > 0) {
12576: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12577: }
12578: }
12579: return ($showsize,$showmtime);
12580: }
12581:
12582: sub ask_embedded_js {
12583: return <<"END";
12584: <script type="text/javascript"">
12585: // <![CDATA[
12586: function toggleBrowse(counter) {
12587: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12588: var fileid = document.getElementById('embedded_item_'+counter);
12589: var uploaddivid = document.getElementById('moduploaddep_'+counter);
12590: if (chkboxid.checked == true) {
12591: uploaddivid.style.display='block';
12592: } else {
12593: uploaddivid.style.display='none';
12594: fileid.value = '';
12595: }
12596: }
12597: // ]]>
12598: </script>
12599:
12600: END
12601: }
12602:
12603: sub upload_embedded {
12604: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12605: $current_disk_usage,$hiddenstate,$actionurl) = @_;
12606: my (%pathchange,$output,$modifyform,$footer,$returnflag);
12607: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12608: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12609: my $orig_uploaded_filename =
12610: $env{'form.embedded_item_'.$i.'.filename'};
12611: foreach my $type ('orig','ref','attrib','codebase') {
12612: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12613: $env{'form.embedded_'.$type.'_'.$i} =
12614: &unescape($env{'form.embedded_'.$type.'_'.$i});
12615: }
12616: }
12617: my ($path,$fname) =
12618: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12619: # no path, whole string is fname
12620: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12621: $fname = &Apache::lonnet::clean_filename($fname);
12622: # See if there is anything left
12623: next if ($fname eq '');
12624:
12625: # Check if file already exists as a file or directory.
12626: my ($state,$msg);
12627: if ($context eq 'portfolio') {
12628: my $port_path = $dirpath;
12629: if ($group ne '') {
12630: $port_path = "groups/$group/$port_path";
12631: }
12632: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12633: $fname,$group,'embedded_item_'.$i,
12634: $dir_root,$port_path,$disk_quota,
12635: $current_disk_usage,$uname,$udom);
12636: if ($state eq 'will_exceed_quota'
12637: || $state eq 'file_locked') {
12638: $output .= $msg;
12639: next;
12640: }
12641: } elsif (($context eq 'author') || ($context eq 'testbank')) {
12642: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12643: if ($state eq 'exists') {
12644: $output .= $msg;
12645: next;
12646: }
12647: }
12648: # Check if extension is valid
12649: if (($fname =~ /\.(\w+)$/) &&
12650: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12651: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12652: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12653: next;
12654: } elsif (($fname =~ /\.(\w+)$/) &&
12655: (!defined(&Apache::loncommon::fileembstyle($1)))) {
12656: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12657: next;
12658: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12659: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12660: next;
12661: }
12662: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12663: my $subdir = $path;
12664: $subdir =~ s{/+$}{};
12665: if ($context eq 'portfolio') {
12666: my $result;
12667: if ($state eq 'existingfile') {
12668: $result=
12669: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12670: $dirpath.$env{'form.currentpath'}.$subdir);
12671: } else {
12672: $result=
12673: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12674: $dirpath.
12675: $env{'form.currentpath'}.$subdir);
12676: if ($result !~ m|^/uploaded/|) {
12677: $output .= '<span class="LC_error">'
12678: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12679: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12680: .'</span><br />';
12681: next;
12682: } else {
12683: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12684: $path.$fname.'</span>').'<br />';
12685: }
12686: }
12687: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12688: my $extendedsubdir = $dirpath.'/'.$subdir;
12689: $extendedsubdir =~ s{/+$}{};
12690: my $result =
12691: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12692: if ($result !~ m|^/uploaded/|) {
12693: $output .= '<span class="LC_error">'
12694: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12695: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12696: .'</span><br />';
12697: next;
12698: } else {
12699: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12700: $path.$fname.'</span>').'<br />';
12701: if ($context eq 'syllabus') {
12702: &Apache::lonnet::make_public_indefinitely($result);
12703: }
12704: }
12705: } else {
12706: # Save the file
12707: my $target = $env{'form.embedded_item_'.$i};
12708: my $fullpath = $dir_root.$dirpath.'/'.$path;
12709: my $dest = $fullpath.$fname;
12710: my $url = $url_root.$dirpath.'/'.$path.$fname;
12711: my @parts=split(/\//,"$dirpath/$path");
12712: my $count;
12713: my $filepath = $dir_root;
12714: foreach my $subdir (@parts) {
12715: $filepath .= "/$subdir";
12716: if (!-e $filepath) {
12717: mkdir($filepath,0770);
12718: }
12719: }
12720: my $fh;
12721: if (!open($fh,'>'.$dest)) {
12722: &Apache::lonnet::logthis('Failed to create '.$dest);
12723: $output .= '<span class="LC_error">'.
12724: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12725: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12726: '</span><br />';
12727: } else {
12728: if (!print $fh $env{'form.embedded_item_'.$i}) {
12729: &Apache::lonnet::logthis('Failed to write to '.$dest);
12730: $output .= '<span class="LC_error">'.
12731: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12732: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12733: '</span><br />';
12734: } else {
12735: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12736: $url.'</span>').'<br />';
12737: unless ($context eq 'testbank') {
12738: $footer .= &mt('View embedded file: [_1]',
12739: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12740: }
12741: }
12742: close($fh);
12743: }
12744: }
12745: if ($env{'form.embedded_ref_'.$i}) {
12746: $pathchange{$i} = 1;
12747: }
12748: }
12749: if ($output) {
12750: $output = '<p>'.$output.'</p>';
12751: }
12752: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12753: $returnflag = 'ok';
12754: my $numpathchgs = scalar(keys(%pathchange));
12755: if ($numpathchgs > 0) {
12756: if ($context eq 'portfolio') {
12757: $output .= '<p>'.&mt('or').'</p>';
12758: } elsif ($context eq 'testbank') {
12759: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12760: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12761: $returnflag = 'modify_orightml';
12762: }
12763: }
12764: return ($output.$footer,$returnflag,$numpathchgs);
12765: }
12766:
12767: sub modify_html_form {
12768: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12769: my $end = 0;
12770: my $modifyform;
12771: if ($context eq 'upload_embedded') {
12772: return unless (ref($pathchange) eq 'HASH');
12773: if ($env{'form.number_embedded_items'}) {
12774: $end += $env{'form.number_embedded_items'};
12775: }
12776: if ($env{'form.number_pathchange_items'}) {
12777: $end += $env{'form.number_pathchange_items'};
12778: }
12779: if ($end) {
12780: for (my $i=0; $i<$end; $i++) {
12781: if ($i < $env{'form.number_embedded_items'}) {
12782: next unless($pathchange->{$i});
12783: }
12784: $modifyform .=
12785: &start_data_table_row().
12786: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12787: 'checked="checked" /></td>'.
12788: '<td>'.$env{'form.embedded_ref_'.$i}.
12789: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12790: &escape($env{'form.embedded_ref_'.$i}).'" />'.
12791: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12792: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12793: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12794: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12795: '<td>'.$env{'form.embedded_orig_'.$i}.
12796: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12797: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12798: &end_data_table_row();
12799: }
12800: }
12801: } else {
12802: $modifyform = $pathchgtable;
12803: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12804: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12805: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12806: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12807: }
12808: }
12809: if ($modifyform) {
12810: if ($actionurl eq '/adm/dependencies') {
12811: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12812: }
12813: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12814: '<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".
12815: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12816: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12817: '</ol></p>'."\n".'<p>'.
12818: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12819: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12820: &start_data_table()."\n".
12821: &start_data_table_header_row().
12822: '<th>'.&mt('Change?').'</th>'.
12823: '<th>'.&mt('Current reference').'</th>'.
12824: '<th>'.&mt('Required reference').'</th>'.
12825: &end_data_table_header_row()."\n".
12826: $modifyform.
12827: &end_data_table().'<br />'."\n".$hiddenstate.
12828: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12829: '</form>'."\n";
12830: }
12831: return;
12832: }
12833:
12834: sub modify_html_refs {
12835: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12836: my $container;
12837: if ($context eq 'portfolio') {
12838: $container = $env{'form.container'};
12839: } elsif ($context eq 'coursedoc') {
12840: $container = $env{'form.primaryurl'};
12841: } elsif ($context eq 'manage_dependencies') {
12842: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12843: $container = "/$container";
12844: } elsif ($context eq 'syllabus') {
12845: $container = $url;
12846: } else {
12847: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12848: }
12849: my (%allfiles,%codebase,$output,$content);
12850: my @changes = &get_env_multiple('form.namechange');
12851: unless ((@changes > 0) || ($context eq 'syllabus')) {
12852: if (wantarray) {
12853: return ('',0,0);
12854: } else {
12855: return;
12856: }
12857: }
12858: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12859: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12860: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12861: if (wantarray) {
12862: return ('',0,0);
12863: } else {
12864: return;
12865: }
12866: }
12867: $content = &Apache::lonnet::getfile($container);
12868: if ($content eq '-1') {
12869: if (wantarray) {
12870: return ('',0,0);
12871: } else {
12872: return;
12873: }
12874: }
12875: } else {
12876: unless ($container =~ /^\Q$dir_root\E/) {
12877: if (wantarray) {
12878: return ('',0,0);
12879: } else {
12880: return;
12881: }
12882: }
12883: if (open(my $fh,'<',$container)) {
12884: $content = join('', <$fh>);
12885: close($fh);
12886: } else {
12887: if (wantarray) {
12888: return ('',0,0);
12889: } else {
12890: return;
12891: }
12892: }
12893: }
12894: my ($count,$codebasecount) = (0,0);
12895: my $mm = new File::MMagic;
12896: my $mime_type = $mm->checktype_contents($content);
12897: if ($mime_type eq 'text/html') {
12898: my $parse_result =
12899: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12900: \%codebase,\$content);
12901: if ($parse_result eq 'ok') {
12902: foreach my $i (@changes) {
12903: my $orig = &unescape($env{'form.embedded_orig_'.$i});
12904: my $ref = &unescape($env{'form.embedded_ref_'.$i});
12905: if ($allfiles{$ref}) {
12906: my $newname = $orig;
12907: my ($attrib_regexp,$codebase);
12908: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12909: if ($attrib_regexp =~ /:/) {
12910: $attrib_regexp =~ s/\:/|/g;
12911: }
12912: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12913: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12914: $count += $numchg;
12915: $allfiles{$newname} = $allfiles{$ref};
12916: delete($allfiles{$ref});
12917: }
12918: if ($env{'form.embedded_codebase_'.$i} ne '') {
12919: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12920: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12921: $codebasecount ++;
12922: }
12923: }
12924: }
12925: my $skiprewrites;
12926: if ($count || $codebasecount) {
12927: my $saveresult;
12928: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12929: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12930: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12931: if ($url eq $container) {
12932: my ($fname) = ($container =~ m{/([^/]+)$});
12933: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12934: $count,'<span class="LC_filename">'.
12935: $fname.'</span>').'</p>';
12936: } else {
12937: $output = '<p class="LC_error">'.
12938: &mt('Error: update failed for: [_1].',
12939: '<span class="LC_filename">'.
12940: $container.'</span>').'</p>';
12941: }
12942: if ($context eq 'syllabus') {
12943: unless ($saveresult eq 'ok') {
12944: $skiprewrites = 1;
12945: }
12946: }
12947: } else {
12948: if (open(my $fh,'>',$container)) {
12949: print $fh $content;
12950: close($fh);
12951: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12952: $count,'<span class="LC_filename">'.
12953: $container.'</span>').'</p>';
12954: } else {
12955: $output = '<p class="LC_error">'.
12956: &mt('Error: could not update [_1].',
12957: '<span class="LC_filename">'.
12958: $container.'</span>').'</p>';
12959: }
12960: }
12961: }
12962: if (($context eq 'syllabus') && (!$skiprewrites)) {
12963: my ($actionurl,$state);
12964: $actionurl = "/public/$udom/$uname/syllabus";
12965: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12966: &ask_for_embedded_content($actionurl,$state,\%allfiles,
12967: \%codebase,
12968: {'context' => 'rewrites',
12969: 'ignore_remote_references' => 1,});
12970: if (ref($mapping) eq 'HASH') {
12971: my $rewrites = 0;
12972: foreach my $key (keys(%{$mapping})) {
12973: next if ($key =~ m{^https?://});
12974: my $ref = $mapping->{$key};
12975: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12976: my $attrib;
12977: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12978: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12979: }
12980: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12981: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12982: $rewrites += $numchg;
12983: }
12984: }
12985: if ($rewrites) {
12986: my $saveresult;
12987: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12988: if ($url eq $container) {
12989: my ($fname) = ($container =~ m{/([^/]+)$});
12990: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12991: $count,'<span class="LC_filename">'.
12992: $fname.'</span>').'</p>';
12993: } else {
12994: $output .= '<p class="LC_error">'.
12995: &mt('Error: could not update links in [_1].',
12996: '<span class="LC_filename">'.
12997: $container.'</span>').'</p>';
12998:
12999: }
13000: }
13001: }
13002: }
13003: } else {
13004: &logthis('Failed to parse '.$container.
13005: ' to modify references: '.$parse_result);
13006: }
13007: }
13008: if (wantarray) {
13009: return ($output,$count,$codebasecount);
13010: } else {
13011: return $output;
13012: }
13013: }
13014:
13015: sub check_for_existing {
13016: my ($path,$fname,$element) = @_;
13017: my ($state,$msg);
13018: if (-d $path.'/'.$fname) {
13019: $state = 'exists';
13020: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13021: } elsif (-e $path.'/'.$fname) {
13022: $state = 'exists';
13023: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13024: }
13025: if ($state eq 'exists') {
13026: $msg = '<span class="LC_error">'.$msg.'</span><br />';
13027: }
13028: return ($state,$msg);
13029: }
13030:
13031: sub check_for_upload {
13032: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13033: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13034: my $filesize = length($env{'form.'.$element});
13035: if (!$filesize) {
13036: my $msg = '<span class="LC_error">'.
13037: &mt('Unable to upload [_1]. (size = [_2] bytes)',
13038: '<span class="LC_filename">'.$fname.'</span>',
13039: $filesize).'<br />'.
13040: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13041: '</span>';
13042: return ('zero_bytes',$msg);
13043: }
13044: $filesize = $filesize/1000; #express in k (1024?)
13045: my $getpropath = 1;
13046: my ($dirlistref,$listerror) =
13047: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13048: my $found_file = 0;
13049: my $locked_file = 0;
13050: my @lockers;
13051: my $navmap;
13052: if ($env{'request.course.id'}) {
13053: $navmap = Apache::lonnavmaps::navmap->new();
13054: }
13055: if (ref($dirlistref) eq 'ARRAY') {
13056: foreach my $line (@{$dirlistref}) {
13057: my ($file_name,$rest)=split(/\&/,$line,2);
13058: if ($file_name eq $fname){
13059: $file_name = $path.$file_name;
13060: if ($group ne '') {
13061: $file_name = $group.$file_name;
13062: }
13063: $found_file = 1;
13064: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13065: foreach my $lock (@lockers) {
13066: if (ref($lock) eq 'ARRAY') {
13067: my ($symb,$crsid) = @{$lock};
13068: if ($crsid eq $env{'request.course.id'}) {
13069: if (ref($navmap)) {
13070: my $res = $navmap->getBySymb($symb);
13071: foreach my $part (@{$res->parts()}) {
13072: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13073: unless (($slot_status == $res->RESERVED) ||
13074: ($slot_status == $res->RESERVED_LOCATION)) {
13075: $locked_file = 1;
13076: }
13077: }
13078: } else {
13079: $locked_file = 1;
13080: }
13081: } else {
13082: $locked_file = 1;
13083: }
13084: }
13085: }
13086: } else {
13087: my @info = split(/\&/,$rest);
13088: my $currsize = $info[6]/1000;
13089: if ($currsize < $filesize) {
13090: my $extra = $filesize - $currsize;
13091: if (($current_disk_usage + $extra) > $disk_quota) {
13092: my $msg = '<p class="LC_warning">'.
13093: &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.',
13094: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13095: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13096: $disk_quota,$current_disk_usage).'</p>';
13097: return ('will_exceed_quota',$msg);
13098: }
13099: }
13100: }
13101: }
13102: }
13103: }
13104: if (($current_disk_usage + $filesize) > $disk_quota){
13105: my $msg = '<p class="LC_warning">'.
13106: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13107: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13108: return ('will_exceed_quota',$msg);
13109: } elsif ($found_file) {
13110: if ($locked_file) {
13111: my $msg = '<p class="LC_warning">';
13112: $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>');
13113: $msg .= '</p>';
13114: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13115: return ('file_locked',$msg);
13116: } else {
13117: my $msg = '<p class="LC_error">';
13118: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13119: $msg .= '</p>';
13120: return ('existingfile',$msg);
13121: }
13122: }
13123: }
13124:
13125: sub check_for_traversal {
13126: my ($path,$url,$toplevel) = @_;
13127: my @parts=split(/\//,$path);
13128: my $cleanpath;
13129: my $fullpath = $url;
13130: for (my $i=0;$i<@parts;$i++) {
13131: next if ($parts[$i] eq '.');
13132: if ($parts[$i] eq '..') {
13133: $fullpath =~ s{([^/]+/)$}{};
13134: } else {
13135: $fullpath .= $parts[$i].'/';
13136: }
13137: }
13138: if ($fullpath =~ /^\Q$url\E(.*)$/) {
13139: $cleanpath = $1;
13140: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13141: my $curr_toprel = $1;
13142: my @parts = split(/\//,$curr_toprel);
13143: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13144: my @urlparts = split(/\//,$url_toprel);
13145: my $doubledots;
13146: my $startdiff = -1;
13147: for (my $i=0; $i<@urlparts; $i++) {
13148: if ($startdiff == -1) {
13149: unless ($urlparts[$i] eq $parts[$i]) {
13150: $startdiff = $i;
13151: $doubledots .= '../';
13152: }
13153: } else {
13154: $doubledots .= '../';
13155: }
13156: }
13157: if ($startdiff > -1) {
13158: $cleanpath = $doubledots;
13159: for (my $i=$startdiff; $i<@parts; $i++) {
13160: $cleanpath .= $parts[$i].'/';
13161: }
13162: }
13163: }
13164: $cleanpath =~ s{(/)$}{};
13165: return $cleanpath;
13166: }
13167:
13168: sub is_archive_file {
13169: my ($mimetype) = @_;
13170: if (($mimetype eq 'application/octet-stream') ||
13171: ($mimetype eq 'application/x-stuffit') ||
13172: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13173: return 1;
13174: }
13175: return;
13176: }
13177:
13178: sub decompress_form {
13179: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13180: my %lt = &Apache::lonlocal::texthash (
13181: this => 'This file is an archive file.',
13182: camt => 'This file is a Camtasia archive file.',
13183: itsc => 'Its contents are as follows:',
13184: youm => 'You may wish to extract its contents.',
13185: extr => 'Extract contents',
13186: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13187: proa => 'Process automatically?',
13188: yes => 'Yes',
13189: no => 'No',
13190: fold => 'Title for folder containing movie',
13191: movi => 'Title for page containing embedded movie',
13192: );
13193: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13194: my ($is_camtasia,$topdir,%toplevel,@paths);
13195: my $info = &list_archive_contents($fileloc,\@paths);
13196: if (@paths) {
13197: foreach my $path (@paths) {
13198: $path =~ s{^/}{};
13199: if ($path =~ m{^([^/]+)/$}) {
13200: $topdir = $1;
13201: }
13202: if ($path =~ m{^([^/]+)/}) {
13203: $toplevel{$1} = $path;
13204: } else {
13205: $toplevel{$path} = $path;
13206: }
13207: }
13208: }
13209: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13210: my @camtasia6 = ("$topdir/","$topdir/index.html",
13211: "$topdir/media/",
13212: "$topdir/media/$topdir.mp4",
13213: "$topdir/media/FirstFrame.png",
13214: "$topdir/media/player.swf",
13215: "$topdir/media/swfobject.js",
13216: "$topdir/media/expressInstall.swf");
13217: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13218: "$topdir/$topdir.mp4",
13219: "$topdir/$topdir\_config.xml",
13220: "$topdir/$topdir\_controller.swf",
13221: "$topdir/$topdir\_embed.css",
13222: "$topdir/$topdir\_First_Frame.png",
13223: "$topdir/$topdir\_player.html",
13224: "$topdir/$topdir\_Thumbnails.png",
13225: "$topdir/playerProductInstall.swf",
13226: "$topdir/scripts/",
13227: "$topdir/scripts/config_xml.js",
13228: "$topdir/scripts/handlebars.js",
13229: "$topdir/scripts/jquery-1.7.1.min.js",
13230: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13231: "$topdir/scripts/modernizr.js",
13232: "$topdir/scripts/player-min.js",
13233: "$topdir/scripts/swfobject.js",
13234: "$topdir/skins/",
13235: "$topdir/skins/configuration_express.xml",
13236: "$topdir/skins/express_show/",
13237: "$topdir/skins/express_show/player-min.css",
13238: "$topdir/skins/express_show/spritesheet.png");
13239: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13240: "$topdir/$topdir.mp4",
13241: "$topdir/$topdir\_config.xml",
13242: "$topdir/$topdir\_controller.swf",
13243: "$topdir/$topdir\_embed.css",
13244: "$topdir/$topdir\_First_Frame.png",
13245: "$topdir/$topdir\_player.html",
13246: "$topdir/$topdir\_Thumbnails.png",
13247: "$topdir/playerProductInstall.swf",
13248: "$topdir/scripts/",
13249: "$topdir/scripts/config_xml.js",
13250: "$topdir/scripts/techsmith-smart-player.min.js",
13251: "$topdir/skins/",
13252: "$topdir/skins/configuration_express.xml",
13253: "$topdir/skins/express_show/",
13254: "$topdir/skins/express_show/spritesheet.min.css",
13255: "$topdir/skins/express_show/spritesheet.png",
13256: "$topdir/skins/express_show/techsmith-smart-player.min.css");
13257: my @diffs = &compare_arrays(\@paths,\@camtasia6);
13258: if (@diffs == 0) {
13259: $is_camtasia = 6;
13260: } else {
13261: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13262: if (@diffs == 0) {
13263: $is_camtasia = 8;
13264: } else {
13265: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13266: if (@diffs == 0) {
13267: $is_camtasia = 8;
13268: }
13269: }
13270: }
13271: }
13272: my $output;
13273: if ($is_camtasia) {
13274: $output = <<"ENDCAM";
13275: <script type="text/javascript" language="Javascript">
13276: // <![CDATA[
13277:
13278: function camtasiaToggle() {
13279: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13280: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13281: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13282: document.getElementById('camtasia_titles').style.display='block';
13283: } else {
13284: document.getElementById('camtasia_titles').style.display='none';
13285: }
13286: }
13287: }
13288: return;
13289: }
13290:
13291: // ]]>
13292: </script>
13293: <p>$lt{'camt'}</p>
13294: ENDCAM
13295: } else {
13296: $output = '<p>'.$lt{'this'};
13297: if ($info eq '') {
13298: $output .= ' '.$lt{'youm'}.'</p>'."\n";
13299: } else {
13300: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13301: '<div><pre>'.$info.'</pre></div>';
13302: }
13303: }
13304: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13305: my $duplicates;
13306: my $num = 0;
13307: if (ref($dirlist) eq 'ARRAY') {
13308: foreach my $item (@{$dirlist}) {
13309: if (ref($item) eq 'ARRAY') {
13310: if (exists($toplevel{$item->[0]})) {
13311: $duplicates .=
13312: &start_data_table_row().
13313: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13314: 'value="0" checked="checked" />'.&mt('No').'</label>'.
13315: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
13316: 'value="1" />'.&mt('Yes').'</label>'.
13317: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13318: '<td>'.$item->[0].'</td>';
13319: if ($item->[2]) {
13320: $duplicates .= '<td>'.&mt('Directory').'</td>';
13321: } else {
13322: $duplicates .= '<td>'.&mt('File').'</td>';
13323: }
13324: $duplicates .= '<td>'.$item->[3].'</td>'.
13325: '<td>'.
13326: &Apache::lonlocal::locallocaltime($item->[4]).
13327: '</td>'.
13328: &end_data_table_row();
13329: $num ++;
13330: }
13331: }
13332: }
13333: }
13334: my $itemcount;
13335: if (@paths > 0) {
13336: $itemcount = scalar(@paths);
13337: } else {
13338: $itemcount = 1;
13339: }
13340: if ($is_camtasia) {
13341: $output .= $lt{'auto'}.'<br />'.
13342: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13343: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13344: $lt{'yes'}.'</label> <label>'.
13345: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13346: $lt{'no'}.'</label></span><br />'.
13347: '<div id="camtasia_titles" style="display:block">'.
13348: &Apache::lonhtmlcommon::start_pick_box().
13349: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13350: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13351: &Apache::lonhtmlcommon::row_closure().
13352: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13353: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13354: &Apache::lonhtmlcommon::row_closure(1).
13355: &Apache::lonhtmlcommon::end_pick_box().
13356: '</div>';
13357: }
13358: $output .=
13359: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13360: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13361: "\n";
13362: if ($duplicates ne '') {
13363: $output .= '<p><span class="LC_warning">'.
13364: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
13365: &start_data_table().
13366: &start_data_table_header_row().
13367: '<th>'.&mt('Overwrite?').'</th>'.
13368: '<th>'.&mt('Name').'</th>'.
13369: '<th>'.&mt('Type').'</th>'.
13370: '<th>'.&mt('Size').'</th>'.
13371: '<th>'.&mt('Last modified').'</th>'.
13372: &end_data_table_header_row().
13373: $duplicates.
13374: &end_data_table().
13375: '</p>';
13376: }
13377: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13378: if (ref($hiddenelements) eq 'HASH') {
13379: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13380: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13381: }
13382: }
13383: $output .= <<"END";
13384: <br />
13385: <input type="submit" name="decompress" value="$lt{'extr'}" />
13386: </form>
13387: $noextract
13388: END
13389: return $output;
13390: }
13391:
13392: sub decompression_utility {
13393: my ($program) = @_;
13394: my @utilities = ('tar','gunzip','bunzip2','unzip');
13395: my $location;
13396: if (grep(/^\Q$program\E$/,@utilities)) {
13397: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13398: '/usr/sbin/') {
13399: if (-x $dir.$program) {
13400: $location = $dir.$program;
13401: last;
13402: }
13403: }
13404: }
13405: return $location;
13406: }
13407:
13408: sub list_archive_contents {
13409: my ($file,$pathsref) = @_;
13410: my (@cmd,$output);
13411: my $needsregexp;
13412: if ($file =~ /\.zip$/) {
13413: @cmd = (&decompression_utility('unzip'),"-l");
13414: $needsregexp = 1;
13415: } elsif (($file =~ m/\.tar\.gz$/) ||
13416: ($file =~ /\.tgz$/)) {
13417: @cmd = (&decompression_utility('tar'),"-ztf");
13418: } elsif ($file =~ /\.tar\.bz2$/) {
13419: @cmd = (&decompression_utility('tar'),"-jtf");
13420: } elsif ($file =~ m|\.tar$|) {
13421: @cmd = (&decompression_utility('tar'),"-tf");
13422: }
13423: if (@cmd) {
13424: undef($!);
13425: undef($@);
13426: if (open(my $fh,"-|", @cmd, $file)) {
13427: while (my $line = <$fh>) {
13428: $output .= $line;
13429: chomp($line);
13430: my $item;
13431: if ($needsregexp) {
13432: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
13433: } else {
13434: $item = $line;
13435: }
13436: if ($item ne '') {
13437: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13438: push(@{$pathsref},$item);
13439: }
13440: }
13441: }
13442: close($fh);
13443: }
13444: }
13445: return $output;
13446: }
13447:
13448: sub decompress_uploaded_file {
13449: my ($file,$dir) = @_;
13450: &Apache::lonnet::appenv({'cgi.file' => $file});
13451: &Apache::lonnet::appenv({'cgi.dir' => $dir});
13452: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13453: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13454: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13455: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13456: my $decompressed = $env{'cgi.decompressed'};
13457: &Apache::lonnet::delenv('cgi.file');
13458: &Apache::lonnet::delenv('cgi.dir');
13459: &Apache::lonnet::delenv('cgi.decompressed');
13460: return ($decompressed,$result);
13461: }
13462:
13463: sub process_decompression {
13464: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13465: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13466: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13467: &mt('Unexpected file path.').'</p>'."\n";
13468: }
13469: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13470: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13471: &mt('Unexpected course context.').'</p>'."\n";
13472: }
13473: unless ($file eq &Apache::lonnet::clean_filename($file)) {
13474: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13475: &mt('Filename contained unexpected characters.').'</p>'."\n";
13476: }
13477: my ($dir,$error,$warning,$output);
13478: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13479: $error = &mt('Filename not a supported archive file type.').
13480: '<br />'.&mt('Filename should end with one of: [_1].',
13481: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13482: } else {
13483: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13484: if ($docuhome eq 'no_host') {
13485: $error = &mt('Could not determine home server for course.');
13486: } else {
13487: my @ids=&Apache::lonnet::current_machine_ids();
13488: my $currdir = "$dir_root/$destination";
13489: if (grep(/^\Q$docuhome\E$/,@ids)) {
13490: $dir = &LONCAPA::propath($docudom,$docuname).
13491: "$dir_root/$destination";
13492: } else {
13493: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13494: "$dir_root/$docudom/$docuname/$destination";
13495: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13496: $error = &mt('Archive file not found.');
13497: }
13498: }
13499: my (@to_overwrite,@to_skip);
13500: if ($env{'form.archive_overwrite_total'} > 0) {
13501: my $total = $env{'form.archive_overwrite_total'};
13502: for (my $i=0; $i<$total; $i++) {
13503: if ($env{'form.archive_overwrite_'.$i} == 1) {
13504: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13505: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13506: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13507: }
13508: }
13509: }
13510: my $numskip = scalar(@to_skip);
13511: my $numoverwrite = scalar(@to_overwrite);
13512: if (($numskip) && (!$numoverwrite)) {
13513: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
13514: } elsif ($dir eq '') {
13515: $error = &mt('Directory containing archive file unavailable.');
13516: } elsif (!$error) {
13517: my ($decompressed,$display);
13518: if (($numskip) || ($numoverwrite)) {
13519: my $tempdir = time.'_'.$$.int(rand(10000));
13520: mkdir("$dir/$tempdir",0755);
13521: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13522: ($decompressed,$display) =
13523: &decompress_uploaded_file($file,"$dir/$tempdir");
13524: foreach my $item (@to_skip) {
13525: if (($item ne '') && ($item !~ /\.\./)) {
13526: if (-f "$dir/$tempdir/$item") {
13527: unlink("$dir/$tempdir/$item");
13528: } elsif (-d "$dir/$tempdir/$item") {
13529: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13530: }
13531: }
13532: }
13533: foreach my $item (@to_overwrite) {
13534: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13535: if (($item ne '') && ($item !~ /\.\./)) {
13536: if (-f "$dir/$item") {
13537: unlink("$dir/$item");
13538: } elsif (-d "$dir/$item") {
13539: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13540: }
13541: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13542: }
13543: }
13544: }
13545: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13546: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13547: }
13548: }
13549: } else {
13550: ($decompressed,$display) =
13551: &decompress_uploaded_file($file,$dir);
13552: }
13553: if ($decompressed eq 'ok') {
13554: $output = '<p class="LC_info">'.
13555: &mt('Files extracted successfully from archive.').
13556: '</p>'."\n";
13557: my ($warning,$result,@contents);
13558: my ($newdirlistref,$newlisterror) =
13559: &Apache::lonnet::dirlist($currdir,$docudom,
13560: $docuname,1);
13561: my (%is_dir,%changes,@newitems);
13562: my $dirptr = 16384;
13563: if (ref($newdirlistref) eq 'ARRAY') {
13564: foreach my $dir_line (@{$newdirlistref}) {
13565: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13566: unless (($item =~ /^\.+$/) || ($item eq $file)) {
13567: push(@newitems,$item);
13568: if ($dirptr&$testdir) {
13569: $is_dir{$item} = 1;
13570: }
13571: $changes{$item} = 1;
13572: }
13573: }
13574: }
13575: if (keys(%changes) > 0) {
13576: foreach my $item (sort(@newitems)) {
13577: if ($changes{$item}) {
13578: push(@contents,$item);
13579: }
13580: }
13581: }
13582: if (@contents > 0) {
13583: my $wantform;
13584: unless ($env{'form.autoextract_camtasia'}) {
13585: $wantform = 1;
13586: }
13587: my (%children,%parent,%dirorder,%titles);
13588: my ($count,$datatable) = &get_extracted($docudom,$docuname,
13589: $currdir,\%is_dir,
13590: \%children,\%parent,
13591: \@contents,\%dirorder,
13592: \%titles,$wantform);
13593: if ($datatable ne '') {
13594: $output .= &archive_options_form('decompressed',$datatable,
13595: $count,$hiddenelem);
13596: my $startcount = 6;
13597: $output .= &archive_javascript($startcount,$count,
13598: \%titles,\%children);
13599: }
13600: if ($env{'form.autoextract_camtasia'}) {
13601: my $version = $env{'form.autoextract_camtasia'};
13602: my %displayed;
13603: my $total = 1;
13604: $env{'form.archive_directory'} = [];
13605: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13606: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13607: $path =~ s{/$}{};
13608: my $item;
13609: if ($path ne '') {
13610: $item = "$path/$titles{$i}";
13611: } else {
13612: $item = $titles{$i};
13613: }
13614: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13615: if ($item eq $contents[0]) {
13616: push(@{$env{'form.archive_directory'}},$i);
13617: $env{'form.archive_'.$i} = 'display';
13618: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13619: $displayed{'folder'} = $i;
13620: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13621: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13622: $env{'form.archive_'.$i} = 'display';
13623: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13624: $displayed{'web'} = $i;
13625: } else {
13626: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13627: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13628: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13629: push(@{$env{'form.archive_directory'}},$i);
13630: }
13631: $env{'form.archive_'.$i} = 'dependency';
13632: }
13633: $total ++;
13634: }
13635: for (my $i=1; $i<$total; $i++) {
13636: next if ($i == $displayed{'web'});
13637: next if ($i == $displayed{'folder'});
13638: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13639: }
13640: $env{'form.phase'} = 'decompress_cleanup';
13641: $env{'form.archivedelete'} = 1;
13642: $env{'form.archive_count'} = $total-1;
13643: $output .=
13644: &process_extracted_files('coursedocs',$docudom,
13645: $docuname,$destination,
13646: $dir_root,$hiddenelem);
13647: }
13648: } else {
13649: $warning = &mt('No new items extracted from archive file.');
13650: }
13651: } else {
13652: $output = $display;
13653: $error = &mt('An error occurred during extraction from the archive file.');
13654: }
13655: }
13656: }
13657: }
13658: if ($error) {
13659: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13660: $error.'</p>'."\n";
13661: }
13662: if ($warning) {
13663: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13664: }
13665: return $output;
13666: }
13667:
13668: sub get_extracted {
13669: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13670: $titles,$wantform) = @_;
13671: my $count = 0;
13672: my $depth = 0;
13673: my $datatable;
13674: my @hierarchy;
13675: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13676: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13677: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13678: foreach my $item (@{$contents}) {
13679: $count ++;
13680: @{$dirorder->{$count}} = @hierarchy;
13681: $titles->{$count} = $item;
13682: &archive_hierarchy($depth,$count,$parent,$children);
13683: if ($wantform) {
13684: $datatable .= &archive_row($is_dir->{$item},$item,
13685: $currdir,$depth,$count);
13686: }
13687: if ($is_dir->{$item}) {
13688: $depth ++;
13689: push(@hierarchy,$count);
13690: $parent->{$depth} = $count;
13691: $datatable .=
13692: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13693: \$depth,\$count,\@hierarchy,$dirorder,
13694: $children,$parent,$titles,$wantform);
13695: $depth --;
13696: pop(@hierarchy);
13697: }
13698: }
13699: return ($count,$datatable);
13700: }
13701:
13702: sub recurse_extracted_archive {
13703: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13704: $children,$parent,$titles,$wantform) = @_;
13705: my $result='';
13706: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13707: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13708: (ref($dirorder) eq 'HASH')) {
13709: return $result;
13710: }
13711: my $dirptr = 16384;
13712: my ($newdirlistref,$newlisterror) =
13713: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13714: if (ref($newdirlistref) eq 'ARRAY') {
13715: foreach my $dir_line (@{$newdirlistref}) {
13716: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13717: unless ($item =~ /^\.+$/) {
13718: $$count ++;
13719: @{$dirorder->{$$count}} = @{$hierarchy};
13720: $titles->{$$count} = $item;
13721: &archive_hierarchy($$depth,$$count,$parent,$children);
13722:
13723: my $is_dir;
13724: if ($dirptr&$testdir) {
13725: $is_dir = 1;
13726: }
13727: if ($wantform) {
13728: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13729: }
13730: if ($is_dir) {
13731: $$depth ++;
13732: push(@{$hierarchy},$$count);
13733: $parent->{$$depth} = $$count;
13734: $result .=
13735: &recurse_extracted_archive("$currdir/$item",$docudom,
13736: $docuname,$depth,$count,
13737: $hierarchy,$dirorder,$children,
13738: $parent,$titles,$wantform);
13739: $$depth --;
13740: pop(@{$hierarchy});
13741: }
13742: }
13743: }
13744: }
13745: return $result;
13746: }
13747:
13748: sub archive_hierarchy {
13749: my ($depth,$count,$parent,$children) =@_;
13750: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13751: if (exists($parent->{$depth})) {
13752: $children->{$parent->{$depth}} .= $count.':';
13753: }
13754: }
13755: return;
13756: }
13757:
13758: sub archive_row {
13759: my ($is_dir,$item,$currdir,$depth,$count) = @_;
13760: my ($name) = ($item =~ m{([^/]+)$});
13761: my %choices = &Apache::lonlocal::texthash (
13762: 'display' => 'Add as file',
13763: 'dependency' => 'Include as dependency',
13764: 'discard' => 'Discard',
13765: );
13766: if ($is_dir) {
13767: $choices{'display'} = &mt('Add as folder');
13768: }
13769: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13770: my $offset = 0;
13771: foreach my $action ('display','dependency','discard') {
13772: $offset ++;
13773: if ($action ne 'display') {
13774: $offset ++;
13775: }
13776: $output .= '<td><span class="LC_nobreak">'.
13777: '<label><input type="radio" name="archive_'.$count.
13778: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13779: my $text = $choices{$action};
13780: if ($is_dir) {
13781: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13782: if ($action eq 'display') {
13783: $text = &mt('Add as folder');
13784: }
13785: } else {
13786: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13787:
13788: }
13789: $output .= ' /> '.$choices{$action}.'</label></span>';
13790: if ($action eq 'dependency') {
13791: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13792: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
13793: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13794: '<option value=""></option>'."\n".
13795: '</select>'."\n".
13796: '</div>';
13797: } elsif ($action eq 'display') {
13798: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13799: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13800: '</div>';
13801: }
13802: $output .= '</td>';
13803: }
13804: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13805: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
13806: for (my $i=0; $i<$depth; $i++) {
13807: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13808: }
13809: if ($is_dir) {
13810: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
13811: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13812: } else {
13813: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13814: }
13815: $output .= ' '.$name.'</td>'."\n".
13816: &end_data_table_row();
13817: return $output;
13818: }
13819:
13820: sub archive_options_form {
13821: my ($form,$display,$count,$hiddenelem) = @_;
13822: my %lt = &Apache::lonlocal::texthash(
13823: perm => 'Permanently remove archive file?',
13824: hows => 'How should each extracted item be incorporated in the course?',
13825: cont => 'Content actions for all',
13826: addf => 'Add as folder/file',
13827: incd => 'Include as dependency for a displayed file',
13828: disc => 'Discard',
13829: no => 'No',
13830: yes => 'Yes',
13831: save => 'Save',
13832: );
13833: my $output = <<"END";
13834: <form name="$form" method="post" action="">
13835: <p><span class="LC_nobreak">$lt{'perm'}
13836: <label>
13837: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13838: </label>
13839:
13840: <label>
13841: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13842: </span>
13843: </p>
13844: <input type="hidden" name="phase" value="decompress_cleanup" />
13845: <br />$lt{'hows'}
13846: <div class="LC_columnSection">
13847: <fieldset>
13848: <legend>$lt{'cont'}</legend>
13849: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
13850: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13851: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13852: </fieldset>
13853: </div>
13854: END
13855: return $output.
13856: &start_data_table()."\n".
13857: $display."\n".
13858: &end_data_table()."\n".
13859: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13860: $hiddenelem.
13861: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13862: '</form>';
13863: }
13864:
13865: sub archive_javascript {
13866: my ($startcount,$numitems,$titles,$children) = @_;
13867: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13868: my $maintitle = $env{'form.comment'};
13869: my $scripttag = <<START;
13870: <script type="text/javascript">
13871: // <![CDATA[
13872:
13873: function checkAll(form,prefix) {
13874: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
13875: for (var i=0; i < form.elements.length; i++) {
13876: var id = form.elements[i].id;
13877: if ((id != '') && (id != undefined)) {
13878: if (idstr.test(id)) {
13879: if (form.elements[i].type == 'radio') {
13880: form.elements[i].checked = true;
13881: var nostart = i-$startcount;
13882: var offset = nostart%7;
13883: var count = (nostart-offset)/7;
13884: dependencyCheck(form,count,offset);
13885: }
13886: }
13887: }
13888: }
13889: }
13890:
13891: function propagateCheck(form,count) {
13892: if (count > 0) {
13893: var startelement = $startcount + ((count-1) * 7);
13894: for (var j=1; j<6; j++) {
13895: if ((j != 2) && (j != 4)) {
13896: var item = startelement + j;
13897: if (form.elements[item].type == 'radio') {
13898: if (form.elements[item].checked) {
13899: containerCheck(form,count,j);
13900: break;
13901: }
13902: }
13903: }
13904: }
13905: }
13906: }
13907:
13908: numitems = $numitems
13909: var titles = new Array(numitems);
13910: var parents = new Array(numitems);
13911: for (var i=0; i<numitems; i++) {
13912: parents[i] = new Array;
13913: }
13914: var maintitle = '$maintitle';
13915:
13916: START
13917:
13918: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13919: my @contents = split(/:/,$children->{$container});
13920: for (my $i=0; $i<@contents; $i ++) {
13921: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13922: }
13923: }
13924:
13925: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13926: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13927: }
13928:
13929: $scripttag .= <<END;
13930:
13931: function containerCheck(form,count,offset) {
13932: if (count > 0) {
13933: dependencyCheck(form,count,offset);
13934: var item = (offset+$startcount)+7*(count-1);
13935: form.elements[item].checked = true;
13936: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13937: if (parents[count].length > 0) {
13938: for (var j=0; j<parents[count].length; j++) {
13939: containerCheck(form,parents[count][j],offset);
13940: }
13941: }
13942: }
13943: }
13944: }
13945:
13946: function dependencyCheck(form,count,offset) {
13947: if (count > 0) {
13948: var chosen = (offset+$startcount)+7*(count-1);
13949: var depitem = $startcount + ((count-1) * 7) + 4;
13950: var currtype = form.elements[depitem].type;
13951: if (form.elements[chosen].value == 'dependency') {
13952: document.getElementById('arc_depon_'+count).style.display='block';
13953: form.elements[depitem].options.length = 0;
13954: form.elements[depitem].options[0] = new Option('Select','',true,true);
13955: for (var i=1; i<=numitems; i++) {
13956: if (i == count) {
13957: continue;
13958: }
13959: var startelement = $startcount + (i-1) * 7;
13960: for (var j=1; j<6; j++) {
13961: if ((j != 2) && (j!= 4)) {
13962: var item = startelement + j;
13963: if (form.elements[item].type == 'radio') {
13964: if (form.elements[item].checked) {
13965: if (form.elements[item].value == 'display') {
13966: var n = form.elements[depitem].options.length;
13967: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13968: }
13969: }
13970: }
13971: }
13972: }
13973: }
13974: } else {
13975: document.getElementById('arc_depon_'+count).style.display='none';
13976: form.elements[depitem].options.length = 0;
13977: form.elements[depitem].options[0] = new Option('Select','',true,true);
13978: }
13979: titleCheck(form,count,offset);
13980: }
13981: }
13982:
13983: function propagateSelect(form,count,offset) {
13984: if (count > 0) {
13985: var item = (1+offset+$startcount)+7*(count-1);
13986: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
13987: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13988: if (parents[count].length > 0) {
13989: for (var j=0; j<parents[count].length; j++) {
13990: containerSelect(form,parents[count][j],offset,picked);
13991: }
13992: }
13993: }
13994: }
13995: }
13996:
13997: function containerSelect(form,count,offset,picked) {
13998: if (count > 0) {
13999: var item = (offset+$startcount)+7*(count-1);
14000: if (form.elements[item].type == 'radio') {
14001: if (form.elements[item].value == 'dependency') {
14002: if (form.elements[item+1].type == 'select-one') {
14003: for (var i=0; i<form.elements[item+1].options.length; i++) {
14004: if (form.elements[item+1].options[i].value == picked) {
14005: form.elements[item+1].selectedIndex = i;
14006: break;
14007: }
14008: }
14009: }
14010: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14011: if (parents[count].length > 0) {
14012: for (var j=0; j<parents[count].length; j++) {
14013: containerSelect(form,parents[count][j],offset,picked);
14014: }
14015: }
14016: }
14017: }
14018: }
14019: }
14020: }
14021:
14022: function titleCheck(form,count,offset) {
14023: if (count > 0) {
14024: var chosen = (offset+$startcount)+7*(count-1);
14025: var depitem = $startcount + ((count-1) * 7) + 2;
14026: var currtype = form.elements[depitem].type;
14027: if (form.elements[chosen].value == 'display') {
14028: document.getElementById('arc_title_'+count).style.display='block';
14029: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14030: document.getElementById('archive_title_'+count).value=maintitle;
14031: }
14032: } else {
14033: document.getElementById('arc_title_'+count).style.display='none';
14034: if (currtype == 'text') {
14035: document.getElementById('archive_title_'+count).value='';
14036: }
14037: }
14038: }
14039: return;
14040: }
14041:
14042: // ]]>
14043: </script>
14044: END
14045: return $scripttag;
14046: }
14047:
14048: sub process_extracted_files {
14049: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14050: my $numitems = $env{'form.archive_count'};
14051: return if ((!$numitems) || ($numitems =~ /\D/));
14052: my @ids=&Apache::lonnet::current_machine_ids();
14053: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14054: %folders,%containers,%mapinner,%prompttofetch);
14055: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14056: if (grep(/^\Q$docuhome\E$/,@ids)) {
14057: $prefix = &LONCAPA::propath($docudom,$docuname);
14058: $pathtocheck = "$dir_root/$destination";
14059: $dir = $dir_root;
14060: $ishome = 1;
14061: } else {
14062: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14063: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14064: $dir = "$dir_root/$docudom/$docuname";
14065: }
14066: my $currdir = "$dir_root/$destination";
14067: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14068: if ($env{'form.folderpath'}) {
14069: my @items = split('&',$env{'form.folderpath'});
14070: $folders{'0'} = $items[-2];
14071: if ($env{'form.folderpath'} =~ /\:1$/) {
14072: $containers{'0'}='page';
14073: } else {
14074: $containers{'0'}='sequence';
14075: }
14076: }
14077: my @archdirs = &get_env_multiple('form.archive_directory');
14078: if ($numitems) {
14079: for (my $i=1; $i<=$numitems; $i++) {
14080: my $path = $env{'form.archive_content_'.$i};
14081: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14082: my $item = $1;
14083: $toplevelitems{$item} = $i;
14084: if (grep(/^\Q$i\E$/,@archdirs)) {
14085: $is_dir{$item} = 1;
14086: }
14087: }
14088: }
14089: }
14090: my ($output,%children,%parent,%titles,%dirorder,$result);
14091: if (keys(%toplevelitems) > 0) {
14092: my @contents = sort(keys(%toplevelitems));
14093: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14094: \%parent,\@contents,\%dirorder,\%titles);
14095: }
14096: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14097: if ($numitems) {
14098: for (my $i=1; $i<=$numitems; $i++) {
14099: next if ($env{'form.archive_'.$i} eq 'dependency');
14100: my $path = $env{'form.archive_content_'.$i};
14101: if ($path =~ /^\Q$pathtocheck\E/) {
14102: if ($env{'form.archive_'.$i} eq 'discard') {
14103: if ($prefix ne '' && $path ne '') {
14104: if (-e $prefix.$path) {
14105: if ((@archdirs > 0) &&
14106: (grep(/^\Q$i\E$/,@archdirs))) {
14107: $todeletedir{$prefix.$path} = 1;
14108: } else {
14109: $todelete{$prefix.$path} = 1;
14110: }
14111: }
14112: }
14113: } elsif ($env{'form.archive_'.$i} eq 'display') {
14114: my ($docstitle,$title,$url,$outer);
14115: ($title) = ($path =~ m{/([^/]+)$});
14116: $docstitle = $env{'form.archive_title_'.$i};
14117: if ($docstitle eq '') {
14118: $docstitle = $title;
14119: }
14120: $outer = 0;
14121: if (ref($dirorder{$i}) eq 'ARRAY') {
14122: if (@{$dirorder{$i}} > 0) {
14123: foreach my $item (reverse(@{$dirorder{$i}})) {
14124: if ($env{'form.archive_'.$item} eq 'display') {
14125: $outer = $item;
14126: last;
14127: }
14128: }
14129: }
14130: }
14131: my ($errtext,$fatal) =
14132: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14133: '/'.$folders{$outer}.'.'.
14134: $containers{$outer});
14135: next if ($fatal);
14136: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14137: if ($context eq 'coursedocs') {
14138: $mapinner{$i} = time;
14139: $folders{$i} = 'default_'.$mapinner{$i};
14140: $containers{$i} = 'sequence';
14141: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14142: $folders{$i}.'.'.$containers{$i};
14143: my $newidx = &LONCAPA::map::getresidx();
14144: $LONCAPA::map::resources[$newidx]=
14145: $docstitle.':'.$url.':false:normal:res';
14146: push(@LONCAPA::map::order,$newidx);
14147: my ($outtext,$errtext) =
14148: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14149: $docuname.'/'.$folders{$outer}.
14150: '.'.$containers{$outer},1,1);
14151: $newseqid{$i} = $newidx;
14152: unless ($errtext) {
14153: $result .= '<li>'.&mt('Folder: [_1] added to course',
14154: &HTML::Entities::encode($docstitle,'<>&"'))..
14155: '</li>'."\n";
14156: }
14157: }
14158: } else {
14159: if ($context eq 'coursedocs') {
14160: my $newidx=&LONCAPA::map::getresidx();
14161: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14162: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14163: $title;
14164: if (($outer !~ /\D/) &&
14165: (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14166: ($newidx !~ /\D/)) {
14167: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14168: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14169: }
14170: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14171: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14172: }
14173: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14174: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14175: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14176: unless ($ishome) {
14177: my $fetch = "$newdest{$i}/$title";
14178: $fetch =~ s/^\Q$prefix$dir\E//;
14179: $prompttofetch{$fetch} = 1;
14180: }
14181: }
14182: }
14183: $LONCAPA::map::resources[$newidx]=
14184: $docstitle.':'.$url.':false:normal:res';
14185: push(@LONCAPA::map::order, $newidx);
14186: my ($outtext,$errtext)=
14187: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14188: $docuname.'/'.$folders{$outer}.
14189: '.'.$containers{$outer},1,1);
14190: unless ($errtext) {
14191: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14192: $result .= '<li>'.&mt('File: [_1] added to course',
14193: &HTML::Entities::encode($docstitle,'<>&"')).
14194: '</li>'."\n";
14195: }
14196: }
14197: } else {
14198: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14199: &HTML::Entities::encode($path,'<>&"')).'<br />';
14200: }
14201: }
14202: }
14203: }
14204: } else {
14205: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14206: &HTML::Entities::encode($path,'<>&"')).'<br />';
14207: }
14208: }
14209: for (my $i=1; $i<=$numitems; $i++) {
14210: next unless ($env{'form.archive_'.$i} eq 'dependency');
14211: my $path = $env{'form.archive_content_'.$i};
14212: if ($path =~ /^\Q$pathtocheck\E/) {
14213: my ($title) = ($path =~ m{/([^/]+)$});
14214: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14215: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14216: if (ref($dirorder{$i}) eq 'ARRAY') {
14217: my ($itemidx,$fullpath,$relpath);
14218: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14219: my $container = $dirorder{$referrer{$i}}->[-1];
14220: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14221: if ($dirorder{$i}->[$j] eq $container) {
14222: $itemidx = $j;
14223: }
14224: }
14225: }
14226: if ($itemidx eq '') {
14227: $itemidx = 0;
14228: }
14229: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14230: if ($mapinner{$referrer{$i}}) {
14231: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14232: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14233: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14234: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14235: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14236: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14237: if (!-e $fullpath) {
14238: mkdir($fullpath,0755);
14239: }
14240: }
14241: } else {
14242: last;
14243: }
14244: }
14245: }
14246: } elsif ($newdest{$referrer{$i}}) {
14247: $fullpath = $newdest{$referrer{$i}};
14248: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14249: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14250: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14251: last;
14252: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14253: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14254: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14255: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14256: if (!-e $fullpath) {
14257: mkdir($fullpath,0755);
14258: }
14259: }
14260: } else {
14261: last;
14262: }
14263: }
14264: }
14265: if ($fullpath ne '') {
14266: if (-e "$prefix$path") {
14267: unless (rename("$prefix$path","$fullpath/$title")) {
14268: $warning .= &mt('Failed to rename dependency').'<br />';
14269: }
14270: }
14271: if (-e "$fullpath/$title") {
14272: my $showpath;
14273: if ($relpath ne '') {
14274: $showpath = "$relpath/$title";
14275: } else {
14276: $showpath = "/$title";
14277: }
14278: $result .= '<li>'.&mt('[_1] included as a dependency',
14279: &HTML::Entities::encode($showpath,'<>&"')).
14280: '</li>'."\n";
14281: unless ($ishome) {
14282: my $fetch = "$fullpath/$title";
14283: $fetch =~ s/^\Q$prefix$dir\E//;
14284: $prompttofetch{$fetch} = 1;
14285: }
14286: }
14287: }
14288: }
14289: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14290: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14291: &HTML::Entities::encode($path,'<>&"'),
14292: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14293: '<br />';
14294: }
14295: } else {
14296: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14297: &HTML::Entities::encode($path)).'<br />';
14298: }
14299: }
14300: if (keys(%todelete)) {
14301: foreach my $key (keys(%todelete)) {
14302: unlink($key);
14303: }
14304: }
14305: if (keys(%todeletedir)) {
14306: foreach my $key (keys(%todeletedir)) {
14307: rmdir($key);
14308: }
14309: }
14310: foreach my $dir (sort(keys(%is_dir))) {
14311: if (($pathtocheck ne '') && ($dir ne '')) {
14312: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14313: }
14314: }
14315: if ($result ne '') {
14316: $output .= '<ul>'."\n".
14317: $result."\n".
14318: '</ul>';
14319: }
14320: unless ($ishome) {
14321: my $replicationfail;
14322: foreach my $item (keys(%prompttofetch)) {
14323: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14324: unless ($fetchresult eq 'ok') {
14325: $replicationfail .= '<li>'.$item.'</li>'."\n";
14326: }
14327: }
14328: if ($replicationfail) {
14329: $output .= '<p class="LC_error">'.
14330: &mt('Course home server failed to retrieve:').'<ul>'.
14331: $replicationfail.
14332: '</ul></p>';
14333: }
14334: }
14335: } else {
14336: $warning = &mt('No items found in archive.');
14337: }
14338: if ($error) {
14339: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14340: $error.'</p>'."\n";
14341: }
14342: if ($warning) {
14343: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14344: }
14345: return $output;
14346: }
14347:
14348: sub cleanup_empty_dirs {
14349: my ($path) = @_;
14350: if (($path ne '') && (-d $path)) {
14351: if (opendir(my $dirh,$path)) {
14352: my @dircontents = grep(!/^\./,readdir($dirh));
14353: my $numitems = 0;
14354: foreach my $item (@dircontents) {
14355: if (-d "$path/$item") {
14356: &cleanup_empty_dirs("$path/$item");
14357: if (-e "$path/$item") {
14358: $numitems ++;
14359: }
14360: } else {
14361: $numitems ++;
14362: }
14363: }
14364: if ($numitems == 0) {
14365: rmdir($path);
14366: }
14367: closedir($dirh);
14368: }
14369: }
14370: return;
14371: }
14372:
14373: =pod
14374:
14375: =item * &get_folder_hierarchy()
14376:
14377: Provides hierarchy of names of folders/sub-folders containing the current
14378: item,
14379:
14380: Inputs: 3
14381: - $navmap - navmaps object
14382:
14383: - $map - url for map (either the trigger itself, or map containing
14384: the resource, which is the trigger).
14385:
14386: - $showitem - 1 => show title for map itself; 0 => do not show.
14387:
14388: Outputs: 1 @pathitems - array of folder/subfolder names.
14389:
14390: =cut
14391:
14392: sub get_folder_hierarchy {
14393: my ($navmap,$map,$showitem) = @_;
14394: my @pathitems;
14395: if (ref($navmap)) {
14396: my $mapres = $navmap->getResourceByUrl($map);
14397: if (ref($mapres)) {
14398: my $pcslist = $mapres->map_hierarchy();
14399: if ($pcslist ne '') {
14400: my @pcs = split(/,/,$pcslist);
14401: foreach my $pc (@pcs) {
14402: if ($pc == 1) {
14403: push(@pathitems,&mt('Main Content'));
14404: } else {
14405: my $res = $navmap->getByMapPc($pc);
14406: if (ref($res)) {
14407: my $title = $res->compTitle();
14408: $title =~ s/\W+/_/g;
14409: if ($title ne '') {
14410: push(@pathitems,$title);
14411: }
14412: }
14413: }
14414: }
14415: }
14416: if ($showitem) {
14417: if ($mapres->{ID} eq '0.0') {
14418: push(@pathitems,&mt('Main Content'));
14419: } else {
14420: my $maptitle = $mapres->compTitle();
14421: $maptitle =~ s/\W+/_/g;
14422: if ($maptitle ne '') {
14423: push(@pathitems,$maptitle);
14424: }
14425: }
14426: }
14427: }
14428: }
14429: return @pathitems;
14430: }
14431:
14432: =pod
14433:
14434: =item * &get_turnedin_filepath()
14435:
14436: Determines path in a user's portfolio file for storage of files uploaded
14437: to a specific essayresponse or dropbox item.
14438:
14439: Inputs: 3 required + 1 optional.
14440: $symb is symb for resource, $uname and $udom are for current user (required).
14441: $caller is optional (can be "submission", if routine is called when storing
14442: an upoaded file when "Submit Answer" button was pressed).
14443:
14444: Returns array containing $path and $multiresp.
14445: $path is path in portfolio. $multiresp is 1 if this resource contains more
14446: than one file upload item. Callers of routine should append partid as a
14447: subdirectory to $path in cases where $multiresp is 1.
14448:
14449: Called by: homework/essayresponse.pm and homework/structuretags.pm
14450:
14451: =cut
14452:
14453: sub get_turnedin_filepath {
14454: my ($symb,$uname,$udom,$caller) = @_;
14455: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14456: my $turnindir;
14457: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14458: $turnindir = $userhash{'turnindir'};
14459: my ($path,$multiresp);
14460: if ($turnindir eq '') {
14461: if ($caller eq 'submission') {
14462: $turnindir = &mt('turned in');
14463: $turnindir =~ s/\W+/_/g;
14464: my %newhash = (
14465: 'turnindir' => $turnindir,
14466: );
14467: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14468: }
14469: }
14470: if ($turnindir ne '') {
14471: $path = '/'.$turnindir.'/';
14472: my ($multipart,$turnin,@pathitems);
14473: my $navmap = Apache::lonnavmaps::navmap->new();
14474: if (defined($navmap)) {
14475: my $mapres = $navmap->getResourceByUrl($map);
14476: if (ref($mapres)) {
14477: my $pcslist = $mapres->map_hierarchy();
14478: if ($pcslist ne '') {
14479: foreach my $pc (split(/,/,$pcslist)) {
14480: my $res = $navmap->getByMapPc($pc);
14481: if (ref($res)) {
14482: my $title = $res->compTitle();
14483: $title =~ s/\W+/_/g;
14484: if ($title ne '') {
14485: if (($pc > 1) && (length($title) > 12)) {
14486: $title = substr($title,0,12);
14487: }
14488: push(@pathitems,$title);
14489: }
14490: }
14491: }
14492: }
14493: my $maptitle = $mapres->compTitle();
14494: $maptitle =~ s/\W+/_/g;
14495: if ($maptitle ne '') {
14496: if (length($maptitle) > 12) {
14497: $maptitle = substr($maptitle,0,12);
14498: }
14499: push(@pathitems,$maptitle);
14500: }
14501: unless ($env{'request.state'} eq 'construct') {
14502: my $res = $navmap->getBySymb($symb);
14503: if (ref($res)) {
14504: my $partlist = $res->parts();
14505: my $totaluploads = 0;
14506: if (ref($partlist) eq 'ARRAY') {
14507: foreach my $part (@{$partlist}) {
14508: my @types = $res->responseType($part);
14509: my @ids = $res->responseIds($part);
14510: for (my $i=0; $i < scalar(@ids); $i++) {
14511: if ($types[$i] eq 'essay') {
14512: my $partid = $part.'_'.$ids[$i];
14513: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14514: $totaluploads ++;
14515: }
14516: }
14517: }
14518: }
14519: if ($totaluploads > 1) {
14520: $multiresp = 1;
14521: }
14522: }
14523: }
14524: }
14525: } else {
14526: return;
14527: }
14528: } else {
14529: return;
14530: }
14531: my $restitle=&Apache::lonnet::gettitle($symb);
14532: $restitle =~ s/\W+/_/g;
14533: if ($restitle eq '') {
14534: $restitle = ($resurl =~ m{/[^/]+$});
14535: if ($restitle eq '') {
14536: $restitle = time;
14537: }
14538: }
14539: if (length($restitle) > 12) {
14540: $restitle = substr($restitle,0,12);
14541: }
14542: push(@pathitems,$restitle);
14543: $path .= join('/',@pathitems);
14544: }
14545: return ($path,$multiresp);
14546: }
14547:
14548: =pod
14549:
14550: =back
14551:
14552: =head1 CSV Upload/Handling functions
14553:
14554: =over 4
14555:
14556: =item * &upfile_store($r)
14557:
14558: Store uploaded file, $r should be the HTTP Request object,
14559: needs $env{'form.upfile'}
14560: returns $datatoken to be put into hidden field
14561:
14562: =cut
14563:
14564: sub upfile_store {
14565: my $r=shift;
14566: $env{'form.upfile'}=~s/\r/\n/gs;
14567: $env{'form.upfile'}=~s/\f/\n/gs;
14568: $env{'form.upfile'}=~s/\n+/\n/gs;
14569: $env{'form.upfile'}=~s/\n+$//gs;
14570:
14571: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14572: '_enroll_'.$env{'request.course.id'}.'_'.
14573: time.'_'.$$);
14574: return if ($datatoken eq '');
14575:
14576: {
14577: my $datafile = $r->dir_config('lonDaemons').
14578: '/tmp/'.$datatoken.'.tmp';
14579: if ( open(my $fh,'>',$datafile) ) {
14580: print $fh $env{'form.upfile'};
14581: close($fh);
14582: }
14583: }
14584: return $datatoken;
14585: }
14586:
14587: =pod
14588:
14589: =item * &load_tmp_file($r,$datatoken)
14590:
14591: Load uploaded file from tmp, $r should be the HTTP Request object,
14592: $datatoken is the name to assign to the temporary file.
14593: sets $env{'form.upfile'} to the contents of the file
14594:
14595: =cut
14596:
14597: sub load_tmp_file {
14598: my ($r,$datatoken) = @_;
14599: return if ($datatoken eq '');
14600: my @studentdata=();
14601: {
14602: my $studentfile = $r->dir_config('lonDaemons').
14603: '/tmp/'.$datatoken.'.tmp';
14604: if ( open(my $fh,'<',$studentfile) ) {
14605: @studentdata=<$fh>;
14606: close($fh);
14607: }
14608: }
14609: $env{'form.upfile'}=join('',@studentdata);
14610: }
14611:
14612: sub valid_datatoken {
14613: my ($datatoken) = @_;
14614: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14615: return $datatoken;
14616: }
14617: return;
14618: }
14619:
14620: =pod
14621:
14622: =item * &upfile_record_sep()
14623:
14624: Separate uploaded file into records
14625: returns array of records,
14626: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14627:
14628: =cut
14629:
14630: sub upfile_record_sep {
14631: if ($env{'form.upfiletype'} eq 'xml') {
14632: } else {
14633: my @records;
14634: foreach my $line (split(/\n/,$env{'form.upfile'})) {
14635: if ($line=~/^\s*$/) { next; }
14636: push(@records,$line);
14637: }
14638: return @records;
14639: }
14640: }
14641:
14642: =pod
14643:
14644: =item * &record_sep($record)
14645:
14646: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14647:
14648: =cut
14649:
14650: sub takeleft {
14651: my $index=shift;
14652: return substr('0000'.$index,-4,4);
14653: }
14654:
14655: sub record_sep {
14656: my $record=shift;
14657: my %components=();
14658: if ($env{'form.upfiletype'} eq 'xml') {
14659: } elsif ($env{'form.upfiletype'} eq 'space') {
14660: my $i=0;
14661: foreach my $field (split(/\s+/,$record)) {
14662: $field=~s/^(\"|\')//;
14663: $field=~s/(\"|\')$//;
14664: $components{&takeleft($i)}=$field;
14665: $i++;
14666: }
14667: } elsif ($env{'form.upfiletype'} eq 'tab') {
14668: my $i=0;
14669: foreach my $field (split(/\t/,$record)) {
14670: $field=~s/^(\"|\')//;
14671: $field=~s/(\"|\')$//;
14672: $components{&takeleft($i)}=$field;
14673: $i++;
14674: }
14675: } else {
14676: my $separator=',';
14677: if ($env{'form.upfiletype'} eq 'semisv') {
14678: $separator=';';
14679: }
14680: my $i=0;
14681: # the character we are looking for to indicate the end of a quote or a record
14682: my $looking_for=$separator;
14683: # do not add the characters to the fields
14684: my $ignore=0;
14685: # we just encountered a separator (or the beginning of the record)
14686: my $just_found_separator=1;
14687: # store the field we are working on here
14688: my $field='';
14689: # work our way through all characters in record
14690: foreach my $character ($record=~/(.)/g) {
14691: if ($character eq $looking_for) {
14692: if ($character ne $separator) {
14693: # Found the end of a quote, again looking for separator
14694: $looking_for=$separator;
14695: $ignore=1;
14696: } else {
14697: # Found a separator, store away what we got
14698: $components{&takeleft($i)}=$field;
14699: $i++;
14700: $just_found_separator=1;
14701: $ignore=0;
14702: $field='';
14703: }
14704: next;
14705: }
14706: # single or double quotation marks after a separator indicate beginning of a quote
14707: # we are now looking for the end of the quote and need to ignore separators
14708: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
14709: $looking_for=$character;
14710: next;
14711: }
14712: # ignore would be true after we reached the end of a quote
14713: if ($ignore) { next; }
14714: if (($just_found_separator) && ($character=~/\s/)) { next; }
14715: $field.=$character;
14716: $just_found_separator=0;
14717: }
14718: # catch the very last entry, since we never encountered the separator
14719: $components{&takeleft($i)}=$field;
14720: }
14721: return %components;
14722: }
14723:
14724: ######################################################
14725: ######################################################
14726:
14727: =pod
14728:
14729: =item * &upfile_select_html()
14730:
14731: Return HTML code to select a file from the users machine and specify
14732: the file type.
14733:
14734: =cut
14735:
14736: ######################################################
14737: ######################################################
14738: sub upfile_select_html {
14739: my %Types = (
14740: csv => &mt('CSV (comma separated values, spreadsheet)'),
14741: semisv => &mt('Semicolon separated values'),
14742: space => &mt('Space separated'),
14743: tab => &mt('Tabulator separated'),
14744: # xml => &mt('HTML/XML'),
14745: );
14746: my $Str = '<input type="file" name="upfile" size="50" />'.
14747: '<br />'.&mt('Type').': <select name="upfiletype">';
14748: foreach my $type (sort(keys(%Types))) {
14749: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14750: }
14751: $Str .= "</select>\n";
14752: return $Str;
14753: }
14754:
14755: sub get_samples {
14756: my ($records,$toget) = @_;
14757: my @samples=({});
14758: my $got=0;
14759: foreach my $rec (@$records) {
14760: my %temp = &record_sep($rec);
14761: if (! grep(/\S/, values(%temp))) { next; }
14762: if (%temp) {
14763: $samples[$got]=\%temp;
14764: $got++;
14765: if ($got == $toget) { last; }
14766: }
14767: }
14768: return \@samples;
14769: }
14770:
14771: ######################################################
14772: ######################################################
14773:
14774: =pod
14775:
14776: =item * &csv_print_samples($r,$records)
14777:
14778: Prints a table of sample values from each column uploaded $r is an
14779: Apache Request ref, $records is an arrayref from
14780: &Apache::loncommon::upfile_record_sep
14781:
14782: =cut
14783:
14784: ######################################################
14785: ######################################################
14786: sub csv_print_samples {
14787: my ($r,$records) = @_;
14788: my $samples = &get_samples($records,5);
14789:
14790: $r->print(&mt('Samples').'<br />'.&start_data_table().
14791: &start_data_table_header_row());
14792: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14793: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14794: $r->print(&end_data_table_header_row());
14795: foreach my $hash (@$samples) {
14796: $r->print(&start_data_table_row());
14797: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14798: $r->print('<td>');
14799: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14800: $r->print('</td>');
14801: }
14802: $r->print(&end_data_table_row());
14803: }
14804: $r->print(&end_data_table().'<br />'."\n");
14805: }
14806:
14807: ######################################################
14808: ######################################################
14809:
14810: =pod
14811:
14812: =item * &csv_print_select_table($r,$records,$d)
14813:
14814: Prints a table to create associations between values and table columns.
14815:
14816: $r is an Apache Request ref,
14817: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14818: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14819:
14820: =cut
14821:
14822: ######################################################
14823: ######################################################
14824: sub csv_print_select_table {
14825: my ($r,$records,$d) = @_;
14826: my $i=0;
14827: my $samples = &get_samples($records,1);
14828: $r->print(&mt('Associate columns with student attributes.')."\n".
14829: &start_data_table().&start_data_table_header_row().
14830: '<th>'.&mt('Attribute').'</th>'.
14831: '<th>'.&mt('Column').'</th>'.
14832: &end_data_table_header_row()."\n");
14833: foreach my $array_ref (@$d) {
14834: my ($value,$display,$defaultcol)=@{ $array_ref };
14835: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
14836:
14837: $r->print('<td><select name="f'.$i.'"'.
14838: ' onchange="javascript:flip(this.form,'.$i.');">');
14839: $r->print('<option value="none"></option>');
14840: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14841: $r->print('<option value="'.$sample.'"'.
14842: ($sample eq $defaultcol ? ' selected="selected" ' : '').
14843: '>'.&mt('Column [_1]',($sample+1)).'</option>');
14844: }
14845: $r->print('</select></td>'.&end_data_table_row()."\n");
14846: $i++;
14847: }
14848: $r->print(&end_data_table());
14849: $i--;
14850: return $i;
14851: }
14852:
14853: ######################################################
14854: ######################################################
14855:
14856: =pod
14857:
14858: =item * &csv_samples_select_table($r,$records,$d)
14859:
14860: Prints a table of sample values from the upload and can make associate samples to internal names.
14861:
14862: $r is an Apache Request ref,
14863: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14864: $d is an array of 2 element arrays (internal name, displayed name)
14865:
14866: =cut
14867:
14868: ######################################################
14869: ######################################################
14870: sub csv_samples_select_table {
14871: my ($r,$records,$d) = @_;
14872: my $i=0;
14873: #
14874: my $max_samples = 5;
14875: my $samples = &get_samples($records,$max_samples);
14876: $r->print(&start_data_table().
14877: &start_data_table_header_row().'<th>'.
14878: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14879: &end_data_table_header_row());
14880:
14881: foreach my $key (sort(keys(%{ $samples->[0] }))) {
14882: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14883: ' onchange="javascript:flip(this.form,'.$i.');">');
14884: foreach my $option (@$d) {
14885: my ($value,$display,$defaultcol)=@{ $option };
14886: $r->print('<option value="'.$value.'"'.
14887: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14888: $display.'</option>');
14889: }
14890: $r->print('</select></td><td>');
14891: foreach my $line (0..($max_samples-1)) {
14892: if (defined($samples->[$line]{$key})) {
14893: $r->print($samples->[$line]{$key}."<br />\n");
14894: }
14895: }
14896: $r->print('</td>'.&end_data_table_row());
14897: $i++;
14898: }
14899: $r->print(&end_data_table());
14900: $i--;
14901: return($i);
14902: }
14903:
14904: ######################################################
14905: ######################################################
14906:
14907: =pod
14908:
14909: =item * &clean_excel_name($name)
14910:
14911: Returns a replacement for $name which does not contain any illegal characters.
14912:
14913: =cut
14914:
14915: ######################################################
14916: ######################################################
14917: sub clean_excel_name {
14918: my ($name) = @_;
14919: $name =~ s/[:\*\?\/\\]//g;
14920: if (length($name) > 31) {
14921: $name = substr($name,0,31);
14922: }
14923: return $name;
14924: }
14925:
14926: =pod
14927:
14928: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14929:
14930: Returns either 1 or undef
14931:
14932: 1 if the part is to be hidden, undef if it is to be shown
14933:
14934: Arguments are:
14935:
14936: $id the id of the part to be checked
14937: $symb, optional the symb of the resource to check
14938: $udom, optional the domain of the user to check for
14939: $uname, optional the username of the user to check for
14940:
14941: =cut
14942:
14943: sub check_if_partid_hidden {
14944: my ($id,$symb,$udom,$uname) = @_;
14945: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14946: $symb,$udom,$uname);
14947: my $truth=1;
14948: #if the string starts with !, then the list is the list to show not hide
14949: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14950: my @hiddenlist=split(/,/,$hiddenparts);
14951: foreach my $checkid (@hiddenlist) {
14952: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14953: }
14954: return !$truth;
14955: }
14956:
14957:
14958: ############################################################
14959: ############################################################
14960:
14961: =pod
14962:
14963: =back
14964:
14965: =head1 cgi-bin script and graphing routines
14966:
14967: =over 4
14968:
14969: =item * &get_cgi_id()
14970:
14971: Inputs: none
14972:
14973: Returns an id which can be used to pass environment variables
14974: to various cgi-bin scripts. These environment variables will
14975: be removed from the users environment after a given time by
14976: the routine &Apache::lonnet::transfer_profile_to_env.
14977:
14978: =cut
14979:
14980: ############################################################
14981: ############################################################
14982: my $uniq=0;
14983: sub get_cgi_id {
14984: $uniq=($uniq+1)%100000;
14985: return (time.'_'.$$.'_'.$uniq);
14986: }
14987:
14988: ############################################################
14989: ############################################################
14990:
14991: =pod
14992:
14993: =item * &DrawBarGraph()
14994:
14995: Facilitates the plotting of data in a (stacked) bar graph.
14996: Puts plot definition data into the users environment in order for
14997: graph.png to plot it. Returns an <img> tag for the plot.
14998: The bars on the plot are labeled '1','2',...,'n'.
14999:
15000: Inputs:
15001:
15002: =over 4
15003:
15004: =item $Title: string, the title of the plot
15005:
15006: =item $xlabel: string, text describing the X-axis of the plot
15007:
15008: =item $ylabel: string, text describing the Y-axis of the plot
15009:
15010: =item $Max: scalar, the maximum Y value to use in the plot
15011: If $Max is < any data point, the graph will not be rendered.
15012:
15013: =item $colors: array ref holding the colors to be used for the data sets when
15014: they are plotted. If undefined, default values will be used.
15015:
15016: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15017:
15018: =item @Values: An array of array references. Each array reference holds data
15019: to be plotted in a stacked bar chart.
15020:
15021: =item If the final element of @Values is a hash reference the key/value
15022: pairs will be added to the graph definition.
15023:
15024: =back
15025:
15026: Returns:
15027:
15028: An <img> tag which references graph.png and the appropriate identifying
15029: information for the plot.
15030:
15031: =cut
15032:
15033: ############################################################
15034: ############################################################
15035: sub DrawBarGraph {
15036: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15037: #
15038: if (! defined($colors)) {
15039: $colors = ['#33ff00',
15040: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15041: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15042: ];
15043: }
15044: my $extra_settings = {};
15045: if (ref($Values[-1]) eq 'HASH') {
15046: $extra_settings = pop(@Values);
15047: }
15048: #
15049: my $identifier = &get_cgi_id();
15050: my $id = 'cgi.'.$identifier;
15051: if (! @Values || ref($Values[0]) ne 'ARRAY') {
15052: return '';
15053: }
15054: #
15055: my @Labels;
15056: if (defined($labels)) {
15057: @Labels = @$labels;
15058: } else {
15059: for (my $i=0;$i<@{$Values[0]};$i++) {
15060: push(@Labels,$i+1);
15061: }
15062: }
15063: #
15064: my $NumBars = scalar(@{$Values[0]});
15065: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15066: my %ValuesHash;
15067: my $NumSets=1;
15068: foreach my $array (@Values) {
15069: next if (! ref($array));
15070: $ValuesHash{$id.'.data.'.$NumSets++} =
15071: join(',',@$array);
15072: }
15073: #
15074: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15075: if ($NumBars < 3) {
15076: $width = 120+$NumBars*32;
15077: $xskip = 1;
15078: $bar_width = 30;
15079: } elsif ($NumBars < 5) {
15080: $width = 120+$NumBars*20;
15081: $xskip = 1;
15082: $bar_width = 20;
15083: } elsif ($NumBars < 10) {
15084: $width = 120+$NumBars*15;
15085: $xskip = 1;
15086: $bar_width = 15;
15087: } elsif ($NumBars <= 25) {
15088: $width = 120+$NumBars*11;
15089: $xskip = 5;
15090: $bar_width = 8;
15091: } elsif ($NumBars <= 50) {
15092: $width = 120+$NumBars*8;
15093: $xskip = 5;
15094: $bar_width = 4;
15095: } else {
15096: $width = 120+$NumBars*8;
15097: $xskip = 5;
15098: $bar_width = 4;
15099: }
15100: #
15101: $Max = 1 if ($Max < 1);
15102: if ( int($Max) < $Max ) {
15103: $Max++;
15104: $Max = int($Max);
15105: }
15106: $Title = '' if (! defined($Title));
15107: $xlabel = '' if (! defined($xlabel));
15108: $ylabel = '' if (! defined($ylabel));
15109: $ValuesHash{$id.'.title'} = &escape($Title);
15110: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
15111: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
15112: $ValuesHash{$id.'.y_max_value'} = $Max;
15113: $ValuesHash{$id.'.NumBars'} = $NumBars;
15114: $ValuesHash{$id.'.NumSets'} = $NumSets;
15115: $ValuesHash{$id.'.PlotType'} = 'bar';
15116: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15117: $ValuesHash{$id.'.height'} = $height;
15118: $ValuesHash{$id.'.width'} = $width;
15119: $ValuesHash{$id.'.xskip'} = $xskip;
15120: $ValuesHash{$id.'.bar_width'} = $bar_width;
15121: $ValuesHash{$id.'.labels'} = join(',',@Labels);
15122: #
15123: # Deal with other parameters
15124: while (my ($key,$value) = each(%$extra_settings)) {
15125: $ValuesHash{$id.'.'.$key} = $value;
15126: }
15127: #
15128: &Apache::lonnet::appenv(\%ValuesHash);
15129: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15130: }
15131:
15132: ############################################################
15133: ############################################################
15134:
15135: =pod
15136:
15137: =item * &DrawXYGraph()
15138:
15139: Facilitates the plotting of data in an XY graph.
15140: Puts plot definition data into the users environment in order for
15141: graph.png to plot it. Returns an <img> tag for the plot.
15142:
15143: Inputs:
15144:
15145: =over 4
15146:
15147: =item $Title: string, the title of the plot
15148:
15149: =item $xlabel: string, text describing the X-axis of the plot
15150:
15151: =item $ylabel: string, text describing the Y-axis of the plot
15152:
15153: =item $Max: scalar, the maximum Y value to use in the plot
15154: If $Max is < any data point, the graph will not be rendered.
15155:
15156: =item $colors: Array ref containing the hex color codes for the data to be
15157: plotted in. If undefined, default values will be used.
15158:
15159: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15160:
15161: =item $Ydata: Array ref containing Array refs.
15162: Each of the contained arrays will be plotted as a separate curve.
15163:
15164: =item %Values: hash indicating or overriding any default values which are
15165: passed to graph.png.
15166: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15167:
15168: =back
15169:
15170: Returns:
15171:
15172: An <img> tag which references graph.png and the appropriate identifying
15173: information for the plot.
15174:
15175: =cut
15176:
15177: ############################################################
15178: ############################################################
15179: sub DrawXYGraph {
15180: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15181: #
15182: # Create the identifier for the graph
15183: my $identifier = &get_cgi_id();
15184: my $id = 'cgi.'.$identifier;
15185: #
15186: $Title = '' if (! defined($Title));
15187: $xlabel = '' if (! defined($xlabel));
15188: $ylabel = '' if (! defined($ylabel));
15189: my %ValuesHash =
15190: (
15191: $id.'.title' => &escape($Title),
15192: $id.'.xlabel' => &escape($xlabel),
15193: $id.'.ylabel' => &escape($ylabel),
15194: $id.'.y_max_value'=> $Max,
15195: $id.'.labels' => join(',',@$Xlabels),
15196: $id.'.PlotType' => 'XY',
15197: );
15198: #
15199: if (defined($colors) && ref($colors) eq 'ARRAY') {
15200: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15201: }
15202: #
15203: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15204: return '';
15205: }
15206: my $NumSets=1;
15207: foreach my $array (@{$Ydata}){
15208: next if (! ref($array));
15209: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15210: }
15211: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15212: #
15213: # Deal with other parameters
15214: while (my ($key,$value) = each(%Values)) {
15215: $ValuesHash{$id.'.'.$key} = $value;
15216: }
15217: #
15218: &Apache::lonnet::appenv(\%ValuesHash);
15219: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15220: }
15221:
15222: ############################################################
15223: ############################################################
15224:
15225: =pod
15226:
15227: =item * &DrawXYYGraph()
15228:
15229: Facilitates the plotting of data in an XY graph with two Y axes.
15230: Puts plot definition data into the users environment in order for
15231: graph.png to plot it. Returns an <img> tag for the plot.
15232:
15233: Inputs:
15234:
15235: =over 4
15236:
15237: =item $Title: string, the title of the plot
15238:
15239: =item $xlabel: string, text describing the X-axis of the plot
15240:
15241: =item $ylabel: string, text describing the Y-axis of the plot
15242:
15243: =item $colors: Array ref containing the hex color codes for the data to be
15244: plotted in. If undefined, default values will be used.
15245:
15246: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15247:
15248: =item $Ydata1: The first data set
15249:
15250: =item $Min1: The minimum value of the left Y-axis
15251:
15252: =item $Max1: The maximum value of the left Y-axis
15253:
15254: =item $Ydata2: The second data set
15255:
15256: =item $Min2: The minimum value of the right Y-axis
15257:
15258: =item $Max2: The maximum value of the left Y-axis
15259:
15260: =item %Values: hash indicating or overriding any default values which are
15261: passed to graph.png.
15262: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15263:
15264: =back
15265:
15266: Returns:
15267:
15268: An <img> tag which references graph.png and the appropriate identifying
15269: information for the plot.
15270:
15271: =cut
15272:
15273: ############################################################
15274: ############################################################
15275: sub DrawXYYGraph {
15276: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15277: $Ydata2,$Min2,$Max2,%Values)=@_;
15278: #
15279: # Create the identifier for the graph
15280: my $identifier = &get_cgi_id();
15281: my $id = 'cgi.'.$identifier;
15282: #
15283: $Title = '' if (! defined($Title));
15284: $xlabel = '' if (! defined($xlabel));
15285: $ylabel = '' if (! defined($ylabel));
15286: my %ValuesHash =
15287: (
15288: $id.'.title' => &escape($Title),
15289: $id.'.xlabel' => &escape($xlabel),
15290: $id.'.ylabel' => &escape($ylabel),
15291: $id.'.labels' => join(',',@$Xlabels),
15292: $id.'.PlotType' => 'XY',
15293: $id.'.NumSets' => 2,
15294: $id.'.two_axes' => 1,
15295: $id.'.y1_max_value' => $Max1,
15296: $id.'.y1_min_value' => $Min1,
15297: $id.'.y2_max_value' => $Max2,
15298: $id.'.y2_min_value' => $Min2,
15299: );
15300: #
15301: if (defined($colors) && ref($colors) eq 'ARRAY') {
15302: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15303: }
15304: #
15305: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15306: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15307: return '';
15308: }
15309: my $NumSets=1;
15310: foreach my $array ($Ydata1,$Ydata2){
15311: next if (! ref($array));
15312: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15313: }
15314: #
15315: # Deal with other parameters
15316: while (my ($key,$value) = each(%Values)) {
15317: $ValuesHash{$id.'.'.$key} = $value;
15318: }
15319: #
15320: &Apache::lonnet::appenv(\%ValuesHash);
15321: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15322: }
15323:
15324: ############################################################
15325: ############################################################
15326:
15327: =pod
15328:
15329: =back
15330:
15331: =head1 Statistics helper routines?
15332:
15333: Bad place for them but what the hell.
15334:
15335: =over 4
15336:
15337: =item * &chartlink()
15338:
15339: Returns a link to the chart for a specific student.
15340:
15341: Inputs:
15342:
15343: =over 4
15344:
15345: =item $linktext: The text of the link
15346:
15347: =item $sname: The students username
15348:
15349: =item $sdomain: The students domain
15350:
15351: =back
15352:
15353: =back
15354:
15355: =cut
15356:
15357: ############################################################
15358: ############################################################
15359: sub chartlink {
15360: my ($linktext, $sname, $sdomain) = @_;
15361: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15362: '&SelectedStudent='.&escape($sname.':'.$sdomain).
15363: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
15364: '">'.$linktext.'</a>';
15365: }
15366:
15367: #######################################################
15368: #######################################################
15369:
15370: =pod
15371:
15372: =head1 Course Environment Routines
15373:
15374: =over 4
15375:
15376: =item * &restore_course_settings()
15377:
15378: =item * &store_course_settings()
15379:
15380: Restores/Store indicated form parameters from the course environment.
15381: Will not overwrite existing values of the form parameters.
15382:
15383: Inputs:
15384: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15385:
15386: a hash ref describing the data to be stored. For example:
15387:
15388: %Save_Parameters = ('Status' => 'scalar',
15389: 'chartoutputmode' => 'scalar',
15390: 'chartoutputdata' => 'scalar',
15391: 'Section' => 'array',
15392: 'Group' => 'array',
15393: 'StudentData' => 'array',
15394: 'Maps' => 'array');
15395:
15396: Returns: both routines return nothing
15397:
15398: =back
15399:
15400: =cut
15401:
15402: #######################################################
15403: #######################################################
15404: sub store_course_settings {
15405: return &store_settings($env{'request.course.id'},@_);
15406: }
15407:
15408: sub store_settings {
15409: # save to the environment
15410: # appenv the same items, just to be safe
15411: my $udom = $env{'user.domain'};
15412: my $uname = $env{'user.name'};
15413: my ($context,$prefix,$Settings) = @_;
15414: my %SaveHash;
15415: my %AppHash;
15416: while (my ($setting,$type) = each(%$Settings)) {
15417: my $basename = join('.','internal',$context,$prefix,$setting);
15418: my $envname = 'environment.'.$basename;
15419: if (exists($env{'form.'.$setting})) {
15420: # Save this value away
15421: if ($type eq 'scalar' &&
15422: (! exists($env{$envname}) ||
15423: $env{$envname} ne $env{'form.'.$setting})) {
15424: $SaveHash{$basename} = $env{'form.'.$setting};
15425: $AppHash{$envname} = $env{'form.'.$setting};
15426: } elsif ($type eq 'array') {
15427: my $stored_form;
15428: if (ref($env{'form.'.$setting})) {
15429: $stored_form = join(',',
15430: map {
15431: &escape($_);
15432: } sort(@{$env{'form.'.$setting}}));
15433: } else {
15434: $stored_form =
15435: &escape($env{'form.'.$setting});
15436: }
15437: # Determine if the array contents are the same.
15438: if ($stored_form ne $env{$envname}) {
15439: $SaveHash{$basename} = $stored_form;
15440: $AppHash{$envname} = $stored_form;
15441: }
15442: }
15443: }
15444: }
15445: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15446: $udom,$uname);
15447: if ($put_result !~ /^(ok|delayed)/) {
15448: &Apache::lonnet::logthis('unable to save form parameters, '.
15449: 'got error:'.$put_result);
15450: }
15451: # Make sure these settings stick around in this session, too
15452: &Apache::lonnet::appenv(\%AppHash);
15453: return;
15454: }
15455:
15456: sub restore_course_settings {
15457: return &restore_settings($env{'request.course.id'},@_);
15458: }
15459:
15460: sub restore_settings {
15461: my ($context,$prefix,$Settings) = @_;
15462: while (my ($setting,$type) = each(%$Settings)) {
15463: next if (exists($env{'form.'.$setting}));
15464: my $envname = 'environment.internal.'.$context.'.'.$prefix.
15465: '.'.$setting;
15466: if (exists($env{$envname})) {
15467: if ($type eq 'scalar') {
15468: $env{'form.'.$setting} = $env{$envname};
15469: } elsif ($type eq 'array') {
15470: $env{'form.'.$setting} = [
15471: map {
15472: &unescape($_);
15473: } split(',',$env{$envname})
15474: ];
15475: }
15476: }
15477: }
15478: }
15479:
15480: #######################################################
15481: #######################################################
15482:
15483: =pod
15484:
15485: =head1 Domain E-mail Routines
15486:
15487: =over 4
15488:
15489: =item * &build_recipient_list()
15490:
15491: Build recipient lists for following types of e-mail:
15492: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15493: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15494: module change checking, student/employee ID conflict checks, as
15495: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15496: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15497:
15498: Inputs:
15499: defmail (scalar - email address of default recipient),
15500: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15501: requestsmail, updatesmail, or idconflictsmail).
15502:
15503: defdom (domain for which to retrieve configuration settings),
15504:
15505: origmail (scalar - email address of recipient from loncapa.conf,
15506: i.e., predates configuration by DC via domainprefs.pm
15507:
15508: $requname username of requester (if mailing type is helpdeskmail)
15509:
15510: $requdom domain of requester (if mailing type is helpdeskmail)
15511:
15512: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15513:
15514: Returns: comma separated list of addresses to which to send e-mail.
15515:
15516: =back
15517:
15518: =cut
15519:
15520: ############################################################
15521: ############################################################
15522: sub build_recipient_list {
15523: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15524: my @recipients;
15525: my ($otheremails,$lastresort,$allbcc,$addtext);
15526: my %domconfig =
15527: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15528: if (ref($domconfig{'contacts'}) eq 'HASH') {
15529: if (exists($domconfig{'contacts'}{$mailing})) {
15530: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15531: my @contacts = ('adminemail','supportemail');
15532: foreach my $item (@contacts) {
15533: if ($domconfig{'contacts'}{$mailing}{$item}) {
15534: my $addr = $domconfig{'contacts'}{$item};
15535: if (!grep(/^\Q$addr\E$/,@recipients)) {
15536: push(@recipients,$addr);
15537: }
15538: }
15539: }
15540: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15541: if ($mailing eq 'helpdeskmail') {
15542: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15543: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15544: my @ok_bccs;
15545: foreach my $bcc (@bccs) {
15546: $bcc =~ s/^\s+//g;
15547: $bcc =~ s/\s+$//g;
15548: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15549: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15550: push(@ok_bccs,$bcc);
15551: }
15552: }
15553: }
15554: if (@ok_bccs > 0) {
15555: $allbcc = join(', ',@ok_bccs);
15556: }
15557: }
15558: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15559: }
15560: }
15561: } elsif ($origmail ne '') {
15562: $lastresort = $origmail;
15563: }
15564: if ($mailing eq 'helpdeskmail') {
15565: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15566: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15567: my ($inststatus,$inststatus_checked);
15568: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15569: ($env{'user.domain'} ne 'public')) {
15570: $inststatus_checked = 1;
15571: $inststatus = $env{'environment.inststatus'};
15572: }
15573: unless ($inststatus_checked) {
15574: if (($requname ne '') && ($requdom ne '')) {
15575: if (($requname =~ /^$match_username$/) &&
15576: ($requdom =~ /^$match_domain$/) &&
15577: (&Apache::lonnet::domain($requdom))) {
15578: my $requhome = &Apache::lonnet::homeserver($requname,
15579: $requdom);
15580: unless ($requhome eq 'no_host') {
15581: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15582: $inststatus = $userenv{'inststatus'};
15583: $inststatus_checked = 1;
15584: }
15585: }
15586: }
15587: }
15588: unless ($inststatus_checked) {
15589: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15590: my %srch = (srchby => 'email',
15591: srchdomain => $defdom,
15592: srchterm => $reqemail,
15593: srchtype => 'exact');
15594: my %srch_results = &Apache::lonnet::usersearch(\%srch);
15595: foreach my $uname (keys(%srch_results)) {
15596: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15597: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15598: $inststatus_checked = 1;
15599: last;
15600: }
15601: }
15602: unless ($inststatus_checked) {
15603: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15604: if ($dirsrchres eq 'ok') {
15605: foreach my $uname (keys(%srch_results)) {
15606: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15607: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15608: $inststatus_checked = 1;
15609: last;
15610: }
15611: }
15612: }
15613: }
15614: }
15615: }
15616: if ($inststatus ne '') {
15617: foreach my $status (split(/\:/,$inststatus)) {
15618: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15619: my @contacts = ('adminemail','supportemail');
15620: foreach my $item (@contacts) {
15621: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15622: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15623: if (!grep(/^\Q$addr\E$/,@recipients)) {
15624: push(@recipients,$addr);
15625: }
15626: }
15627: }
15628: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15629: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15630: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15631: my @ok_bccs;
15632: foreach my $bcc (@bccs) {
15633: $bcc =~ s/^\s+//g;
15634: $bcc =~ s/\s+$//g;
15635: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15636: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15637: push(@ok_bccs,$bcc);
15638: }
15639: }
15640: }
15641: if (@ok_bccs > 0) {
15642: $allbcc = join(', ',@ok_bccs);
15643: }
15644: }
15645: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15646: last;
15647: }
15648: }
15649: }
15650: }
15651: }
15652: } elsif ($origmail ne '') {
15653: $lastresort = $origmail;
15654: }
15655: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15656: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15657: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15658: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15659: my %what = (
15660: perlvar => 1,
15661: );
15662: my $primary = &Apache::lonnet::domain($defdom,'primary');
15663: if ($primary) {
15664: my $gotaddr;
15665: my ($result,$returnhash) =
15666: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15667: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15668: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15669: $lastresort = $returnhash->{'lonSupportEMail'};
15670: $gotaddr = 1;
15671: }
15672: }
15673: unless ($gotaddr) {
15674: my $uintdom = &Apache::lonnet::internet_dom($primary);
15675: my $intdom = &Apache::lonnet::internet_dom($lonhost);
15676: unless ($uintdom eq $intdom) {
15677: my %domconfig =
15678: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15679: if (ref($domconfig{'contacts'}) eq 'HASH') {
15680: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15681: my @contacts = ('adminemail','supportemail');
15682: foreach my $item (@contacts) {
15683: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15684: my $addr = $domconfig{'contacts'}{$item};
15685: if (!grep(/^\Q$addr\E$/,@recipients)) {
15686: push(@recipients,$addr);
15687: }
15688: }
15689: }
15690: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15691: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15692: }
15693: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15694: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15695: my @ok_bccs;
15696: foreach my $bcc (@bccs) {
15697: $bcc =~ s/^\s+//g;
15698: $bcc =~ s/\s+$//g;
15699: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15700: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15701: push(@ok_bccs,$bcc);
15702: }
15703: }
15704: }
15705: if (@ok_bccs > 0) {
15706: $allbcc = join(', ',@ok_bccs);
15707: }
15708: }
15709: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15710: }
15711: }
15712: }
15713: }
15714: }
15715: }
15716: }
15717: if (defined($defmail)) {
15718: if ($defmail ne '') {
15719: push(@recipients,$defmail);
15720: }
15721: }
15722: if ($otheremails) {
15723: my @others;
15724: if ($otheremails =~ /,/) {
15725: @others = split(/,/,$otheremails);
15726: } else {
15727: push(@others,$otheremails);
15728: }
15729: foreach my $addr (@others) {
15730: if (!grep(/^\Q$addr\E$/,@recipients)) {
15731: push(@recipients,$addr);
15732: }
15733: }
15734: }
15735: if ($mailing eq 'helpdeskmail') {
15736: if ((!@recipients) && ($lastresort ne '')) {
15737: push(@recipients,$lastresort);
15738: }
15739: } elsif ($lastresort ne '') {
15740: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15741: push(@recipients,$lastresort);
15742: }
15743: }
15744: my $recipientlist = join(',',@recipients);
15745: if (wantarray) {
15746: return ($recipientlist,$allbcc,$addtext);
15747: } else {
15748: return $recipientlist;
15749: }
15750: }
15751:
15752: ############################################################
15753: ############################################################
15754:
15755: =pod
15756:
15757: =head1 Course Catalog Routines
15758:
15759: =over 4
15760:
15761: =item * &gather_categories()
15762:
15763: Converts category definitions - keys of categories hash stored in
15764: coursecategories in configuration.db on the primary library server in a
15765: domain - to an array. Also generates javascript and idx hash used to
15766: generate Domain Coordinator interface for editing Course Categories.
15767:
15768: Inputs:
15769:
15770: categories (reference to hash of category definitions).
15771:
15772: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15773: categories and subcategories).
15774:
15775: idx (reference to hash of counters used in Domain Coordinator interface for
15776: editing Course Categories).
15777:
15778: jsarray (reference to array of categories used to create Javascript arrays for
15779: Domain Coordinator interface for editing Course Categories).
15780:
15781: Returns: nothing
15782:
15783: Side effects: populates cats, idx and jsarray.
15784:
15785: =cut
15786:
15787: sub gather_categories {
15788: my ($categories,$cats,$idx,$jsarray) = @_;
15789: my %counters;
15790: my $num = 0;
15791: foreach my $item (keys(%{$categories})) {
15792: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15793: if ($container eq '' && $depth == 0) {
15794: $cats->[$depth][$categories->{$item}] = $cat;
15795: } else {
15796: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15797: }
15798: my ($escitem,$tail) = split(/:/,$item,2);
15799: if ($counters{$tail} eq '') {
15800: $counters{$tail} = $num;
15801: $num ++;
15802: }
15803: if (ref($idx) eq 'HASH') {
15804: $idx->{$item} = $counters{$tail};
15805: }
15806: if (ref($jsarray) eq 'ARRAY') {
15807: push(@{$jsarray->[$counters{$tail}]},$item);
15808: }
15809: }
15810: return;
15811: }
15812:
15813: =pod
15814:
15815: =item * &extract_categories()
15816:
15817: Used to generate breadcrumb trails for course categories.
15818:
15819: Inputs:
15820:
15821: categories (reference to hash of category definitions).
15822:
15823: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15824: categories and subcategories).
15825:
15826: trails (reference to array of breacrumb trails for each category).
15827:
15828: allitems (reference to hash - key is category key
15829: (format: escaped(name):escaped(parent category):depth in hierarchy).
15830:
15831: idx (reference to hash of counters used in Domain Coordinator interface for
15832: editing Course Categories).
15833:
15834: jsarray (reference to array of categories used to create Javascript arrays for
15835: Domain Coordinator interface for editing Course Categories).
15836:
15837: subcats (reference to hash of arrays containing all subcategories within each
15838: category, -recursive)
15839:
15840: maxd (reference to hash used to hold max depth for all top-level categories).
15841:
15842: Returns: nothing
15843:
15844: Side effects: populates trails and allitems hash references.
15845:
15846: =cut
15847:
15848: sub extract_categories {
15849: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15850: if (ref($categories) eq 'HASH') {
15851: &gather_categories($categories,$cats,$idx,$jsarray);
15852: if (ref($cats->[0]) eq 'ARRAY') {
15853: for (my $i=0; $i<@{$cats->[0]}; $i++) {
15854: my $name = $cats->[0][$i];
15855: my $item = &escape($name).'::0';
15856: my $trailstr;
15857: if ($name eq 'instcode') {
15858: $trailstr = &mt('Official courses (with institutional codes)');
15859: } elsif ($name eq 'communities') {
15860: $trailstr = &mt('Communities');
15861: } else {
15862: $trailstr = $name;
15863: }
15864: if ($allitems->{$item} eq '') {
15865: push(@{$trails},$trailstr);
15866: $allitems->{$item} = scalar(@{$trails})-1;
15867: }
15868: my @parents = ($name);
15869: if (ref($cats->[1]{$name}) eq 'ARRAY') {
15870: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15871: my $category = $cats->[1]{$name}[$j];
15872: if (ref($subcats) eq 'HASH') {
15873: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15874: }
15875: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15876: }
15877: } else {
15878: if (ref($subcats) eq 'HASH') {
15879: $subcats->{$item} = [];
15880: }
15881: if (ref($maxd) eq 'HASH') {
15882: $maxd->{$name} = 1;
15883: }
15884: }
15885: }
15886: }
15887: }
15888: return;
15889: }
15890:
15891: =pod
15892:
15893: =item * &recurse_categories()
15894:
15895: Recursively used to generate breadcrumb trails for course categories.
15896:
15897: Inputs:
15898:
15899: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15900: categories and subcategories).
15901:
15902: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15903:
15904: category (current course category, for which breadcrumb trail is being generated).
15905:
15906: trails (reference to array of breadcrumb trails for each category).
15907:
15908: allitems (reference to hash - key is category key
15909: (format: escaped(name):escaped(parent category):depth in hierarchy).
15910:
15911: parents (array containing containers directories for current category,
15912: back to top level).
15913:
15914: Returns: nothing
15915:
15916: Side effects: populates trails and allitems hash references
15917:
15918: =cut
15919:
15920: sub recurse_categories {
15921: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15922: my $shallower = $depth - 1;
15923: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15924: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15925: my $name = $cats->[$depth]{$category}[$k];
15926: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15927: my $trailstr = join(' » ',(@{$parents},$category));
15928: if ($allitems->{$item} eq '') {
15929: push(@{$trails},$trailstr);
15930: $allitems->{$item} = scalar(@{$trails})-1;
15931: }
15932: my $deeper = $depth+1;
15933: push(@{$parents},$category);
15934: if (ref($subcats) eq 'HASH') {
15935: my $subcat = &escape($name).':'.$category.':'.$depth;
15936: for (my $j=@{$parents}; $j>=0; $j--) {
15937: my $higher;
15938: if ($j > 0) {
15939: $higher = &escape($parents->[$j]).':'.
15940: &escape($parents->[$j-1]).':'.$j;
15941: } else {
15942: $higher = &escape($parents->[$j]).'::'.$j;
15943: }
15944: push(@{$subcats->{$higher}},$subcat);
15945: }
15946: }
15947: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15948: $subcats,$maxd);
15949: pop(@{$parents});
15950: }
15951: } else {
15952: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15953: my $trailstr = join(' » ',(@{$parents},$category));
15954: if ($allitems->{$item} eq '') {
15955: push(@{$trails},$trailstr);
15956: $allitems->{$item} = scalar(@{$trails})-1;
15957: }
15958: if (ref($maxd) eq 'HASH') {
15959: if ($depth > $maxd->{$parents->[0]}) {
15960: $maxd->{$parents->[0]} = $depth;
15961: }
15962: }
15963: }
15964: return;
15965: }
15966:
15967: =pod
15968:
15969: =item * &assign_categories_table()
15970:
15971: Create a datatable for display of hierarchical categories in a domain,
15972: with checkboxes to allow a course to be categorized.
15973:
15974: Inputs:
15975:
15976: cathash - reference to hash of categories defined for the domain (from
15977: configuration.db)
15978:
15979: currcat - scalar with an & separated list of categories assigned to a course.
15980:
15981: type - scalar contains course type (Course or Community).
15982:
15983: disabled - scalar (optional) contains disabled="disabled" if input elements are
15984: to be readonly (e.g., Domain Helpdesk role viewing course settings).
15985:
15986: Returns: $output (markup to be displayed)
15987:
15988: =cut
15989:
15990: sub assign_categories_table {
15991: my ($cathash,$currcat,$type,$disabled) = @_;
15992: my $output;
15993: if (ref($cathash) eq 'HASH') {
15994: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15995: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15996: $maxdepth = scalar(@cats);
15997: if (@cats > 0) {
15998: my $itemcount = 0;
15999: if (ref($cats[0]) eq 'ARRAY') {
16000: my @currcategories;
16001: if ($currcat ne '') {
16002: @currcategories = split('&',$currcat);
16003: }
16004: my $table;
16005: for (my $i=0; $i<@{$cats[0]}; $i++) {
16006: my $parent = $cats[0][$i];
16007: next if ($parent eq 'instcode');
16008: if ($type eq 'Community') {
16009: next unless ($parent eq 'communities');
16010: } else {
16011: next if ($parent eq 'communities');
16012: }
16013: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16014: my $item = &escape($parent).'::0';
16015: my $checked = '';
16016: if (@currcategories > 0) {
16017: if (grep(/^\Q$item\E$/,@currcategories)) {
16018: $checked = ' checked="checked"';
16019: }
16020: }
16021: my $parent_title = $parent;
16022: if ($parent eq 'communities') {
16023: $parent_title = &mt('Communities');
16024: }
16025: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16026: '<input type="checkbox" name="usecategory" value="'.
16027: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16028: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16029: my $depth = 1;
16030: push(@path,$parent);
16031: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16032: pop(@path);
16033: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16034: $itemcount ++;
16035: }
16036: if ($itemcount) {
16037: $output = &Apache::loncommon::start_data_table().
16038: $table.
16039: &Apache::loncommon::end_data_table();
16040: }
16041: }
16042: }
16043: }
16044: return $output;
16045: }
16046:
16047: =pod
16048:
16049: =item * &assign_category_rows()
16050:
16051: Create a datatable row for display of nested categories in a domain,
16052: with checkboxes to allow a course to be categorized,called recursively.
16053:
16054: Inputs:
16055:
16056: itemcount - track row number for alternating colors
16057:
16058: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16059: categories and subcategories.
16060:
16061: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16062:
16063: parent - parent of current category item
16064:
16065: path - Array containing all categories back up through the hierarchy from the
16066: current category to the top level.
16067:
16068: currcategories - reference to array of current categories assigned to the course
16069:
16070: disabled - scalar (optional) contains disabled="disabled" if input elements are
16071: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16072:
16073: Returns: $output (markup to be displayed).
16074:
16075: =cut
16076:
16077: sub assign_category_rows {
16078: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16079: my ($text,$name,$item,$chgstr);
16080: if (ref($cats) eq 'ARRAY') {
16081: my $maxdepth = scalar(@{$cats});
16082: if (ref($cats->[$depth]) eq 'HASH') {
16083: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16084: my $numchildren = @{$cats->[$depth]{$parent}};
16085: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16086: $text .= '<td><table class="LC_data_table">';
16087: for (my $j=0; $j<$numchildren; $j++) {
16088: $name = $cats->[$depth]{$parent}[$j];
16089: $item = &escape($name).':'.&escape($parent).':'.$depth;
16090: my $deeper = $depth+1;
16091: my $checked = '';
16092: if (ref($currcategories) eq 'ARRAY') {
16093: if (@{$currcategories} > 0) {
16094: if (grep(/^\Q$item\E$/,@{$currcategories})) {
16095: $checked = ' checked="checked"';
16096: }
16097: }
16098: }
16099: $text .= '<tr><td><span class="LC_nobreak"><label>'.
16100: '<input type="checkbox" name="usecategory" value="'.
16101: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16102: '<input type="hidden" name="catname" value="'.$name.'" />'.
16103: '</td><td>';
16104: if (ref($path) eq 'ARRAY') {
16105: push(@{$path},$name);
16106: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16107: pop(@{$path});
16108: }
16109: $text .= '</td></tr>';
16110: }
16111: $text .= '</table></td>';
16112: }
16113: }
16114: }
16115: return $text;
16116: }
16117:
16118: =pod
16119:
16120: =back
16121:
16122: =cut
16123:
16124: ############################################################
16125: ############################################################
16126:
16127:
16128: sub commit_customrole {
16129: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
16130: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16131: ($start?', '.&mt('starting').' '.localtime($start):'').
16132: ($end?', ending '.localtime($end):'').': <b>'.
16133: &Apache::lonnet::assigncustomrole(
16134: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
16135: '</b><br />';
16136: return $output;
16137: }
16138:
16139: sub commit_standardrole {
16140: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
16141: my ($output,$logmsg,$linefeed);
16142: if ($context eq 'auto') {
16143: $linefeed = "\n";
16144: } else {
16145: $linefeed = "<br />\n";
16146: }
16147: if ($three eq 'st') {
16148: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16149: $one,$two,$sec,$context,$credits);
16150: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
16151: ($result eq 'unknown_course') || ($result eq 'refused')) {
16152: $output = $logmsg.' '.&mt('Error: ').$result."\n";
16153: } else {
16154: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16155: ($start?', '.&mt('starting').' '.localtime($start):'').
16156: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16157: if ($context eq 'auto') {
16158: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16159: } else {
16160: $output .= '<b>'.$result.'</b>'.$linefeed.
16161: &mt('Add to classlist').': <b>ok</b>';
16162: }
16163: $output .= $linefeed;
16164: }
16165: } else {
16166: $output = &mt('Assigning').' '.$three.' in '.$url.
16167: ($start?', '.&mt('starting').' '.localtime($start):'').
16168: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16169: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16170: if ($context eq 'auto') {
16171: $output .= $result.$linefeed;
16172: } else {
16173: $output .= '<b>'.$result.'</b>'.$linefeed;
16174: }
16175: }
16176: return $output;
16177: }
16178:
16179: sub commit_studentrole {
16180: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16181: $credits) = @_;
16182: my ($result,$linefeed,$oldsecurl,$newsecurl);
16183: if ($context eq 'auto') {
16184: $linefeed = "\n";
16185: } else {
16186: $linefeed = '<br />'."\n";
16187: }
16188: if (defined($one) && defined($two)) {
16189: my $cid=$one.'_'.$two;
16190: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16191: my $secchange = 0;
16192: my $expire_role_result;
16193: my $modify_section_result;
16194: if ($oldsec ne '-1') {
16195: if ($oldsec ne $sec) {
16196: $secchange = 1;
16197: my $now = time;
16198: my $uurl='/'.$cid;
16199: $uurl=~s/\_/\//g;
16200: if ($oldsec) {
16201: $uurl.='/'.$oldsec;
16202: }
16203: $oldsecurl = $uurl;
16204: $expire_role_result =
16205: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
16206: if ($env{'request.course.sec'} ne '') {
16207: if ($expire_role_result eq 'refused') {
16208: my @roles = ('st');
16209: my @statuses = ('previous');
16210: my @roledoms = ($one);
16211: my $withsec = 1;
16212: my %roleshash =
16213: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16214: \@statuses,\@roles,\@roledoms,$withsec);
16215: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16216: my ($oldstart,$oldend) =
16217: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16218: if ($oldend > 0 && $oldend <= $now) {
16219: $expire_role_result = 'ok';
16220: }
16221: }
16222: }
16223: }
16224: $result = $expire_role_result;
16225: }
16226: }
16227: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16228: $modify_section_result =
16229: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16230: undef,undef,undef,$sec,
16231: $end,$start,'','',$cid,
16232: '',$context,$credits);
16233: if ($modify_section_result =~ /^ok/) {
16234: if ($secchange == 1) {
16235: if ($sec eq '') {
16236: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16237: } else {
16238: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16239: }
16240: } elsif ($oldsec eq '-1') {
16241: if ($sec eq '') {
16242: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16243: } else {
16244: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16245: }
16246: } else {
16247: if ($sec eq '') {
16248: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16249: } else {
16250: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16251: }
16252: }
16253: } else {
16254: if ($secchange) {
16255: $$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;
16256: } else {
16257: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16258: }
16259: }
16260: $result = $modify_section_result;
16261: } elsif ($secchange == 1) {
16262: if ($oldsec eq '') {
16263: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16264: } else {
16265: $$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;
16266: }
16267: if ($expire_role_result eq 'refused') {
16268: my $newsecurl = '/'.$cid;
16269: $newsecurl =~ s/\_/\//g;
16270: if ($sec ne '') {
16271: $newsecurl.='/'.$sec;
16272: }
16273: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16274: if ($sec eq '') {
16275: $$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;
16276: } else {
16277: $$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;
16278: }
16279: }
16280: }
16281: }
16282: } else {
16283: $$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;
16284: $result = "error: incomplete course id\n";
16285: }
16286: return $result;
16287: }
16288:
16289: sub show_role_extent {
16290: my ($scope,$context,$role) = @_;
16291: $scope =~ s{^/}{};
16292: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16293: push(@courseroles,'co');
16294: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16295: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16296: $scope =~ s{/}{_};
16297: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16298: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16299: my ($audom,$auname) = split(/\//,$scope);
16300: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16301: &Apache::loncommon::plainname($auname,$audom).'</span>');
16302: } else {
16303: $scope =~ s{/$}{};
16304: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16305: &Apache::lonnet::domain($scope,'description').'</span>');
16306: }
16307: }
16308:
16309: ############################################################
16310: ############################################################
16311:
16312: sub check_clone {
16313: my ($args,$linefeed) = @_;
16314: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16315: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16316: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16317: my $clonetitle;
16318: my @clonemsg;
16319: my $can_clone = 0;
16320: my $lctype = lc($args->{'crstype'});
16321: if ($lctype ne 'community') {
16322: $lctype = 'course';
16323: }
16324: if ($clonehome eq 'no_host') {
16325: if ($args->{'crstype'} eq 'Community') {
16326: push(@clonemsg,({
16327: mt => 'No new community created.',
16328: args => [],
16329: },
16330: {
16331: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16332: args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16333: }));
16334: } else {
16335: push(@clonemsg,({
16336: mt => 'No new course created.',
16337: args => [],
16338: },
16339: {
16340: mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16341: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16342: }));
16343: }
16344: } else {
16345: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16346: $clonetitle = $clonedesc{'description'};
16347: if ($args->{'crstype'} eq 'Community') {
16348: if ($clonedesc{'type'} ne 'Community') {
16349: push(@clonemsg,({
16350: mt => 'No new community created.',
16351: args => [],
16352: },
16353: {
16354: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16355: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16356: }));
16357: return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16358: }
16359: }
16360: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16361: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16362: $can_clone = 1;
16363: } else {
16364: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16365: $args->{'clonedomain'},$args->{'clonecourse'});
16366: if ($clonehash{'cloners'} eq '') {
16367: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16368: if ($domdefs{'canclone'}) {
16369: unless ($domdefs{'canclone'} eq 'none') {
16370: if ($domdefs{'canclone'} eq 'domain') {
16371: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16372: $can_clone = 1;
16373: }
16374: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16375: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16376: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16377: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16378: $can_clone = 1;
16379: }
16380: }
16381: }
16382: }
16383: } else {
16384: my @cloners = split(/,/,$clonehash{'cloners'});
16385: if (grep(/^\*$/,@cloners)) {
16386: $can_clone = 1;
16387: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16388: $can_clone = 1;
16389: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16390: $can_clone = 1;
16391: }
16392: unless ($can_clone) {
16393: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16394: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16395: my (%gotdomdefaults,%gotcodedefaults);
16396: foreach my $cloner (@cloners) {
16397: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16398: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16399: my (%codedefaults,@code_order);
16400: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16401: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16402: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16403: }
16404: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16405: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16406: }
16407: } else {
16408: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16409: \%codedefaults,
16410: \@code_order);
16411: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16412: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16413: }
16414: if (@code_order > 0) {
16415: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16416: $cloner,$clonehash{'internal.coursecode'},
16417: $args->{'crscode'})) {
16418: $can_clone = 1;
16419: last;
16420: }
16421: }
16422: }
16423: }
16424: }
16425: }
16426: }
16427: unless ($can_clone) {
16428: my $ccrole = 'cc';
16429: if ($args->{'crstype'} eq 'Community') {
16430: $ccrole = 'co';
16431: }
16432: my %roleshash =
16433: &Apache::lonnet::get_my_roles($args->{'ccuname'},
16434: $args->{'ccdomain'},
16435: 'userroles',['active'],[$ccrole],
16436: [$args->{'clonedomain'}]);
16437: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16438: $can_clone = 1;
16439: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16440: $args->{'ccuname'},$args->{'ccdomain'})) {
16441: $can_clone = 1;
16442: }
16443: }
16444: unless ($can_clone) {
16445: if ($args->{'crstype'} eq 'Community') {
16446: push(@clonemsg,({
16447: mt => 'No new community created.',
16448: args => [],
16449: },
16450: {
16451: 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]).',
16452: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16453: }));
16454: } else {
16455: push(@clonemsg,({
16456: mt => 'No new course created.',
16457: args => [],
16458: },
16459: {
16460: 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]).',
16461: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16462: }));
16463: }
16464: }
16465: }
16466: }
16467: return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16468: }
16469:
16470: sub construct_course {
16471: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16472: $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16473: my ($outcome,$msgref,$clonemsgref);
16474: my $linefeed = '<br />'."\n";
16475: if ($context eq 'auto') {
16476: $linefeed = "\n";
16477: }
16478:
16479: #
16480: # Are we cloning?
16481: #
16482: my ($can_clone,$cloneid,$clonehome,$clonetitle);
16483: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16484: ($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16485: if (!$can_clone) {
16486: return (0,$outcome,$clonemsgref);
16487: }
16488: }
16489:
16490: #
16491: # Open course
16492: #
16493: my $crstype = lc($args->{'crstype'});
16494: my %cenv=();
16495: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16496: $args->{'cdescr'},
16497: $args->{'curl'},
16498: $args->{'course_home'},
16499: $args->{'nonstandard'},
16500: $args->{'crscode'},
16501: $args->{'ccuname'}.':'.
16502: $args->{'ccdomain'},
16503: $args->{'crstype'},
16504: $cnum,$context,$category,
16505: $callercontext);
16506:
16507: # Note: The testing routines depend on this being output; see
16508: # Utils::Course. This needs to at least be output as a comment
16509: # if anyone ever decides to not show this, and Utils::Course::new
16510: # will need to be suitably modified.
16511: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16512: $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16513: } else {
16514: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16515: }
16516: if ($$courseid =~ /^error:/) {
16517: return (0,$outcome,$clonemsgref);
16518: }
16519:
16520: #
16521: # Check if created correctly
16522: #
16523: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16524: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16525: if ($crsuhome eq 'no_host') {
16526: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16527: $outcome .= &mt_user($user_lh,
16528: 'Course creation failed, unrecognized course home server.');
16529: } else {
16530: $outcome .= &mt('Course creation failed, unrecognized course home server.');
16531: }
16532: $outcome .= $linefeed;
16533: return (0,$outcome,$clonemsgref);
16534: }
16535: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16536:
16537: #
16538: # Do the cloning
16539: #
16540: my @clonemsg;
16541: if ($can_clone && $cloneid) {
16542: push(@clonemsg,
16543: {
16544: mt => 'Created [_1] by cloning from [_2]',
16545: args => [$crstype,$clonetitle],
16546: });
16547: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16548: # Copy all files
16549: my @info =
16550: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16551: $args->{'dateshift'},$args->{'crscode'},
16552: $args->{'ccuname'}.':'.$args->{'ccdomain'},
16553: $args->{'tinyurls'});
16554: if (@info) {
16555: push(@clonemsg,@info);
16556: }
16557: # Restore URL
16558: $cenv{'url'}=$oldcenv{'url'};
16559: # Restore title
16560: $cenv{'description'}=$oldcenv{'description'};
16561: # Restore creation date, creator and creation context.
16562: $cenv{'internal.created'}=$oldcenv{'internal.created'};
16563: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16564: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16565: # Mark as cloned
16566: $cenv{'clonedfrom'}=$cloneid;
16567: # Need to clone grading mode
16568: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16569: $cenv{'grading'}=$newenv{'grading'};
16570: # Do not clone these environment entries
16571: &Apache::lonnet::del('environment',
16572: ['default_enrollment_start_date',
16573: 'default_enrollment_end_date',
16574: 'question.email',
16575: 'policy.email',
16576: 'comment.email',
16577: 'pch.users.denied',
16578: 'plc.users.denied',
16579: 'hidefromcat',
16580: 'checkforpriv',
16581: 'categories'],
16582: $$crsudom,$$crsunum);
16583: if ($args->{'textbook'}) {
16584: $cenv{'internal.textbook'} = $args->{'textbook'};
16585: }
16586: }
16587:
16588: #
16589: # Set environment (will override cloned, if existing)
16590: #
16591: my @sections = ();
16592: my @xlists = ();
16593: if ($args->{'crstype'}) {
16594: $cenv{'type'}=$args->{'crstype'};
16595: }
16596: if ($args->{'lti'}) {
16597: $cenv{'internal.lti'}=$args->{'lti'};
16598: }
16599: if ($args->{'crsid'}) {
16600: $cenv{'courseid'}=$args->{'crsid'};
16601: }
16602: if ($args->{'crscode'}) {
16603: $cenv{'internal.coursecode'}=$args->{'crscode'};
16604: }
16605: if ($args->{'crsquota'} ne '') {
16606: $cenv{'internal.coursequota'}=$args->{'crsquota'};
16607: } else {
16608: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16609: }
16610: if ($args->{'ccuname'}) {
16611: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16612: ':'.$args->{'ccdomain'};
16613: } else {
16614: $cenv{'internal.courseowner'} = $args->{'curruser'};
16615: }
16616: if ($args->{'defaultcredits'}) {
16617: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16618: }
16619: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16620: my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
16621: if ($args->{'crssections'}) {
16622: $cenv{'internal.sectionnums'} = '';
16623: if ($args->{'crssections'} =~ m/,/) {
16624: @sections = split/,/,$args->{'crssections'};
16625: } else {
16626: $sections[0] = $args->{'crssections'};
16627: }
16628: if (@sections > 0) {
16629: foreach my $item (@sections) {
16630: my ($sec,$gp) = split/:/,$item;
16631: my $class = $args->{'crscode'}.$sec;
16632: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16633: $cenv{'internal.sectionnums'} .= $item.',';
16634: if ($addcheck eq 'ok') {
16635: unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
16636: push(@oklcsecs,$gp);
16637: }
16638: } else {
16639: push(@badclasses,$class);
16640: }
16641: }
16642: $cenv{'internal.sectionnums'} =~ s/,$//;
16643: }
16644: }
16645: # do not hide course coordinator from staff listing,
16646: # even if privileged
16647: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16648: # add course coordinator's domain to domains to check for privileged users
16649: # if different to course domain
16650: if ($$crsudom ne $args->{'ccdomain'}) {
16651: $cenv{'checkforpriv'} = $args->{'ccdomain'};
16652: }
16653: # add crosslistings
16654: if ($args->{'crsxlist'}) {
16655: $cenv{'internal.crosslistings'}='';
16656: if ($args->{'crsxlist'} =~ m/,/) {
16657: @xlists = split/,/,$args->{'crsxlist'};
16658: } else {
16659: $xlists[0] = $args->{'crsxlist'};
16660: }
16661: if (@xlists > 0) {
16662: foreach my $item (@xlists) {
16663: my ($xl,$gp) = split/:/,$item;
16664: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16665: $cenv{'internal.crosslistings'} .= $item.',';
16666: if ($addcheck eq 'ok') {
16667: unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
16668: push(@oklcsecs,$gp);
16669: }
16670: } else {
16671: push(@badclasses,$xl);
16672: }
16673: }
16674: $cenv{'internal.crosslistings'} =~ s/,$//;
16675: }
16676: }
16677: if ($args->{'autoadds'}) {
16678: $cenv{'internal.autoadds'}=$args->{'autoadds'};
16679: }
16680: if ($args->{'autodrops'}) {
16681: $cenv{'internal.autodrops'}=$args->{'autodrops'};
16682: }
16683: # check for notification of enrollment changes
16684: my @notified = ();
16685: if ($args->{'notify_owner'}) {
16686: if ($args->{'ccuname'} ne '') {
16687: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16688: }
16689: }
16690: if ($args->{'notify_dc'}) {
16691: if ($uname ne '') {
16692: push(@notified,$uname.':'.$udom);
16693: }
16694: }
16695: if (@notified > 0) {
16696: my $notifylist;
16697: if (@notified > 1) {
16698: $notifylist = join(',',@notified);
16699: } else {
16700: $notifylist = $notified[0];
16701: }
16702: $cenv{'internal.notifylist'} = $notifylist;
16703: }
16704: if (@badclasses > 0) {
16705: my %lt=&Apache::lonlocal::texthash(
16706: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16707: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16708: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16709: );
16710: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16711: &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'};
16712: if ($context eq 'auto') {
16713: $outcome .= $badclass_msg.$linefeed;
16714: } else {
16715: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16716: }
16717: foreach my $item (@badclasses) {
16718: if ($context eq 'auto') {
16719: $outcome .= " - $item\n";
16720: } else {
16721: $outcome .= "<li>$item</li>\n";
16722: }
16723: }
16724: if ($context eq 'auto') {
16725: $outcome .= $linefeed;
16726: } else {
16727: $outcome .= "</ul><br /><br /></div>\n";
16728: }
16729: }
16730: if ($args->{'no_end_date'}) {
16731: $args->{'endaccess'} = 0;
16732: }
16733: # If an official course with institutional sections is created by cloning
16734: # an existing course, section-specific hiding of course totals in student's
16735: # view of grades as copied from cloned course, will be checked for valid
16736: # sections.
16737: if (($can_clone && $cloneid) &&
16738: ($cenv{'internal.coursecode'} ne '') &&
16739: ($cenv{'grading'} eq 'standard') &&
16740: ($cenv{'hidetotals'} ne '') &&
16741: ($cenv{'hidetotals'} ne 'all')) {
16742: my @hidesecs;
16743: my $deletehidetotals;
16744: if (@oklcsecs) {
16745: foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
16746: if (grep(/^\Q$sec$/,@oklcsecs)) {
16747: push(@hidesecs,$sec);
16748: }
16749: }
16750: if (@hidesecs) {
16751: $cenv{'hidetotals'} = join(',',@hidesecs);
16752: } else {
16753: $deletehidetotals = 1;
16754: }
16755: } else {
16756: $deletehidetotals = 1;
16757: }
16758: if ($deletehidetotals) {
16759: delete($cenv{'hidetotals'});
16760: &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
16761: }
16762: }
16763: $cenv{'internal.autostart'}=$args->{'enrollstart'};
16764: $cenv{'internal.autoend'}=$args->{'enrollend'};
16765: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16766: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16767: if ($args->{'showphotos'}) {
16768: $cenv{'internal.showphotos'}=$args->{'showphotos'};
16769: }
16770: $cenv{'internal.authtype'} = $args->{'authtype'};
16771: $cenv{'internal.autharg'} = $args->{'autharg'};
16772: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16773: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
16774: 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');
16775: if ($context eq 'auto') {
16776: $outcome .= $krb_msg;
16777: } else {
16778: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16779: }
16780: $outcome .= $linefeed;
16781: }
16782: }
16783: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16784: if ($args->{'setpolicy'}) {
16785: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16786: }
16787: if ($args->{'setcontent'}) {
16788: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16789: }
16790: if ($args->{'setcomment'}) {
16791: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16792: }
16793: }
16794: if ($args->{'reshome'}) {
16795: $cenv{'reshome'}=$args->{'reshome'}.'/';
16796: $cenv{'reshome'}=~s/\/+$/\//;
16797: }
16798: #
16799: # course has keyed access
16800: #
16801: if ($args->{'setkeys'}) {
16802: $cenv{'keyaccess'}='yes';
16803: }
16804: # if specified, key authority is not course, but user
16805: # only active if keyaccess is yes
16806: if ($args->{'keyauth'}) {
16807: my ($user,$domain) = split(':',$args->{'keyauth'});
16808: $user = &LONCAPA::clean_username($user);
16809: $domain = &LONCAPA::clean_username($domain);
16810: if ($user ne '' && $domain ne '') {
16811: $cenv{'keyauth'}=$user.':'.$domain;
16812: }
16813: }
16814:
16815: #
16816: # generate and store uniquecode (available to course requester), if course should have one.
16817: #
16818: if ($args->{'uniquecode'}) {
16819: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16820: if ($code) {
16821: $cenv{'internal.uniquecode'} = $code;
16822: my %crsinfo =
16823: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16824: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16825: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16826: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16827: }
16828: if (ref($coderef)) {
16829: $$coderef = $code;
16830: }
16831: }
16832: }
16833:
16834: if ($args->{'disresdis'}) {
16835: $cenv{'pch.roles.denied'}='st';
16836: }
16837: if ($args->{'disablechat'}) {
16838: $cenv{'plc.roles.denied'}='st';
16839: }
16840:
16841: # Record we've not yet viewed the Course Initialization Helper for this
16842: # course
16843: $cenv{'course.helper.not.run'} = 1;
16844: #
16845: # Use new Randomseed
16846: #
16847: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16848: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16849: #
16850: # The encryption code and receipt prefix for this course
16851: #
16852: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16853: $cenv{'internal.encpref'}=100+int(9*rand(99));
16854: #
16855: # By default, use standard grading
16856: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16857:
16858: $outcome .= $linefeed.&mt('Setting environment').': '.
16859: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16860: #
16861: # Open all assignments
16862: #
16863: if ($args->{'openall'}) {
16864: my $opendate = time;
16865: if ($args->{'openallfrom'} =~ /^\d+$/) {
16866: $opendate = $args->{'openallfrom'};
16867: }
16868: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16869: my %storecontent = ($storeunder => $opendate,
16870: $storeunder.'.type' => 'date_start');
16871: $outcome .= &mt('All assignments open starting [_1]',
16872: &Apache::lonlocal::locallocaltime($opendate)).': '.
16873: &Apache::lonnet::cput
16874: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16875: }
16876: #
16877: # Set first page
16878: #
16879: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16880: || ($cloneid)) {
16881: $outcome .= &mt('Setting first resource').': ';
16882:
16883: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16884: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16885:
16886: $outcome .= ($fatal?$errtext:'read ok').' - ';
16887: my $title; my $url;
16888: if ($args->{'firstres'} eq 'syl') {
16889: $title=&mt('Syllabus');
16890: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16891: } else {
16892: $title=&mt('Table of Contents');
16893: $url='/adm/navmaps';
16894: }
16895:
16896: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16897: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16898:
16899: if ($errtext) { $fatal=2; }
16900: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16901: }
16902:
16903: return (1,$outcome,\@clonemsg);
16904: }
16905:
16906: sub make_unique_code {
16907: my ($cdom,$cnum) = @_;
16908: # get lock on uniquecodes db
16909: my $lockhash = {
16910: $cnum."\0".'uniquecodes' => $env{'user.name'}.
16911: ':'.$env{'user.domain'},
16912: };
16913: my $tries = 0;
16914: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16915: my ($code,$error);
16916:
16917: while (($gotlock ne 'ok') && ($tries<3)) {
16918: $tries ++;
16919: sleep 1;
16920: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16921: }
16922: if ($gotlock eq 'ok') {
16923: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16924: my $gotcode;
16925: my $attempts = 0;
16926: while ((!$gotcode) && ($attempts < 100)) {
16927: $code = &generate_code();
16928: if (!exists($currcodes{$code})) {
16929: $gotcode = 1;
16930: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16931: $error = 'nostore';
16932: }
16933: }
16934: $attempts ++;
16935: }
16936: my @del_lock = ($cnum."\0".'uniquecodes');
16937: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16938: } else {
16939: $error = 'nolock';
16940: }
16941: return ($code,$error);
16942: }
16943:
16944: sub generate_code {
16945: my $code;
16946: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16947: for (my $i=0; $i<6; $i++) {
16948: my $lettnum = int (rand 2);
16949: my $item = '';
16950: if ($lettnum) {
16951: $item = $letts[int( rand(18) )];
16952: } else {
16953: $item = 1+int( rand(8) );
16954: }
16955: $code .= $item;
16956: }
16957: return $code;
16958: }
16959:
16960: ############################################################
16961: ############################################################
16962:
16963: #SD
16964: # only Community and Course, or anything else?
16965: sub course_type {
16966: my ($cid) = @_;
16967: if (!defined($cid)) {
16968: $cid = $env{'request.course.id'};
16969: }
16970: if (defined($env{'course.'.$cid.'.type'})) {
16971: return $env{'course.'.$cid.'.type'};
16972: } else {
16973: return 'Course';
16974: }
16975: }
16976:
16977: sub group_term {
16978: my $crstype = &course_type();
16979: my %names = (
16980: 'Course' => 'group',
16981: 'Community' => 'group',
16982: );
16983: return $names{$crstype};
16984: }
16985:
16986: sub course_types {
16987: my @types = ('official','unofficial','community','textbook','lti');
16988: my %typename = (
16989: official => 'Official course',
16990: unofficial => 'Unofficial course',
16991: community => 'Community',
16992: textbook => 'Textbook course',
16993: lti => 'LTI provider',
16994: );
16995: return (\@types,\%typename);
16996: }
16997:
16998: sub icon {
16999: my ($file)=@_;
17000: my $curfext = lc((split(/\./,$file))[-1]);
17001: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17002: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17003: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17004: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17005: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17006: $curfext.".gif") {
17007: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17008: $curfext.".gif";
17009: }
17010: }
17011: return &lonhttpdurl($iconname);
17012: }
17013:
17014: sub lonhttpdurl {
17015: #
17016: # Had been used for "small fry" static images on separate port 8080.
17017: # Modify here if lightweight http functionality desired again.
17018: # Currently eliminated due to increasing firewall issues.
17019: #
17020: my ($url)=@_;
17021: return $url;
17022: }
17023:
17024: sub connection_aborted {
17025: my ($r)=@_;
17026: $r->print(" ");$r->rflush();
17027: my $c = $r->connection;
17028: return $c->aborted();
17029: }
17030:
17031: # Escapes strings that may have embedded 's that will be put into
17032: # strings as 'strings'.
17033: sub escape_single {
17034: my ($input) = @_;
17035: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
17036: $input =~ s/\'/\\\'/g; # Esacpe the 's....
17037: return $input;
17038: }
17039:
17040: # Same as escape_single, but escape's "'s This
17041: # can be used for "strings"
17042: sub escape_double {
17043: my ($input) = @_;
17044: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
17045: $input =~ s/\"/\\\"/g; # Esacpe the "s....
17046: return $input;
17047: }
17048:
17049: # Escapes the last element of a full URL.
17050: sub escape_url {
17051: my ($url) = @_;
17052: my @urlslices = split(/\//, $url,-1);
17053: my $lastitem = &escape(pop(@urlslices));
17054: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17055: }
17056:
17057: sub compare_arrays {
17058: my ($arrayref1,$arrayref2) = @_;
17059: my (@difference,%count);
17060: @difference = ();
17061: %count = ();
17062: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17063: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17064: foreach my $element (keys(%count)) {
17065: if ($count{$element} == 1) {
17066: push(@difference,$element);
17067: }
17068: }
17069: }
17070: return @difference;
17071: }
17072:
17073: sub lon_status_items {
17074: my %defaults = (
17075: E => 100,
17076: W => 4,
17077: N => 1,
17078: U => 5,
17079: threshold => 200,
17080: sysmail => 2500,
17081: );
17082: my %names = (
17083: E => 'Errors',
17084: W => 'Warnings',
17085: N => 'Notices',
17086: U => 'Unsent',
17087: );
17088: return (\%defaults,\%names);
17089: }
17090:
17091: # -------------------------------------------------------- Initialize user login
17092: sub init_user_environment {
17093: my ($r, $username, $domain, $authhost, $form, $args) = @_;
17094: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17095:
17096: my $public=($username eq 'public' && $domain eq 'public');
17097:
17098: # See if old ID present, if so, remove
17099:
17100: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17101: my $now=time;
17102:
17103: if ($public) {
17104: my $max_public=100;
17105: my $oldest;
17106: my $oldest_time=0;
17107: for(my $next=1;$next<=$max_public;$next++) {
17108: if (-e $lonids."/publicuser_$next.id") {
17109: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17110: if ($mtime<$oldest_time || !$oldest_time) {
17111: $oldest_time=$mtime;
17112: $oldest=$next;
17113: }
17114: } else {
17115: $cookie="publicuser_$next";
17116: last;
17117: }
17118: }
17119: if (!$cookie) { $cookie="publicuser_$oldest"; }
17120: } else {
17121: # if this isn't a robot, kill any existing non-robot sessions
17122: if (!$args->{'robot'}) {
17123: opendir(DIR,$lonids);
17124: while ($filename=readdir(DIR)) {
17125: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17126: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17127: &GDBM_READER(),0640)) {
17128: my $linkedfile;
17129: if (exists($oldenv{'user.linkedenv'})) {
17130: $linkedfile = $oldenv{'user.linkedenv'};
17131: }
17132: untie(%oldenv);
17133: if (unlink("$lonids/$filename")) {
17134: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17135: if (-l "$lonids/$linkedfile.id") {
17136: unlink("$lonids/$linkedfile.id");
17137: }
17138: }
17139: }
17140: } else {
17141: unlink($lonids.'/'.$filename);
17142: }
17143: }
17144: }
17145: closedir(DIR);
17146: # If there is a undeleted lockfile for the user's paste buffer remove it.
17147: my $namespace = 'nohist_courseeditor';
17148: my $lockingkey = 'paste'."\0".'locked_num';
17149: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17150: $domain,$username);
17151: if (exists($lockhash{$lockingkey})) {
17152: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17153: unless ($delresult eq 'ok') {
17154: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17155: }
17156: }
17157: }
17158: # Give them a new cookie
17159: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17160: : $now.$$.int(rand(10000)));
17161: $cookie="$username\_$id\_$domain\_$authhost";
17162:
17163: # Initialize roles
17164:
17165: ($userroles,$firstaccenv,$timerintenv) =
17166: &Apache::lonnet::rolesinit($domain,$username,$authhost);
17167: }
17168: # ------------------------------------ Check browser type and MathML capability
17169:
17170: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17171: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17172:
17173: # ------------------------------------------------------------- Get environment
17174:
17175: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17176: my ($tmp) = keys(%userenv);
17177: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
17178: } else {
17179: undef(%userenv);
17180: }
17181: if (($userenv{'interface'}) && (!$form->{'interface'})) {
17182: $form->{'interface'}=$userenv{'interface'};
17183: }
17184: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17185:
17186: # --------------- Do not trust query string to be put directly into environment
17187: foreach my $option ('interface','localpath','localres') {
17188: $form->{$option}=~s/[\n\r\=]//gs;
17189: }
17190: # --------------------------------------------------------- Write first profile
17191:
17192: {
17193: my $ip = &Apache::lonnet::get_requestor_ip();
17194: my %initial_env =
17195: ("user.name" => $username,
17196: "user.domain" => $domain,
17197: "user.home" => $authhost,
17198: "browser.type" => $clientbrowser,
17199: "browser.version" => $clientversion,
17200: "browser.mathml" => $clientmathml,
17201: "browser.unicode" => $clientunicode,
17202: "browser.os" => $clientos,
17203: "browser.mobile" => $clientmobile,
17204: "browser.info" => $clientinfo,
17205: "browser.osversion" => $clientosversion,
17206: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
17207: "request.course.fn" => '',
17208: "request.course.uri" => '',
17209: "request.course.sec" => '',
17210: "request.role" => 'cm',
17211: "request.role.adv" => $env{'user.adv'},
17212: "request.host" => $ip,);
17213:
17214: if ($form->{'localpath'}) {
17215: $initial_env{"browser.localpath"} = $form->{'localpath'};
17216: $initial_env{"browser.localres"} = $form->{'localres'};
17217: }
17218:
17219: if ($form->{'interface'}) {
17220: $form->{'interface'}=~s/\W//gs;
17221: $initial_env{"browser.interface"} = $form->{'interface'};
17222: $env{'browser.interface'}=$form->{'interface'};
17223: }
17224:
17225: if ($form->{'iptoken'}) {
17226: my $lonhost = $r->dir_config('lonHostID');
17227: $initial_env{"user.noloadbalance"} = $lonhost;
17228: $env{'user.noloadbalance'} = $lonhost;
17229: }
17230:
17231: if ($form->{'noloadbalance'}) {
17232: my @hosts = &Apache::lonnet::current_machine_ids();
17233: my $hosthere = $form->{'noloadbalance'};
17234: if (grep(/^\Q$hosthere\E$/,@hosts)) {
17235: $initial_env{"user.noloadbalance"} = $hosthere;
17236: $env{'user.noloadbalance'} = $hosthere;
17237: }
17238: }
17239:
17240: unless ($domain eq 'public') {
17241: my %is_adv = ( is_adv => $env{'user.adv'} );
17242: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17243:
17244: foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
17245: $userenv{'availabletools.'.$tool} =
17246: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17247: undef,\%userenv,\%domdef,\%is_adv);
17248: }
17249:
17250: foreach my $crstype ('official','unofficial','community','textbook','lti') {
17251: $userenv{'canrequest.'.$crstype} =
17252: &Apache::lonnet::usertools_access($username,$domain,$crstype,
17253: 'reload','requestcourses',
17254: \%userenv,\%domdef,\%is_adv);
17255: }
17256:
17257: if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
17258: (exists($userroles->{"user.role.au./$domain/"}))) {
17259: if ($userenv{'authoreditors'}) {
17260: $userenv{'editors'} = $userenv{'authoreditors'};
17261: } elsif ($domdef{'editors'} ne '') {
17262: $userenv{'editors'} = $domdef{'editors'};
17263: } else {
17264: $userenv{'editors'} = 'edit,xml';
17265: }
17266: }
17267:
17268: $userenv{'canrequest.author'} =
17269: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17270: 'reload','requestauthor',
17271: \%userenv,\%domdef,\%is_adv);
17272: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17273: $domain,$username);
17274: my $reqstatus = $reqauthor{'author_status'};
17275: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
17276: if (ref($reqauthor{'author'}) eq 'HASH') {
17277: $userenv{'requestauthorqueued'} = $reqstatus.':'.
17278: $reqauthor{'author'}{'timestamp'};
17279: }
17280: }
17281: }
17282:
17283: $env{'user.environment'} = "$lonids/$cookie.id";
17284:
17285: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17286: &GDBM_WRCREAT(),0640)) {
17287: &_add_to_env(\%disk_env,\%initial_env);
17288: &_add_to_env(\%disk_env,\%userenv,'environment.');
17289: &_add_to_env(\%disk_env,$userroles);
17290: if (ref($firstaccenv) eq 'HASH') {
17291: &_add_to_env(\%disk_env,$firstaccenv);
17292: }
17293: if (ref($timerintenv) eq 'HASH') {
17294: &_add_to_env(\%disk_env,$timerintenv);
17295: }
17296: if (ref($args->{'extra_env'})) {
17297: &_add_to_env(\%disk_env,$args->{'extra_env'});
17298: }
17299: untie(%disk_env);
17300: } else {
17301: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17302: 'Could not create environment storage in lonauth: '.$!.'</span>');
17303: return 'error: '.$!;
17304: }
17305: }
17306: $env{'request.role'}='cm';
17307: $env{'request.role.adv'}=$env{'user.adv'};
17308: $env{'browser.type'}=$clientbrowser;
17309:
17310: return $cookie;
17311:
17312: }
17313:
17314: sub _add_to_env {
17315: my ($idf,$env_data,$prefix) = @_;
17316: if (ref($env_data) eq 'HASH') {
17317: while (my ($key,$value) = each(%$env_data)) {
17318: $idf->{$prefix.$key} = $value;
17319: $env{$prefix.$key} = $value;
17320: }
17321: }
17322: }
17323:
17324: # --- Get the symbolic name of a problem and the url
17325: sub get_symb {
17326: my ($request,$silent) = @_;
17327: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17328: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17329: if ($symb eq '') {
17330: if (!$silent) {
17331: if (ref($request)) {
17332: $request->print("Unable to handle ambiguous references:$url:.");
17333: }
17334: return ();
17335: }
17336: }
17337: &Apache::lonenc::check_decrypt(\$symb);
17338: return ($symb);
17339: }
17340:
17341: # --------------------------------------------------------------Get annotation
17342:
17343: sub get_annotation {
17344: my ($symb,$enc) = @_;
17345:
17346: my $key = $symb;
17347: if (!$enc) {
17348: $key =
17349: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17350: }
17351: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17352: return $annotation{$key};
17353: }
17354:
17355: sub clean_symb {
17356: my ($symb,$delete_enc) = @_;
17357:
17358: &Apache::lonenc::check_decrypt(\$symb);
17359: my $enc = $env{'request.enc'};
17360: if ($delete_enc) {
17361: delete($env{'request.enc'});
17362: }
17363:
17364: return ($symb,$enc);
17365: }
17366:
17367: ############################################################
17368: ############################################################
17369:
17370: =pod
17371:
17372: =head1 Routines for building display used to search for courses
17373:
17374:
17375: =over 4
17376:
17377: =item * &build_filters()
17378:
17379: Create markup for a table used to set filters to use when selecting
17380: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
17381: and quotacheck.pl
17382:
17383:
17384: Inputs:
17385:
17386: filterlist - anonymous array of fields to include as potential filters
17387:
17388: crstype - course type
17389:
17390: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17391: to pop-open a course selector (will contain "extra element").
17392:
17393: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17394:
17395: filter - anonymous hash of criteria and their values
17396:
17397: action - form action
17398:
17399: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17400:
17401: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17402:
17403: cloneruname - username of owner of new course who wants to clone
17404:
17405: clonerudom - domain of owner of new course who wants to clone
17406:
17407: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
17408:
17409: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17410:
17411: codedom - domain
17412:
17413: formname - value of form element named "form".
17414:
17415: fixeddom - domain, if fixed.
17416:
17417: prevphase - value to assign to form element named "phase" when going back to the previous screen
17418:
17419: cnameelement - name of form element in form on opener page which will receive title of selected course
17420:
17421: cnumelement - name of form element in form on opener page which will receive courseID of selected course
17422:
17423: cdomelement - name of form element in form on opener page which will receive domain of selected course
17424:
17425: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17426:
17427: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17428:
17429: clonewarning - warning message about missing information for intended course owner when DC creates a course
17430:
17431:
17432: Returns: $output - HTML for display of search criteria, and hidden form elements.
17433:
17434:
17435: Side Effects: None
17436:
17437: =cut
17438:
17439: # ---------------------------------------------- search for courses based on last activity etc.
17440:
17441: sub build_filters {
17442: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17443: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17444: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17445: $cnameelement,$cnumelement,$cdomelement,$setroles,
17446: $clonetext,$clonewarning) = @_;
17447: my ($list,$jscript);
17448: my $onchange = 'javascript:updateFilters(this)';
17449: my ($domainselectform,$sincefilterform,$createdfilterform,
17450: $ownerdomselectform,$persondomselectform,$instcodeform,
17451: $typeselectform,$instcodetitle);
17452: if ($formname eq '') {
17453: $formname = $caller;
17454: }
17455: foreach my $item (@{$filterlist}) {
17456: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17457: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17458: if ($item eq 'domainfilter') {
17459: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17460: } elsif ($item eq 'coursefilter') {
17461: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17462: } elsif ($item eq 'ownerfilter') {
17463: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17464: } elsif ($item eq 'ownerdomfilter') {
17465: $filter->{'ownerdomfilter'} =
17466: &LONCAPA::clean_domain($filter->{$item});
17467: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17468: 'ownerdomfilter',1);
17469: } elsif ($item eq 'personfilter') {
17470: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17471: } elsif ($item eq 'persondomfilter') {
17472: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17473: 'persondomfilter',1);
17474: } else {
17475: $filter->{$item} =~ s/\W//g;
17476: }
17477: if (!$filter->{$item}) {
17478: $filter->{$item} = '';
17479: }
17480: }
17481: if ($item eq 'domainfilter') {
17482: my $allow_blank = 1;
17483: if ($formname eq 'portform') {
17484: $allow_blank=0;
17485: } elsif ($formname eq 'studentform') {
17486: $allow_blank=0;
17487: }
17488: if ($fixeddom) {
17489: $domainselectform = '<input type="hidden" name="domainfilter"'.
17490: ' value="'.$codedom.'" />'.
17491: &Apache::lonnet::domain($codedom,'description');
17492: } else {
17493: $domainselectform = &select_dom_form($filter->{$item},
17494: 'domainfilter',
17495: $allow_blank,'',$onchange);
17496: }
17497: } else {
17498: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17499: }
17500: }
17501:
17502: # last course activity filter and selection
17503: $sincefilterform = &timebased_select_form('sincefilter',$filter);
17504:
17505: # course created filter and selection
17506: if (exists($filter->{'createdfilter'})) {
17507: $createdfilterform = &timebased_select_form('createdfilter',$filter);
17508: }
17509:
17510: my %lt = &Apache::lonlocal::texthash(
17511: 'cac' => "$crstype Activity",
17512: 'ccr' => "$crstype Created",
17513: 'cde' => "$crstype Title",
17514: 'cdo' => "$crstype Domain",
17515: 'ins' => 'Institutional Code',
17516: 'inc' => 'Institutional Categorization',
17517: 'cow' => "$crstype Owner/Co-owner",
17518: 'cop' => "$crstype Personnel Includes",
17519: 'cog' => 'Type',
17520: );
17521:
17522: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17523: my $typeval = 'Course';
17524: if ($crstype eq 'Community') {
17525: $typeval = 'Community';
17526: }
17527: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17528: } else {
17529: $typeselectform = '<select name="type" size="1"';
17530: if ($onchange) {
17531: $typeselectform .= ' onchange="'.$onchange.'"';
17532: }
17533: $typeselectform .= '>'."\n";
17534: foreach my $posstype ('Course','Community') {
17535: $typeselectform.='<option value="'.$posstype.'"'.
17536: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
17537: }
17538: $typeselectform.="</select>";
17539: }
17540:
17541: my ($cloneableonlyform,$cloneabletitle);
17542: if (exists($filter->{'cloneableonly'})) {
17543: my $cloneableon = '';
17544: my $cloneableoff = ' checked="checked"';
17545: if ($filter->{'cloneableonly'}) {
17546: $cloneableon = $cloneableoff;
17547: $cloneableoff = '';
17548: }
17549: $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>';
17550: if ($formname eq 'ccrs') {
17551: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17552: } else {
17553: $cloneabletitle = &mt('Cloneable by you');
17554: }
17555: }
17556: my $officialjs;
17557: if ($crstype eq 'Course') {
17558: if (exists($filter->{'instcodefilter'})) {
17559: # if (($fixeddom) || ($formname eq 'requestcrs') ||
17560: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17561: if ($codedom) {
17562: $officialjs = 1;
17563: ($instcodeform,$jscript,$$numtitlesref) =
17564: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17565: $officialjs,$codetitlesref);
17566: if ($jscript) {
17567: $jscript = '<script type="text/javascript">'."\n".
17568: '// <![CDATA['."\n".
17569: $jscript."\n".
17570: '// ]]>'."\n".
17571: '</script>'."\n";
17572: }
17573: }
17574: if ($instcodeform eq '') {
17575: $instcodeform =
17576: '<input type="text" name="instcodefilter" size="10" value="'.
17577: $list->{'instcodefilter'}.'" />';
17578: $instcodetitle = $lt{'ins'};
17579: } else {
17580: $instcodetitle = $lt{'inc'};
17581: }
17582: if ($fixeddom) {
17583: $instcodetitle .= '<br />('.$codedom.')';
17584: }
17585: }
17586: }
17587: my $output = qq|
17588: <form method="post" name="filterpicker" action="$action">
17589: <input type="hidden" name="form" value="$formname" />
17590: |;
17591: if ($formname eq 'modifycourse') {
17592: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17593: '<input type="hidden" name="prevphase" value="'.
17594: $prevphase.'" />'."\n";
17595: } elsif ($formname eq 'quotacheck') {
17596: $output .= qq|
17597: <input type="hidden" name="sortby" value="" />
17598: <input type="hidden" name="sortorder" value="" />
17599: |;
17600: } else {
17601: my $name_input;
17602: if ($cnameelement ne '') {
17603: $name_input = '<input type="hidden" name="cnameelement" value="'.
17604: $cnameelement.'" />';
17605: }
17606: $output .= qq|
17607: <input type="hidden" name="cnumelement" value="$cnumelement" />
17608: <input type="hidden" name="cdomelement" value="$cdomelement" />
17609: $name_input
17610: $roleelement
17611: $multelement
17612: $typeelement
17613: |;
17614: if ($formname eq 'portform') {
17615: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17616: }
17617: }
17618: if ($fixeddom) {
17619: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17620: }
17621: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17622: if ($sincefilterform) {
17623: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17624: .$sincefilterform
17625: .&Apache::lonhtmlcommon::row_closure();
17626: }
17627: if ($createdfilterform) {
17628: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17629: .$createdfilterform
17630: .&Apache::lonhtmlcommon::row_closure();
17631: }
17632: if ($domainselectform) {
17633: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17634: .$domainselectform
17635: .&Apache::lonhtmlcommon::row_closure();
17636: }
17637: if ($typeselectform) {
17638: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17639: $output .= $typeselectform;
17640: } else {
17641: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17642: .$typeselectform
17643: .&Apache::lonhtmlcommon::row_closure();
17644: }
17645: }
17646: if ($instcodeform) {
17647: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17648: .$instcodeform
17649: .&Apache::lonhtmlcommon::row_closure();
17650: }
17651: if (exists($filter->{'ownerfilter'})) {
17652: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17653: '<table><tr><td>'.&mt('Username').'<br />'.
17654: '<input type="text" name="ownerfilter" size="20" value="'.
17655: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17656: $ownerdomselectform.'</td></tr></table>'.
17657: &Apache::lonhtmlcommon::row_closure();
17658: }
17659: if (exists($filter->{'personfilter'})) {
17660: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17661: '<table><tr><td>'.&mt('Username').'<br />'.
17662: '<input type="text" name="personfilter" size="20" value="'.
17663: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17664: $persondomselectform.'</td></tr></table>'.
17665: &Apache::lonhtmlcommon::row_closure();
17666: }
17667: if (exists($filter->{'coursefilter'})) {
17668: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17669: .'<input type="text" name="coursefilter" size="25" value="'
17670: .$list->{'coursefilter'}.'" />'
17671: .&Apache::lonhtmlcommon::row_closure();
17672: }
17673: if ($cloneableonlyform) {
17674: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17675: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17676: }
17677: if (exists($filter->{'descriptfilter'})) {
17678: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17679: .'<input type="text" name="descriptfilter" size="40" value="'
17680: .$list->{'descriptfilter'}.'" />'
17681: .&Apache::lonhtmlcommon::row_closure(1);
17682: }
17683: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17684: '<input type="hidden" name="updater" value="" />'."\n".
17685: '<input type="submit" name="gosearch" value="'.
17686: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17687: return $jscript.$clonewarning.$output;
17688: }
17689:
17690: =pod
17691:
17692: =item * &timebased_select_form()
17693:
17694: Create markup for a dropdown list used to select a time-based
17695: filter e.g., Course Activity, Course Created, when searching for courses
17696: or communities
17697:
17698: Inputs:
17699:
17700: item - name of form element (sincefilter or createdfilter)
17701:
17702: filter - anonymous hash of criteria and their values
17703:
17704: Returns: HTML for a select box contained a blank, then six time selections,
17705: with value set in incoming form variables currently selected.
17706:
17707: Side Effects: None
17708:
17709: =cut
17710:
17711: sub timebased_select_form {
17712: my ($item,$filter) = @_;
17713: if (ref($filter) eq 'HASH') {
17714: $filter->{$item} =~ s/[^\d-]//g;
17715: if (!$filter->{$item}) { $filter->{$item}=-1; }
17716: return &select_form(
17717: $filter->{$item},
17718: $item,
17719: { '-1' => '',
17720: '86400' => &mt('today'),
17721: '604800' => &mt('last week'),
17722: '2592000' => &mt('last month'),
17723: '7776000' => &mt('last three months'),
17724: '15552000' => &mt('last six months'),
17725: '31104000' => &mt('last year'),
17726: 'select_form_order' =>
17727: ['-1','86400','604800','2592000','7776000',
17728: '15552000','31104000']});
17729: }
17730: }
17731:
17732: =pod
17733:
17734: =item * &js_changer()
17735:
17736: Create script tag containing Javascript used to submit course search form
17737: when course type or domain is changed, and also to hide 'Searching ...' on
17738: page load completion for page showing search result.
17739:
17740: Inputs: None
17741:
17742: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17743:
17744: Side Effects: None
17745:
17746: =cut
17747:
17748: sub js_changer {
17749: return <<ENDJS;
17750: <script type="text/javascript">
17751: // <![CDATA[
17752: function updateFilters(caller) {
17753: if (typeof(caller) != "undefined") {
17754: document.filterpicker.updater.value = caller.name;
17755: }
17756: document.filterpicker.submit();
17757: }
17758:
17759: function hideSearching() {
17760: if (document.getElementById('searching')) {
17761: document.getElementById('searching').style.display = 'none';
17762: }
17763: return;
17764: }
17765:
17766: // ]]>
17767: </script>
17768:
17769: ENDJS
17770: }
17771:
17772: =pod
17773:
17774: =item * &search_courses()
17775:
17776: Process selected filters form course search form and pass to lonnet::courseiddump
17777: to retrieve a hash for which keys are courseIDs which match the selected filters.
17778:
17779: Inputs:
17780:
17781: dom - domain being searched
17782:
17783: type - course type ('Course' or 'Community' or '.' if any).
17784:
17785: filter - anonymous hash of criteria and their values
17786:
17787: numtitles - for institutional codes - number of categories
17788:
17789: cloneruname - optional username of new course owner
17790:
17791: clonerudom - optional domain of new course owner
17792:
17793: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17794: (used when DC is using course creation form)
17795:
17796: codetitles - reference to array of titles of components in institutional codes (official courses).
17797:
17798: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17799: (and so can clone automatically)
17800:
17801: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17802:
17803: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17804: courses to clone
17805:
17806: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17807:
17808:
17809: Side Effects: None
17810:
17811: =cut
17812:
17813:
17814: sub search_courses {
17815: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17816: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17817: my (%courses,%showcourses,$cloner);
17818: if (($filter->{'ownerfilter'} ne '') ||
17819: ($filter->{'ownerdomfilter'} ne '')) {
17820: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17821: $filter->{'ownerdomfilter'};
17822: }
17823: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17824: if (!$filter->{$item}) {
17825: $filter->{$item}='.';
17826: }
17827: }
17828: my $now = time;
17829: my $timefilter =
17830: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17831: my ($createdbefore,$createdafter);
17832: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17833: $createdbefore = $now;
17834: $createdafter = $now-$filter->{'createdfilter'};
17835: }
17836: my ($instcodefilter,$regexpok);
17837: if ($numtitles) {
17838: if ($env{'form.official'} eq 'on') {
17839: $instcodefilter =
17840: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17841: $regexpok = 1;
17842: } elsif ($env{'form.official'} eq 'off') {
17843: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17844: unless ($instcodefilter eq '') {
17845: $regexpok = -1;
17846: }
17847: }
17848: } else {
17849: $instcodefilter = $filter->{'instcodefilter'};
17850: }
17851: if ($instcodefilter eq '') { $instcodefilter = '.'; }
17852: if ($type eq '') { $type = '.'; }
17853:
17854: if (($clonerudom ne '') && ($cloneruname ne '')) {
17855: $cloner = $cloneruname.':'.$clonerudom;
17856: }
17857: %courses = &Apache::lonnet::courseiddump($dom,
17858: $filter->{'descriptfilter'},
17859: $timefilter,
17860: $instcodefilter,
17861: $filter->{'combownerfilter'},
17862: $filter->{'coursefilter'},
17863: undef,undef,$type,$regexpok,undef,undef,
17864: undef,undef,$cloner,$cc_clone,
17865: $filter->{'cloneableonly'},
17866: $createdbefore,$createdafter,undef,
17867: $domcloner,undef,$reqcrsdom,$reqinstcode);
17868: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17869: my $ccrole;
17870: if ($type eq 'Community') {
17871: $ccrole = 'co';
17872: } else {
17873: $ccrole = 'cc';
17874: }
17875: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17876: $filter->{'persondomfilter'},
17877: 'userroles',undef,
17878: [$ccrole,'in','ad','ep','ta','cr'],
17879: $dom);
17880: foreach my $role (keys(%rolehash)) {
17881: my ($cnum,$cdom,$courserole) = split(':',$role);
17882: my $cid = $cdom.'_'.$cnum;
17883: if (exists($courses{$cid})) {
17884: if (ref($courses{$cid}) eq 'HASH') {
17885: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17886: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17887: push(@{$courses{$cid}{roles}},$courserole);
17888: }
17889: } else {
17890: $courses{$cid}{roles} = [$courserole];
17891: }
17892: $showcourses{$cid} = $courses{$cid};
17893: }
17894: }
17895: }
17896: %courses = %showcourses;
17897: }
17898: return %courses;
17899: }
17900:
17901: =pod
17902:
17903: =back
17904:
17905: =head1 Routines for version requirements for current course.
17906:
17907: =over 4
17908:
17909: =item * &check_release_required()
17910:
17911: Compares required LON-CAPA version with version on server, and
17912: if required version is newer looks for a server with the required version.
17913:
17914: Looks first at servers in user's owen domain; if none suitable, looks at
17915: servers in course's domain are permitted to host sessions for user's domain.
17916:
17917: Inputs:
17918:
17919: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17920:
17921: $courseid - Course ID of current course
17922:
17923: $rolecode - User's current role in course (for switchserver query string).
17924:
17925: $required - LON-CAPA version needed by course (format: Major.Minor).
17926:
17927:
17928: Returns:
17929:
17930: $switchserver - query string tp append to /adm/switchserver call (if
17931: current server's LON-CAPA version is too old.
17932:
17933: $warning - Message is displayed if no suitable server could be found.
17934:
17935: =cut
17936:
17937: sub check_release_required {
17938: my ($loncaparev,$courseid,$rolecode,$required) = @_;
17939: my ($switchserver,$warning);
17940: if ($required ne '') {
17941: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17942: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17943: if ($reqdmajor ne '' && $reqdminor ne '') {
17944: my $otherserver;
17945: if (($major eq '' && $minor eq '') ||
17946: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17947: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17948: my $switchlcrev =
17949: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17950: $userdomserver);
17951: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17952: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17953: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17954: my $cdom = $env{'course.'.$courseid.'.domain'};
17955: if ($cdom ne $env{'user.domain'}) {
17956: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17957: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17958: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17959: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17960: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17961: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17962: my $canhost =
17963: &Apache::lonnet::can_host_session($env{'user.domain'},
17964: $coursedomserver,
17965: $remoterev,
17966: $udomdefaults{'remotesessions'},
17967: $defdomdefaults{'hostedsessions'});
17968:
17969: if ($canhost) {
17970: $otherserver = $coursedomserver;
17971: } else {
17972: $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.");
17973: }
17974: } else {
17975: $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).");
17976: }
17977: } else {
17978: $otherserver = $userdomserver;
17979: }
17980: }
17981: if ($otherserver ne '') {
17982: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
17983: }
17984: }
17985: }
17986: return ($switchserver,$warning);
17987: }
17988:
17989: =pod
17990:
17991: =item * &check_release_result()
17992:
17993: Inputs:
17994:
17995: $switchwarning - Warning message if no suitable server found to host session.
17996:
17997: $switchserver - query string to append to /adm/switchserver containing lonHostID
17998: and current role.
17999:
18000: Returns: HTML to display with information about requirement to switch server.
18001: Either displaying warning with link to Roles/Courses screen or
18002: display link to switchserver.
18003:
18004: =cut
18005:
18006: sub check_release_result {
18007: my ($switchwarning,$switchserver) = @_;
18008: my $output = &start_page('Selected course unavailable on this server').
18009: '<p class="LC_warning">';
18010: if ($switchwarning) {
18011: $output .= $switchwarning.'<br /><a href="/adm/roles">';
18012: if (&show_course()) {
18013: $output .= &mt('Display courses');
18014: } else {
18015: $output .= &mt('Display roles');
18016: }
18017: $output .= '</a>';
18018: } elsif ($switchserver) {
18019: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18020: '<br />'.
18021: '<a href="/adm/switchserver?'.$switchserver.'">'.
18022: &mt('Switch Server').
18023: '</a>';
18024: }
18025: $output .= '</p>'.&end_page();
18026: return $output;
18027: }
18028:
18029: =pod
18030:
18031: =item * &needs_coursereinit()
18032:
18033: Determine if course contents stored for user's session needs to be
18034: refreshed, because content has changed since "Big Hash" last tied.
18035:
18036: Check for change is made if time last checked is more than 10 minutes ago
18037: (by default).
18038:
18039: Inputs:
18040:
18041: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18042:
18043: $interval (optional) - Time which may elapse (in s) between last check for content
18044: change in current course. (default: 600 s).
18045:
18046: Returns: an array; first element is:
18047:
18048: =over 4
18049:
18050: 'switch' - if content updates mean user's session
18051: needs to be switched to a server running a newer LON-CAPA version
18052:
18053: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18054: on current server hosting user's session
18055:
18056: '' - if no action required.
18057:
18058: =back
18059:
18060: If first item element is 'switch':
18061:
18062: second item is $switchwarning - Warning message if no suitable server found to host session.
18063:
18064: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18065: and current role.
18066:
18067: otherwise: no other elements returned.
18068:
18069: =back
18070:
18071: =cut
18072:
18073: sub needs_coursereinit {
18074: my ($loncaparev,$interval) = @_;
18075: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18076: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18077: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18078: my $now = time;
18079: if ($interval eq '') {
18080: $interval = 600;
18081: }
18082: if (($now-$env{'request.course.timechecked'})>$interval) {
18083: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18084: my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18085: if ($blocked) {
18086: return ();
18087: }
18088: my $update;
18089: my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18090: my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18091: if ($lastmainchange > $env{'request.course.tied'}) {
18092: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18093: if ($needswitch) {
18094: return ('switch',$switchwarning,$switchserver);
18095: }
18096: $update = 'main';
18097: }
18098: if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18099: if ($update) {
18100: $update = 'both';
18101: } else {
18102: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18103: if ($needswitch) {
18104: return ('switch',$switchwarning,$switchserver);
18105: } else {
18106: $update = 'supp';
18107: }
18108: }
18109: return ($update);
18110: }
18111: }
18112: return ();
18113: }
18114:
18115: sub switch_for_update {
18116: my ($loncaparev,$cdom,$cnum) = @_;
18117: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18118: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18119: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18120: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18121: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18122: $curr_reqd_hash{'internal.releaserequired'}});
18123: my ($switchserver,$switchwarning) =
18124: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18125: $curr_reqd_hash{'internal.releaserequired'});
18126: if ($switchwarning ne '' || $switchserver ne '') {
18127: return ('switch',$switchwarning,$switchserver);
18128: }
18129: }
18130: }
18131: return ();
18132: }
18133:
18134: sub update_content_constraints {
18135: my ($cdom,$cnum,$chome,$cid) = @_;
18136: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18137: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18138: my %checkresponsetypes;
18139: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18140: my ($item,$name,$value) = split(/:/,$key);
18141: if ($item eq 'resourcetag') {
18142: if ($name eq 'responsetype') {
18143: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18144: }
18145: }
18146: }
18147: my $navmap = Apache::lonnavmaps::navmap->new();
18148: if (defined($navmap)) {
18149: my %allresponses;
18150: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
18151: my %responses = $res->responseTypes();
18152: foreach my $key (keys(%responses)) {
18153: next unless(exists($checkresponsetypes{$key}));
18154: $allresponses{$key} += $responses{$key};
18155: }
18156: }
18157: foreach my $key (keys(%allresponses)) {
18158: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18159: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18160: ($reqdmajor,$reqdminor) = ($major,$minor);
18161: }
18162: }
18163: undef($navmap);
18164: }
18165: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18166: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18167: }
18168: return;
18169: }
18170:
18171: sub allmaps_incourse {
18172: my ($cdom,$cnum,$chome,$cid) = @_;
18173: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18174: $cid = $env{'request.course.id'};
18175: $cdom = $env{'course.'.$cid.'.domain'};
18176: $cnum = $env{'course.'.$cid.'.num'};
18177: $chome = $env{'course.'.$cid.'.home'};
18178: }
18179: my %allmaps = ();
18180: my $lastchange =
18181: &Apache::lonnet::get_coursechange($cdom,$cnum);
18182: if ($lastchange > $env{'request.course.tied'}) {
18183: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18184: unless ($ferr) {
18185: &update_content_constraints($cdom,$cnum,$chome,$cid);
18186: }
18187: }
18188: my $navmap = Apache::lonnavmaps::navmap->new();
18189: if (defined($navmap)) {
18190: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18191: $allmaps{$res->src()} = 1;
18192: }
18193: }
18194: return \%allmaps;
18195: }
18196:
18197: sub parse_supplemental_title {
18198: my ($title) = @_;
18199:
18200: my ($foldertitle,$renametitle);
18201: if ($title =~ /&&&/) {
18202: $title = &HTML::Entites::decode($title);
18203: }
18204: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18205: $renametitle=$4;
18206: my ($time,$uname,$udom) = ($1,$2,$3);
18207: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18208: my $name = &plainname($uname,$udom);
18209: $name = &HTML::Entities::encode($name,'"<>&\'');
18210: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18211: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18212: if ($foldertitle ne '') {
18213: $title .= ': <br />'.$foldertitle;
18214: }
18215: }
18216: if (wantarray) {
18217: return ($title,$foldertitle,$renametitle);
18218: }
18219: return $title;
18220: }
18221:
18222: sub get_supplemental {
18223: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18224: my $hashid=$cnum.':'.$cdom;
18225: my ($supplemental,$cached,$set_httprefs);
18226: unless ($ignorecache) {
18227: ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18228: }
18229: unless (defined($cached)) {
18230: my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18231: unless ($chome eq 'no_host') {
18232: my @order = @LONCAPA::map::order;
18233: my @resources = @LONCAPA::map::resources;
18234: my @resparms = @LONCAPA::map::resparms;
18235: my @zombies = @LONCAPA::map::zombies;
18236: my ($errors,%ids,%hidden);
18237: $errors =
18238: &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18239: $errors,$possdel,\%ids,\%hidden);
18240: @LONCAPA::map::order = @order;
18241: @LONCAPA::map::resources = @resources;
18242: @LONCAPA::map::resparms = @resparms;
18243: @LONCAPA::map::zombies = @zombies;
18244: $set_httprefs = 1;
18245: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18246: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18247: }
18248: $supplemental = {
18249: ids => \%ids,
18250: hidden => \%hidden,
18251: };
18252: &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18253: }
18254: }
18255: return ($supplemental,$set_httprefs);
18256: }
18257:
18258: sub recurse_supplemental {
18259: my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18260: if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18261: my $mapnum;
18262: if ($suppmap eq 'supplemental.sequence') {
18263: $mapnum = 0;
18264: } else {
18265: ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18266: }
18267: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18268: if ($fatal) {
18269: $errors ++;
18270: } else {
18271: my @order = @LONCAPA::map::order;
18272: if (@order > 0) {
18273: my @resources = @LONCAPA::map::resources;
18274: my @resparms = @LONCAPA::map::resparms;
18275: foreach my $idx (@order) {
18276: my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18277: if (($src ne '') && ($status eq 'res')) {
18278: my $id = $mapnum.':'.$idx;
18279: push(@{$suppids->{$src}},$id);
18280: if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18281: $hiddensupp->{$id} = 1;
18282: }
18283: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18284: $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18285: $hiddensupp,$hiddensupp->{$id});
18286: } else {
18287: my $allowed;
18288: if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18289: $allowed = 1;
18290: } elsif ($possdel) {
18291: foreach my $item (@{$suppids->{$src}}) {
18292: next if ($item eq $id);
18293: unless ($hiddensupp->{$item}) {
18294: $allowed = 1;
18295: last;
18296: }
18297: }
18298: if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18299: &Apache::lonnet::delenv('httpref.'.$src);
18300: }
18301: }
18302: if ($allowed && (!exists($env{'httpref.'.$src}))) {
18303: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18304: }
18305: }
18306: }
18307: }
18308: }
18309: }
18310: }
18311: return $errors;
18312: }
18313:
18314: sub set_supp_httprefs {
18315: my ($cnum,$cdom,$supplemental,$possdel) = @_;
18316: if (ref($supplemental) eq 'HASH') {
18317: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18318: foreach my $src (keys(%{$supplemental->{'ids'}})) {
18319: next if ($src =~ /\.sequence$/);
18320: if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18321: my $allowed;
18322: if ($env{'request.role.adv'}) {
18323: $allowed = 1;
18324: } else {
18325: foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18326: unless ($supplemental->{'hidden'}->{$id}) {
18327: $allowed = 1;
18328: last;
18329: }
18330: }
18331: }
18332: if (exists($env{'httpref.'.$src})) {
18333: if ($possdel) {
18334: unless ($allowed) {
18335: &Apache::lonnet::delenv('httpref.'.$src);
18336: }
18337: }
18338: } elsif ($allowed) {
18339: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18340: }
18341: }
18342: }
18343: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18344: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18345: }
18346: }
18347: }
18348: }
18349:
18350: sub get_supp_parameter {
18351: my ($resparm,$name)=@_;
18352: return if ($resparm eq '');
18353: my $value=undef;
18354: my $ptype=undef;
18355: foreach (split('&&&',$resparm)) {
18356: my ($thistype,$thisname,$thisvalue)=split('___',$_);
18357: if ($thisname eq $name) {
18358: $value=$thisvalue;
18359: $ptype=$thistype;
18360: }
18361: }
18362: return $value;
18363: }
18364:
18365: sub symb_to_docspath {
18366: my ($symb,$navmapref) = @_;
18367: return unless ($symb && ref($navmapref));
18368: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18369: if ($resurl=~/\.(sequence|page)$/) {
18370: $mapurl=$resurl;
18371: } elsif ($resurl eq 'adm/navmaps') {
18372: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18373: }
18374: my $mapresobj;
18375: unless (ref($$navmapref)) {
18376: $$navmapref = Apache::lonnavmaps::navmap->new();
18377: }
18378: if (ref($$navmapref)) {
18379: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18380: }
18381: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18382: my $type=$2;
18383: my $path;
18384: if (ref($mapresobj)) {
18385: my $pcslist = $mapresobj->map_hierarchy();
18386: if ($pcslist ne '') {
18387: foreach my $pc (split(/,/,$pcslist)) {
18388: next if ($pc <= 1);
18389: my $res = $$navmapref->getByMapPc($pc);
18390: if (ref($res)) {
18391: my $thisurl = $res->src();
18392: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18393: my $thistitle = $res->title();
18394: $path .= '&'.
18395: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18396: &escape($thistitle).
18397: ':'.$res->randompick().
18398: ':'.$res->randomout().
18399: ':'.$res->encrypted().
18400: ':'.$res->randomorder().
18401: ':'.$res->is_page();
18402: }
18403: }
18404: }
18405: $path =~ s/^\&//;
18406: my $maptitle = $mapresobj->title();
18407: if ($mapurl eq 'default') {
18408: $maptitle = 'Main Content';
18409: }
18410: $path .= (($path ne '')? '&' : '').
18411: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18412: &escape($maptitle).
18413: ':'.$mapresobj->randompick().
18414: ':'.$mapresobj->randomout().
18415: ':'.$mapresobj->encrypted().
18416: ':'.$mapresobj->randomorder().
18417: ':'.$mapresobj->is_page();
18418: } else {
18419: my $maptitle = &Apache::lonnet::gettitle($mapurl);
18420: my $ispage = (($type eq 'page')? 1 : '');
18421: if ($mapurl eq 'default') {
18422: $maptitle = 'Main Content';
18423: }
18424: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18425: &escape($maptitle).':::::'.$ispage;
18426: }
18427: unless ($mapurl eq 'default') {
18428: $path = 'default&'.
18429: &escape('Main Content').
18430: ':::::&'.$path;
18431: }
18432: return $path;
18433: }
18434:
18435: sub validate_folderpath {
18436: my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18437: if ($env{'form.folderpath'} ne '') {
18438: my @items = split(/\&/,$env{'form.folderpath'});
18439: my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18440: for (my $i=0; $i<@items; $i++) {
18441: my $odd = $i%2;
18442: if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18443: $badpath = 1;
18444: } elsif ($odd && $supplementalflag) {
18445: my $idx = $i-1;
18446: if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18447: my $esc_name = $1;
18448: if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18449: $supppath .= '&'.$esc_name;
18450: $changed = 1;
18451: } else {
18452: $supppath .= '&'.$items[$i];
18453: }
18454: } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18455: $changed = 1;
18456: my $is_hidden;
18457: unless ($got_supp) {
18458: my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18459: if (ref($supplemental) eq 'HASH') {
18460: if (ref($supplemental->{'hidden'}) eq 'HASH') {
18461: %supphidden = %{$supplemental->{'hidden'}};
18462: }
18463: if (ref($supplemental->{'ids'}) eq 'HASH') {
18464: %suppids = %{$supplemental->{'ids'}};
18465: }
18466: }
18467: $got_supp = 1;
18468: }
18469: if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
18470: my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
18471: if ($supphidden{$mapid}) {
18472: $is_hidden = 1;
18473: }
18474: }
18475: $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
18476: } else {
18477: $supppath .= '&'.$items[$i];
18478: }
18479: } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
18480: $badpath = 1;
18481: } elsif ($supplementalflag) {
18482: $supppath .= '&'.$items[$i];
18483: }
18484: last if ($badpath);
18485: }
18486: if ($badpath) {
18487: delete($env{'form.folderpath'});
18488: } elsif ($changed && $supplementalflag) {
18489: $supppath =~ s/^\&//;
18490: $env{'form.folderpath'} = $supppath;
18491: }
18492: }
18493: return;
18494: }
18495:
18496: sub captcha_display {
18497: my ($context,$lonhost,$defdom) = @_;
18498: my ($output,$error);
18499: my ($captcha,$pubkey,$privkey,$version) =
18500: &get_captcha_config($context,$lonhost,$defdom);
18501: if ($captcha eq 'original') {
18502: $output = &create_captcha();
18503: unless ($output) {
18504: $error = 'captcha';
18505: }
18506: } elsif ($captcha eq 'recaptcha') {
18507: $output = &create_recaptcha($pubkey,$version);
18508: unless ($output) {
18509: $error = 'recaptcha';
18510: }
18511: }
18512: return ($output,$error,$captcha,$version);
18513: }
18514:
18515: sub captcha_response {
18516: my ($context,$lonhost,$defdom) = @_;
18517: my ($captcha_chk,$captcha_error);
18518: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18519: if ($captcha eq 'original') {
18520: ($captcha_chk,$captcha_error) = &check_captcha();
18521: } elsif ($captcha eq 'recaptcha') {
18522: $captcha_chk = &check_recaptcha($privkey,$version);
18523: } else {
18524: $captcha_chk = 1;
18525: }
18526: return ($captcha_chk,$captcha_error);
18527: }
18528:
18529: sub get_captcha_config {
18530: my ($context,$lonhost,$dom_in_effect) = @_;
18531: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18532: my $hostname = &Apache::lonnet::hostname($lonhost);
18533: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18534: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18535: if ($context eq 'usercreation') {
18536: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18537: if (ref($domconfig{$context}) eq 'HASH') {
18538: $hashtocheck = $domconfig{$context}{'cancreate'};
18539: if (ref($hashtocheck) eq 'HASH') {
18540: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18541: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18542: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18543: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18544: }
18545: if ($privkey && $pubkey) {
18546: $captcha = 'recaptcha';
18547: $version = $hashtocheck->{'recaptchaversion'};
18548: if ($version ne '2') {
18549: $version = 1;
18550: }
18551: } else {
18552: $captcha = 'original';
18553: }
18554: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18555: $captcha = 'original';
18556: }
18557: }
18558: } else {
18559: $captcha = 'captcha';
18560: }
18561: } elsif ($context eq 'login') {
18562: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18563: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18564: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18565: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18566: if ($privkey && $pubkey) {
18567: $captcha = 'recaptcha';
18568: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18569: if ($version ne '2') {
18570: $version = 1;
18571: }
18572: } else {
18573: $captcha = 'original';
18574: }
18575: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18576: $captcha = 'original';
18577: }
18578: } elsif ($context eq 'passwords') {
18579: if ($dom_in_effect) {
18580: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18581: if ($passwdconf{'captcha'} eq 'recaptcha') {
18582: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18583: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18584: $privkey = $passwdconf{'recaptchakeys'}{'private'};
18585: }
18586: if ($privkey && $pubkey) {
18587: $captcha = 'recaptcha';
18588: $version = $passwdconf{'recaptchaversion'};
18589: if ($version ne '2') {
18590: $version = 1;
18591: }
18592: } else {
18593: $captcha = 'original';
18594: }
18595: } elsif ($passwdconf{'captcha'} ne 'notused') {
18596: $captcha = 'original';
18597: }
18598: }
18599: }
18600: return ($captcha,$pubkey,$privkey,$version);
18601: }
18602:
18603: sub create_captcha {
18604: my %captcha_params = &captcha_settings();
18605: my ($output,$maxtries,$tries) = ('',10,0);
18606: while ($tries < $maxtries) {
18607: $tries ++;
18608: my $captcha = Authen::Captcha->new (
18609: output_folder => $captcha_params{'output_dir'},
18610: data_folder => $captcha_params{'db_dir'},
18611: );
18612: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18613:
18614: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18615: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18616: '<span class="LC_nobreak">'.
18617: &mt('Type in the letters/numbers shown below').' '.
18618: '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
18619: '</span><br />'.
18620: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18621: last;
18622: }
18623: }
18624: if ($output eq '') {
18625: &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18626: }
18627: return $output;
18628: }
18629:
18630: sub captcha_settings {
18631: my %captcha_params = (
18632: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18633: www_output_dir => "/captchaspool",
18634: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18635: numchars => '5',
18636: );
18637: return %captcha_params;
18638: }
18639:
18640: sub check_captcha {
18641: my ($captcha_chk,$captcha_error);
18642: my $code = $env{'form.code'};
18643: my $md5sum = $env{'form.crypt'};
18644: my %captcha_params = &captcha_settings();
18645: my $captcha = Authen::Captcha->new(
18646: output_folder => $captcha_params{'output_dir'},
18647: data_folder => $captcha_params{'db_dir'},
18648: );
18649: $captcha_chk = $captcha->check_code($code,$md5sum);
18650: my %captcha_hash = (
18651: 0 => 'Code not checked (file error)',
18652: -1 => 'Failed: code expired',
18653: -2 => 'Failed: invalid code (not in database)',
18654: -3 => 'Failed: invalid code (code does not match crypt)',
18655: );
18656: if ($captcha_chk != 1) {
18657: $captcha_error = $captcha_hash{$captcha_chk}
18658: }
18659: return ($captcha_chk,$captcha_error);
18660: }
18661:
18662: sub create_recaptcha {
18663: my ($pubkey,$version) = @_;
18664: if ($version >= 2) {
18665: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18666: '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18667: } else {
18668: my $use_ssl;
18669: if ($ENV{'SERVER_PORT'} == 443) {
18670: $use_ssl = 1;
18671: }
18672: my $captcha = Captcha::reCAPTCHA->new;
18673: return $captcha->get_options_setter({theme => 'white'})."\n".
18674: $captcha->get_html($pubkey,undef,$use_ssl).
18675: &mt('If the text is hard to read, [_1] will replace them.',
18676: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18677: '<br /><br />';
18678: }
18679: }
18680:
18681: sub check_recaptcha {
18682: my ($privkey,$version) = @_;
18683: my $captcha_chk;
18684: my $ip = &Apache::lonnet::get_requestor_ip();
18685: if ($version >= 2) {
18686: my $ua = LWP::UserAgent->new;
18687: $ua->timeout(10);
18688: my %info = (
18689: secret => $privkey,
18690: response => $env{'form.g-recaptcha-response'},
18691: remoteip => $ip,
18692: );
18693: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
18694: if ($response->is_success) {
18695: my $data = JSON::DWIW->from_json($response->decoded_content);
18696: if (ref($data) eq 'HASH') {
18697: if ($data->{'success'}) {
18698: $captcha_chk = 1;
18699: }
18700: }
18701: }
18702: } else {
18703: my $captcha = Captcha::reCAPTCHA->new;
18704: my $captcha_result =
18705: $captcha->check_answer(
18706: $privkey,
18707: $ip,
18708: $env{'form.recaptcha_challenge_field'},
18709: $env{'form.recaptcha_response_field'},
18710: );
18711: if ($captcha_result->{is_valid}) {
18712: $captcha_chk = 1;
18713: }
18714: }
18715: return $captcha_chk;
18716: }
18717:
18718: sub emailusername_info {
18719: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18720: my %titles = &Apache::lonlocal::texthash (
18721: lastname => 'Last Name',
18722: firstname => 'First Name',
18723: institution => 'School/college/university',
18724: location => "School's city, state/province, country",
18725: web => "School's web address",
18726: officialemail => 'E-mail address at institution (if different)',
18727: id => 'Student/Employee ID',
18728: );
18729: return (\@fields,\%titles);
18730: }
18731:
18732: sub cleanup_html {
18733: my ($incoming) = @_;
18734: my $outgoing;
18735: if ($incoming ne '') {
18736: $outgoing = $incoming;
18737: $outgoing =~ s/;/;/g;
18738: $outgoing =~ s/\#/#/g;
18739: $outgoing =~ s/\&/&/g;
18740: $outgoing =~ s/</</g;
18741: $outgoing =~ s/>/>/g;
18742: $outgoing =~ s/\(/(/g;
18743: $outgoing =~ s/\)/)/g;
18744: $outgoing =~ s/"/"/g;
18745: $outgoing =~ s/'/'/g;
18746: $outgoing =~ s/\$/$/g;
18747: $outgoing =~ s{/}{/}g;
18748: $outgoing =~ s/=/=/g;
18749: $outgoing =~ s/\\/\/g
18750: }
18751: return $outgoing;
18752: }
18753:
18754: # Checks for critical messages and returns a redirect url if one exists.
18755: # $interval indicates how often to check for messages.
18756: # $context is the calling context -- roles, grades, contents, menu or flip.
18757: sub critical_redirect {
18758: my ($interval,$context) = @_;
18759: unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18760: return ();
18761: }
18762: if ((time-$env{'user.criticalcheck.time'})>$interval) {
18763: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18764: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18765: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18766: my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18767: if ($blocked) {
18768: my $checkrole = "cm./$cdom/$cnum";
18769: if ($env{'request.course.sec'} ne '') {
18770: $checkrole .= "/$env{'request.course.sec'}";
18771: }
18772: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18773: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18774: return;
18775: }
18776: }
18777: }
18778: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18779: $env{'user.name'});
18780: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18781: my $redirecturl;
18782: if ($what[0]) {
18783: if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18784: $redirecturl='/adm/email?critical=display';
18785: my $url=&Apache::lonnet::absolute_url().$redirecturl;
18786: return (1, $url);
18787: }
18788: }
18789: }
18790: return ();
18791: }
18792:
18793: # Use:
18794: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18795: #
18796: ##################################################
18797: # password associated functions #
18798: ##################################################
18799: sub des_keys {
18800: # Make a new key for DES encryption.
18801: # Each key has two parts which are returned separately.
18802: # Please note: Each key must be passed through the &hex function
18803: # before it is output to the web browser. The hex versions cannot
18804: # be used to decrypt.
18805: my @hexstr=('0','1','2','3','4','5','6','7',
18806: '8','9','a','b','c','d','e','f');
18807: my $lkey='';
18808: for (0..7) {
18809: $lkey.=$hexstr[rand(15)];
18810: }
18811: my $ukey='';
18812: for (0..7) {
18813: $ukey.=$hexstr[rand(15)];
18814: }
18815: return ($lkey,$ukey);
18816: }
18817:
18818: sub des_decrypt {
18819: my ($key,$cyphertext) = @_;
18820: my $keybin=pack("H16",$key);
18821: my $cypher;
18822: if ($Crypt::DES::VERSION>=2.03) {
18823: $cypher=new Crypt::DES $keybin;
18824: } else {
18825: $cypher=new DES $keybin;
18826: }
18827: my $plaintext='';
18828: my $cypherlength = length($cyphertext);
18829: my $numchunks = int($cypherlength/32);
18830: for (my $j=0; $j<$numchunks; $j++) {
18831: my $start = $j*32;
18832: my $cypherblock = substr($cyphertext,$start,32);
18833: my $chunk =
18834: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18835: $chunk .=
18836: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18837: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18838: $plaintext .= $chunk;
18839: }
18840: return $plaintext;
18841: }
18842:
18843: sub get_requested_shorturls {
18844: my ($cdom,$cnum,$navmap) = @_;
18845: return unless (ref($navmap));
18846: my ($numnew,$errors);
18847: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18848: if (@toshorten) {
18849: my (%maps,%resources,%titles);
18850: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18851: 'shorturls',$cdom,$cnum);
18852: if (keys(%resources)) {
18853: my %tocreate;
18854: foreach my $item (sort {$a <=> $b} (@toshorten)) {
18855: my $symb = $resources{$item};
18856: if ($symb) {
18857: $tocreate{$cnum.'&'.$symb} = 1;
18858: }
18859: }
18860: if (keys(%tocreate)) {
18861: ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18862: \%tocreate);
18863: }
18864: }
18865: }
18866: return ($numnew,$errors);
18867: }
18868:
18869: sub make_short_symbs {
18870: my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18871: my ($numnew,@errors);
18872: if (ref($tocreateref) eq 'HASH') {
18873: my %tocreate = %{$tocreateref};
18874: if (keys(%tocreate)) {
18875: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18876: my $su = Short::URL->new(no_vowels => 1);
18877: my $init = '';
18878: my (%newunique,%addcourse,%courseonly,%failed);
18879: # get lock on tiny db
18880: my $now = time;
18881: if ($lockuser eq '') {
18882: $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18883: }
18884: my $lockhash = {
18885: "lock\0$now" => $lockuser,
18886: };
18887: my $tries = 0;
18888: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18889: my ($code,$error);
18890: while (($gotlock ne 'ok') && ($tries<3)) {
18891: $tries ++;
18892: sleep 1;
18893: $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18894: }
18895: if ($gotlock eq 'ok') {
18896: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18897: \%addcourse,\%courseonly,\%failed);
18898: if (keys(%failed)) {
18899: my $numfailed = scalar(keys(%failed));
18900: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18901: }
18902: if (keys(%newunique)) {
18903: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18904: if ($putres eq 'ok') {
18905: $numnew = scalar(keys(%newunique));
18906: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18907: unless ($newputres eq 'ok') {
18908: push(@errors,&mt('error: could not store course look-up of short URLs'));
18909: }
18910: } else {
18911: push(@errors,&mt('error: could not store unique six character URLs'));
18912: }
18913: }
18914: my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18915: unless ($dellockres eq 'ok') {
18916: push(@errors,&mt('error: could not release lockfile'));
18917: }
18918: } else {
18919: push(@errors,&mt('error: could not obtain lockfile'));
18920: }
18921: if (keys(%courseonly)) {
18922: my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18923: if ($result ne 'ok') {
18924: push(@errors,&mt('error: could not update course look-up of short URLs'));
18925: }
18926: }
18927: }
18928: }
18929: return ($numnew,\@errors);
18930: }
18931:
18932: sub shorten_symbs {
18933: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18934: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18935: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18936: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18937: my (%possibles,%collisions);
18938: foreach my $key (keys(%{$tocreate})) {
18939: my $num = String::CRC32::crc32($key);
18940: my $tiny = $su->encode($num,$init);
18941: if ($tiny) {
18942: $possibles{$tiny} = $key;
18943: }
18944: }
18945: if (!$init) {
18946: $init = 1;
18947: } else {
18948: $init ++;
18949: }
18950: if (keys(%possibles)) {
18951: my @posstiny = keys(%possibles);
18952: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18953: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18954: if (keys(%currtiny)) {
18955: foreach my $key (keys(%currtiny)) {
18956: next if ($currtiny{$key} eq '');
18957: if ($currtiny{$key} eq $possibles{$key}) {
18958: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18959: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18960: $courseonly->{$tsymb} = $key;
18961: }
18962: } else {
18963: $collisions{$possibles{$key}} = 1;
18964: }
18965: delete($possibles{$key});
18966: }
18967: }
18968: foreach my $key (keys(%possibles)) {
18969: $newunique->{$key} = $possibles{$key};
18970: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18971: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18972: $addcourse->{$tsymb} = $key;
18973: }
18974: }
18975: }
18976: if (keys(%collisions)) {
18977: if ($init <5) {
18978: if (!$init) {
18979: $init = 1;
18980: } else {
18981: $init ++;
18982: }
18983: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18984: $newunique,$addcourse,$courseonly,$failed);
18985: } else {
18986: foreach my $key (keys(%collisions)) {
18987: $failed->{$key} = 1;
18988: $failed->{$key} = 1;
18989: }
18990: }
18991: }
18992: return $init;
18993: }
18994:
18995: sub is_nonframeable {
18996: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18997: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18998: return if (($remprotocol eq '') || ($remhost eq ''));
18999:
19000: $remprotocol = lc($remprotocol);
19001: $remhost = lc($remhost);
19002: my $remport = 80;
19003: if ($remprotocol eq 'https') {
19004: $remport = 443;
19005: }
19006: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19007: if ($cached) {
19008: unless ($nocache) {
19009: if ($result) {
19010: return 1;
19011: } else {
19012: return 0;
19013: }
19014: }
19015: }
19016: my $uselink;
19017: my $request = new HTTP::Request('HEAD',$url);
19018: my $ua = LWP::UserAgent->new;
19019: $ua->timeout(5);
19020: my $response=$ua->request($request);
19021: if ($response->is_success()) {
19022: my $secpolicy = lc($response->header('content-security-policy'));
19023: my $xframeop = lc($response->header('x-frame-options'));
19024: $secpolicy =~ s/^\s+|\s+$//g;
19025: $xframeop =~ s/^\s+|\s+$//g;
19026: if (($secpolicy ne '') || ($xframeop ne '')) {
19027: my $remotehost = $remprotocol.'://'.$remhost;
19028: my ($origin,$protocol,$port);
19029: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19030: $port = $ENV{'SERVER_PORT'};
19031: } else {
19032: $port = 80;
19033: }
19034: if ($absolute eq '') {
19035: $protocol = 'http:';
19036: if ($port == 443) {
19037: $protocol = 'https:';
19038: }
19039: $origin = $protocol.'//'.lc($hostname);
19040: } else {
19041: $origin = lc($absolute);
19042: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19043: }
19044: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19045: my $framepolicy = $1;
19046: $framepolicy =~ s/^\s+|\s+$//g;
19047: my @policies = split(/\s+/,$framepolicy);
19048: if (@policies) {
19049: if (grep(/^\Q'none'\E$/,@policies)) {
19050: $uselink = 1;
19051: } else {
19052: $uselink = 1;
19053: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19054: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19055: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19056: undef($uselink);
19057: }
19058: if ($uselink) {
19059: if (grep(/^\Q'self'\E$/,@policies)) {
19060: if (($origin ne '') && ($remotehost eq $origin)) {
19061: undef($uselink);
19062: }
19063: }
19064: }
19065: if ($uselink) {
19066: my @possok;
19067: if ($ip ne '') {
19068: push(@possok,$ip);
19069: }
19070: my $hoststr = '';
19071: foreach my $part (reverse(split(/\./,$hostname))) {
19072: if ($hoststr eq '') {
19073: $hoststr = $part;
19074: } else {
19075: $hoststr = "$part.$hoststr";
19076: }
19077: if ($hoststr eq $hostname) {
19078: push(@possok,$hostname);
19079: } else {
19080: push(@possok,"*.$hoststr");
19081: }
19082: }
19083: if (@possok) {
19084: foreach my $poss (@possok) {
19085: last if (!$uselink);
19086: foreach my $policy (@policies) {
19087: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19088: undef($uselink);
19089: last;
19090: }
19091: }
19092: }
19093: }
19094: }
19095: }
19096: }
19097: } elsif ($xframeop ne '') {
19098: $uselink = 1;
19099: my @policies = split(/\s*,\s*/,$xframeop);
19100: if (@policies) {
19101: unless (grep(/^deny$/,@policies)) {
19102: if ($origin ne '') {
19103: if (grep(/^sameorigin$/,@policies)) {
19104: if ($remotehost eq $origin) {
19105: undef($uselink);
19106: }
19107: }
19108: if ($uselink) {
19109: foreach my $policy (@policies) {
19110: if ($policy =~ /^allow-from\s*(.+)$/) {
19111: my $allowfrom = $1;
19112: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19113: undef($uselink);
19114: last;
19115: }
19116: }
19117: }
19118: }
19119: }
19120: }
19121: }
19122: }
19123: }
19124: }
19125: if ($nocache) {
19126: if ($cached) {
19127: my $devalidate;
19128: if ($uselink && !$result) {
19129: $devalidate = 1;
19130: } elsif (!$uselink && $result) {
19131: $devalidate = 1;
19132: }
19133: if ($devalidate) {
19134: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19135: }
19136: }
19137: } else {
19138: if ($uselink) {
19139: $result = 1;
19140: } else {
19141: $result = 0;
19142: }
19143: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19144: }
19145: return $uselink;
19146: }
19147:
19148: sub page_menu {
19149: my ($menucolls,$menunum) = @_;
19150: my %menu;
19151: foreach my $item (split(/;/,$menucolls)) {
19152: my ($num,$value) = split(/\%/,$item);
19153: if ($num eq $menunum) {
19154: my @entries = split(/\&/,$value);
19155: foreach my $entry (@entries) {
19156: my ($name,$fields) = split(/=/,$entry);
19157: if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19158: $menu{$name} = $fields;
19159: } else {
19160: my @shown;
19161: if ($fields =~ /,/) {
19162: @shown = split(/,/,$fields);
19163: } else {
19164: @shown = ($fields);
19165: }
19166: if (@shown) {
19167: foreach my $field (@shown) {
19168: next if ($field eq '');
19169: $menu{$field} = 1;
19170: }
19171: }
19172: }
19173: }
19174: }
19175: }
19176: return %menu;
19177: }
19178:
19179: 1;
19180: __END__;
19181:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>