File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1381:
download - view:
text,
annotated -
select for diffs
Sun May 29 20:37:21 2022 UTC (2 years, 2 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bug 6907
- When context is LTI Provider, or deep-linked, and display is embedded in
another web page, set target to _parent for inline menu links, and help
item when displayng search results within LON-CAPA's own frames.
- Tenth arg for lonhtmlcommon::breadcrumbs() now $links_target instead of
$crstype. $crstype had been added in 1.371, but ceased being used in 1.379.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1381 2022/05/29 20:37:21 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use LONCAPA::LWPReq;
75: use HTTP::Request;
76: use DateTime::TimeZone;
77: use DateTime::Locale;
78: use Encode();
79: use Text::Aspell;
80: use Authen::Captcha;
81: use Captcha::reCAPTCHA;
82: use JSON::DWIW;
83: use Crypt::DES;
84: use DynaLoader; # for Crypt::DES version
85: use MIME::Lite;
86: use MIME::Types;
87: use File::Copy();
88: use File::Path();
89: use String::CRC32();
90: use Short::URL();
91:
92: # ---------------------------------------------- Designs
93: use vars qw(%defaultdesign);
94:
95: my $readit;
96:
97:
98: ##
99: ## Global Variables
100: ##
101:
102:
103: # ----------------------------------------------- SSI with retries:
104: #
105:
106: =pod
107:
108: =head1 Server Side include with retries:
109:
110: =over 4
111:
112: =item * &ssi_with_retries(resource,retries form)
113:
114: Performs an ssi with some number of retries. Retries continue either
115: until the result is ok or until the retry count supplied by the
116: caller is exhausted.
117:
118: Inputs:
119:
120: =over 4
121:
122: resource - Identifies the resource to insert.
123:
124: retries - Count of the number of retries allowed.
125:
126: form - Hash that identifies the rendering options.
127:
128: =back
129:
130: Returns:
131:
132: =over 4
133:
134: content - The content of the response. If retries were exhausted this is empty.
135:
136: response - The response from the last attempt (which may or may not have been successful.
137:
138: =back
139:
140: =back
141:
142: =cut
143:
144: sub ssi_with_retries {
145: my ($resource, $retries, %form) = @_;
146:
147:
148: my $ok = 0; # True if we got a good response.
149: my $content;
150: my $response;
151:
152: # Try to get the ssi done. within the retries count:
153:
154: do {
155: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
156: $ok = $response->is_success;
157: if (!$ok) {
158: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
159: }
160: $retries--;
161: } while (!$ok && ($retries > 0));
162:
163: if (!$ok) {
164: $content = ''; # On error return an empty content.
165: }
166: return ($content, $response);
167:
168: }
169:
170:
171:
172: # ----------------------------------------------- Filetypes/Languages/Copyright
173: my %language;
174: my %supported_language;
175: my %supported_codes;
176: my %latex_language; # For choosing hyphenation in <transl..>
177: my %latex_language_bykey; # for choosing hyphenation from metadata
178: my %cprtag;
179: my %scprtag;
180: my %fe; my %fd; my %fm;
181: my %category_extensions;
182:
183: # ---------------------------------------------- Thesaurus variables
184: #
185: # %Keywords:
186: # A hash used by &keyword to determine if a word is considered a keyword.
187: # $thesaurus_db_file
188: # Scalar containing the full path to the thesaurus database.
189:
190: my %Keywords;
191: my $thesaurus_db_file;
192:
193: #
194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
195: # thesaurus.tab, and filecategories.tab.
196: #
197: BEGIN {
198: # Variable initialization
199: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
200: #
201: unless ($readit) {
202: # ------------------------------------------------------------------- languages
203: {
204: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
205: '/language.tab';
206: if ( open(my $fh,'<',$langtabfile) ) {
207: while (my $line = <$fh>) {
208: next if ($line=~/^\#/);
209: chomp($line);
210: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
211: $language{$key}=$val.' - '.$enc;
212: if ($sup) {
213: $supported_language{$key}=$sup;
214: $supported_codes{$key} = $code;
215: }
216: if ($latex) {
217: $latex_language_bykey{$key} = $latex;
218: $latex_language{$code} = $latex;
219: }
220: }
221: close($fh);
222: }
223: }
224: # ------------------------------------------------------------------ copyrights
225: {
226: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
227: '/copyright.tab';
228: if ( open (my $fh,'<',$copyrightfile) ) {
229: while (my $line = <$fh>) {
230: next if ($line=~/^\#/);
231: chomp($line);
232: my ($key,$val)=(split(/\s+/,$line,2));
233: $cprtag{$key}=$val;
234: }
235: close($fh);
236: }
237: }
238: # ----------------------------------------------------------- source copyrights
239: {
240: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
241: '/source_copyright.tab';
242: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
243: while (my $line = <$fh>) {
244: next if ($line =~ /^\#/);
245: chomp($line);
246: my ($key,$val)=(split(/\s+/,$line,2));
247: $scprtag{$key}=$val;
248: }
249: close($fh);
250: }
251: }
252:
253: # -------------------------------------------------------------- default domain designs
254: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
255: my $designfile = $designdir.'/default.tab';
256: if ( open (my $fh,'<',$designfile) ) {
257: while (my $line = <$fh>) {
258: next if ($line =~ /^\#/);
259: chomp($line);
260: my ($key,$val)=(split(/\=/,$line));
261: if ($val) { $defaultdesign{$key}=$val; }
262: }
263: close($fh);
264: }
265:
266: # ------------------------------------------------------------- file categories
267: {
268: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
269: '/filecategories.tab';
270: if ( open (my $fh,'<',$categoryfile) ) {
271: while (my $line = <$fh>) {
272: next if ($line =~ /^\#/);
273: chomp($line);
274: my ($extension,$category)=(split(/\s+/,$line,2));
275: push(@{$category_extensions{lc($category)}},$extension);
276: }
277: close($fh);
278: }
279:
280: }
281: # ------------------------------------------------------------------ file types
282: {
283: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
284: '/filetypes.tab';
285: if ( open (my $fh,'<',$typesfile) ) {
286: while (my $line = <$fh>) {
287: next if ($line =~ /^\#/);
288: chomp($line);
289: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
290: if ($descr ne '') {
291: $fe{$ending}=lc($emb);
292: $fd{$ending}=$descr;
293: if ($mime ne 'unk') { $fm{$ending}=$mime; }
294: }
295: }
296: close($fh);
297: }
298: }
299: &Apache::lonnet::logthis(
300: "<span style='color:yellow;'>INFO: Read file types</span>");
301: $readit=1;
302: } # end of unless($readit)
303:
304: }
305:
306: ###############################################################
307: ## HTML and Javascript Helper Functions ##
308: ###############################################################
309:
310: =pod
311:
312: =head1 HTML and Javascript Functions
313:
314: =over 4
315:
316: =item * &browser_and_searcher_javascript()
317:
318: X<browsing, javascript>X<searching, javascript>Returns a string
319: containing javascript with two functions, C<openbrowser> and
320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
321: tags.
322:
323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
324:
325: inputs: formname, elementname, only, omit
326:
327: formname and elementname indicate the name of the html form and name of
328: the element that the results of the browsing selection are to be placed in.
329:
330: Specifying 'only' will restrict the browser to displaying only files
331: with the given extension. Can be a comma separated list.
332:
333: Specifying 'omit' will restrict the browser to NOT displaying files
334: with the given extension. Can be a comma separated list.
335:
336: =item * &opensearcher(formname,elementname) [javascript]
337:
338: Inputs: formname, elementname
339:
340: formname and elementname specify the name of the html form and the name
341: of the element the selection from the search results will be placed in.
342:
343: =cut
344:
345: sub browser_and_searcher_javascript {
346: my ($mode)=@_;
347: if (!defined($mode)) { $mode='edit'; }
348: my $resurl=&escape_single(&lastresurl());
349: return <<END;
350: // <!-- BEGIN LON-CAPA Internal
351: var editbrowser = null;
352: function openbrowser(formname,elementname,only,omit,titleelement) {
353: var url = '$resurl/?';
354: if (editbrowser == null) {
355: url += 'launch=1&';
356: }
357: url += 'catalogmode=interactive&';
358: url += 'mode=$mode&';
359: url += 'inhibitmenu=yes&';
360: url += 'form=' + formname + '&';
361: if (only != null) {
362: url += 'only=' + only + '&';
363: } else {
364: url += 'only=&';
365: }
366: if (omit != null) {
367: url += 'omit=' + omit + '&';
368: } else {
369: url += 'omit=&';
370: }
371: if (titleelement != null) {
372: url += 'titleelement=' + titleelement + '&';
373: } else {
374: url += 'titleelement=&';
375: }
376: url += 'element=' + elementname + '';
377: var title = 'Browser';
378: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
379: options += ',width=700,height=600';
380: editbrowser = open(url,title,options,'1');
381: editbrowser.focus();
382: }
383: var editsearcher;
384: function opensearcher(formname,elementname,titleelement) {
385: var url = '/adm/searchcat?';
386: if (editsearcher == null) {
387: url += 'launch=1&';
388: }
389: url += 'catalogmode=interactive&';
390: url += 'mode=$mode&';
391: url += 'form=' + formname + '&';
392: if (titleelement != null) {
393: url += 'titleelement=' + titleelement + '&';
394: } else {
395: url += 'titleelement=&';
396: }
397: url += 'element=' + elementname + '';
398: var title = 'Search';
399: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
400: options += ',width=700,height=600';
401: editsearcher = open(url,title,options,'1');
402: editsearcher.focus();
403: }
404: // END LON-CAPA Internal -->
405: END
406: }
407:
408: sub lastresurl {
409: if ($env{'environment.lastresurl'}) {
410: return $env{'environment.lastresurl'}
411: } else {
412: return '/res';
413: }
414: }
415:
416: sub storeresurl {
417: my $resurl=&Apache::lonnet::clutter(shift);
418: unless ($resurl=~/^\/res/) { return 0; }
419: $resurl=~s/\/$//;
420: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
421: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
422: return 1;
423: }
424:
425: sub studentbrowser_javascript {
426: unless (
427: (($env{'request.course.id'}) &&
428: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
429: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
430: '/'.$env{'request.course.sec'})
431: ))
432: || ($env{'request.role'}=~/^(au|dc|su)/)
433: ) { return ''; }
434: return (<<'ENDSTDBRW');
435: <script type="text/javascript" language="Javascript">
436: // <![CDATA[
437: var stdeditbrowser;
438: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
439: var url = '/adm/pickstudent?';
440: var filter;
441: if (!ignorefilter) {
442: eval('filter=document.'+formname+'.'+uname+'.value;');
443: }
444: if (filter != null) {
445: if (filter != '') {
446: url += 'filter='+filter+'&';
447: }
448: }
449: url += 'form=' + formname + '&unameelement='+uname+
450: '&udomelement='+udom+
451: '&clicker='+clicker;
452: if (roleflag) { url+="&roles=1"; }
453: if (courseadv == 'condition') {
454: if (document.getElementById('courseadv')) {
455: courseadv = document.getElementById('courseadv').value;
456: }
457: }
458: if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
459: var title = 'Student_Browser';
460: var options = 'scrollbars=1,resizable=1,menubar=0';
461: options += ',width=700,height=600';
462: stdeditbrowser = open(url,title,options,'1');
463: stdeditbrowser.focus();
464: }
465: // ]]>
466: </script>
467: ENDSTDBRW
468: }
469:
470: sub resourcebrowser_javascript {
471: unless ($env{'request.course.id'}) { return ''; }
472: return (<<'ENDRESBRW');
473: <script type="text/javascript" language="Javascript">
474: // <![CDATA[
475: var reseditbrowser;
476: function openresbrowser(formname,reslink) {
477: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
478: var title = 'Resource_Browser';
479: var options = 'scrollbars=1,resizable=1,menubar=0';
480: options += ',width=700,height=500';
481: reseditbrowser = open(url,title,options,'1');
482: reseditbrowser.focus();
483: }
484: // ]]>
485: </script>
486: ENDRESBRW
487: }
488:
489: sub selectstudent_link {
490: my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
491: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
492: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
493: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
494: if ($env{'request.course.id'}) {
495: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
496: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
497: '/'.$env{'request.course.sec'})) {
498: return '';
499: }
500: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
501: if ($courseadv eq 'only') {
502: $callargs .= ",'',1,'$courseadv'";
503: } elsif ($courseadv eq 'none') {
504: $callargs .= ",'','','$courseadv'";
505: } elsif ($courseadv eq 'condition') {
506: $callargs .= ",'','','$courseadv'";
507: }
508: return '<span class="LC_nobreak">'.
509: '<a href="javascript:openstdbrowser('.$callargs.');">'.
510: &mt('Select User').'</a></span>';
511: }
512: if ($env{'request.role'}=~/^(au|dc|su)/) {
513: $callargs .= ",'',1";
514: return '<span class="LC_nobreak">'.
515: '<a href="javascript:openstdbrowser('.$callargs.');">'.
516: &mt('Select User').'</a></span>';
517: }
518: return '';
519: }
520:
521: sub selectresource_link {
522: my ($form,$reslink,$arg)=@_;
523:
524: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
525: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
526: unless ($env{'request.course.id'}) { return $arg; }
527: return '<span class="LC_nobreak">'.
528: '<a href="javascript:openresbrowser('.$callargs.');">'.
529: $arg.'</a></span>';
530: }
531:
532:
533:
534: sub authorbrowser_javascript {
535: return <<"ENDAUTHORBRW";
536: <script type="text/javascript" language="JavaScript">
537: // <![CDATA[
538: var stdeditbrowser;
539:
540: function openauthorbrowser(formname,udom) {
541: var url = '/adm/pickauthor?';
542: url += 'form='+formname+'&roledom='+udom;
543: var title = 'Author_Browser';
544: var options = 'scrollbars=1,resizable=1,menubar=0';
545: options += ',width=700,height=600';
546: stdeditbrowser = open(url,title,options,'1');
547: stdeditbrowser.focus();
548: }
549:
550: // ]]>
551: </script>
552: ENDAUTHORBRW
553: }
554:
555: sub coursebrowser_javascript {
556: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
557: $credits_element,$instcode) = @_;
558: my $wintitle = 'Course_Browser';
559: if ($crstype eq 'Community') {
560: $wintitle = 'Community_Browser';
561: }
562: my $id_functions = &javascript_index_functions();
563: my $output = '
564: <script type="text/javascript" language="JavaScript">
565: // <![CDATA[
566: var stdeditbrowser;'."\n";
567:
568: $output .= <<"ENDSTDBRW";
569: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
570: var url = '/adm/pickcourse?';
571: var formid = getFormIdByName(formname);
572: var domainfilter = getDomainFromSelectbox(formname,udom);
573: if (domainfilter != null) {
574: if (domainfilter != '') {
575: url += 'domainfilter='+domainfilter+'&';
576: }
577: }
578: url += 'form=' + formname + '&cnumelement='+uname+
579: '&cdomelement='+udom+
580: '&cnameelement='+desc;
581: if (extra_element !=null && extra_element != '') {
582: if (formname == 'rolechoice' || formname == 'studentform') {
583: url += '&roleelement='+extra_element;
584: if (domainfilter == null || domainfilter == '') {
585: url += '&domainfilter='+extra_element;
586: }
587: }
588: else {
589: if (formname == 'portform') {
590: url += '&setroles='+extra_element;
591: } else {
592: if (formname == 'rules') {
593: url += '&fixeddom='+extra_element;
594: }
595: }
596: }
597: }
598: if (type != null && type != '') {
599: url += '&type='+type;
600: }
601: if (type_elem != null && type_elem != '') {
602: url += '&typeelement='+type_elem;
603: }
604: if (formname == 'ccrs') {
605: var ownername = document.forms[formid].ccuname.value;
606: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
607: url += '&cloner='+ownername+':'+ownerdom;
608: if (type == 'Course') {
609: url += '&crscode='+document.forms[formid].crscode.value;
610: }
611: }
612: if (formname == 'requestcrs') {
613: url += '&crsdom=$domainfilter&crscode=$instcode';
614: }
615: if (multflag !=null && multflag != '') {
616: url += '&multiple='+multflag;
617: }
618: var title = '$wintitle';
619: var options = 'scrollbars=1,resizable=1,menubar=0';
620: options += ',width=700,height=600';
621: stdeditbrowser = open(url,title,options,'1');
622: stdeditbrowser.focus();
623: }
624: $id_functions
625: ENDSTDBRW
626: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
627: $output .= &setsec_javascript($sec_element,$formname,$role_element,
628: $credits_element);
629: }
630: $output .= '
631: // ]]>
632: </script>';
633: return $output;
634: }
635:
636: sub javascript_index_functions {
637: return <<"ENDJS";
638:
639: function getFormIdByName(formname) {
640: for (var i=0;i<document.forms.length;i++) {
641: if (document.forms[i].name == formname) {
642: return i;
643: }
644: }
645: return -1;
646: }
647:
648: function getIndexByName(formid,item) {
649: for (var i=0;i<document.forms[formid].elements.length;i++) {
650: if (document.forms[formid].elements[i].name == item) {
651: return i;
652: }
653: }
654: return -1;
655: }
656:
657: function getDomainFromSelectbox(formname,udom) {
658: var userdom;
659: var formid = getFormIdByName(formname);
660: if (formid > -1) {
661: var domid = getIndexByName(formid,udom);
662: if (domid > -1) {
663: if (document.forms[formid].elements[domid].type == 'select-one') {
664: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
665: }
666: if (document.forms[formid].elements[domid].type == 'hidden') {
667: userdom=document.forms[formid].elements[domid].value;
668: }
669: }
670: }
671: return userdom;
672: }
673:
674: ENDJS
675:
676: }
677:
678: sub javascript_array_indexof {
679: return <<ENDJS;
680: <script type="text/javascript" language="JavaScript">
681: // <![CDATA[
682:
683: if (!Array.prototype.indexOf) {
684: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
685: "use strict";
686: if (this === void 0 || this === null) {
687: throw new TypeError();
688: }
689: var t = Object(this);
690: var len = t.length >>> 0;
691: if (len === 0) {
692: return -1;
693: }
694: var n = 0;
695: if (arguments.length > 0) {
696: n = Number(arguments[1]);
697: if (n !== n) { // shortcut for verifying if it is NaN
698: n = 0;
699: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
700: n = (n > 0 || -1) * Math.floor(Math.abs(n));
701: }
702: }
703: if (n >= len) {
704: return -1;
705: }
706: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
707: for (; k < len; k++) {
708: if (k in t && t[k] === searchElement) {
709: return k;
710: }
711: }
712: return -1;
713: }
714: }
715:
716: // ]]>
717: </script>
718:
719: ENDJS
720:
721: }
722:
723: sub userbrowser_javascript {
724: my $id_functions = &javascript_index_functions();
725: return <<"ENDUSERBRW";
726:
727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
728: var url = '/adm/pickuser?';
729: var userdom = getDomainFromSelectbox(formname,udom);
730: if (userdom != null) {
731: if (userdom != '') {
732: url += 'srchdom='+userdom+'&';
733: }
734: }
735: url += 'form=' + formname + '&unameelement='+uname+
736: '&udomelement='+udom+
737: '&ulastelement='+ulast+
738: '&ufirstelement='+ufirst+
739: '&uemailelement='+uemail+
740: '&hideudomelement='+hideudom+
741: '&coursedom='+crsdom;
742: if ((caller != null) && (caller != undefined)) {
743: url += '&caller='+caller;
744: }
745: var title = 'User_Browser';
746: var options = 'scrollbars=1,resizable=1,menubar=0';
747: options += ',width=700,height=600';
748: var stdeditbrowser = open(url,title,options,'1');
749: stdeditbrowser.focus();
750: }
751:
752: function fix_domain (formname,udom,origdom,uname) {
753: var formid = getFormIdByName(formname);
754: if (formid > -1) {
755: var unameid = getIndexByName(formid,uname);
756: var domid = getIndexByName(formid,udom);
757: var hidedomid = getIndexByName(formid,origdom);
758: if (hidedomid > -1) {
759: var fixeddom = document.forms[formid].elements[hidedomid].value;
760: var unameval = document.forms[formid].elements[unameid].value;
761: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
762: if (domid > -1) {
763: var slct = document.forms[formid].elements[domid];
764: if (slct.type == 'select-one') {
765: var i;
766: for (i=0;i<slct.length;i++) {
767: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
768: }
769: }
770: if (slct.type == 'hidden') {
771: slct.value = fixeddom;
772: }
773: }
774: }
775: }
776: }
777: return;
778: }
779:
780: $id_functions
781: ENDUSERBRW
782: }
783:
784: sub setsec_javascript {
785: my ($sec_element,$formname,$role_element,$credits_element) = @_;
786: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
787: $communityrolestr);
788: if ($role_element ne '') {
789: my @allroles = ('st','ta','ep','in','ad');
790: foreach my $crstype ('Course','Community') {
791: if ($crstype eq 'Community') {
792: foreach my $role (@allroles) {
793: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
794: }
795: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
796: } else {
797: foreach my $role (@allroles) {
798: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
799: }
800: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
801: }
802: }
803: $rolestr = '"'.join('","',@allroles).'"';
804: $courserolestr = '"'.join('","',@courserolenames).'"';
805: $communityrolestr = '"'.join('","',@communityrolenames).'"';
806: }
807: my $setsections = qq|
808: function setSect(sectionlist) {
809: var sectionsArray = new Array();
810: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
811: sectionsArray = sectionlist.split(",");
812: }
813: var numSections = sectionsArray.length;
814: document.$formname.$sec_element.length = 0;
815: if (numSections == 0) {
816: document.$formname.$sec_element.multiple=false;
817: document.$formname.$sec_element.size=1;
818: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
819: } else {
820: if (numSections == 1) {
821: document.$formname.$sec_element.multiple=false;
822: document.$formname.$sec_element.size=1;
823: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
824: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
825: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
826: } else {
827: for (var i=0; i<numSections; i++) {
828: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
829: }
830: document.$formname.$sec_element.multiple=true
831: if (numSections < 3) {
832: document.$formname.$sec_element.size=numSections;
833: } else {
834: document.$formname.$sec_element.size=3;
835: }
836: document.$formname.$sec_element.options[0].selected = false
837: }
838: }
839: }
840:
841: function setRole(crstype) {
842: |;
843: if ($role_element eq '') {
844: $setsections .= ' return;
845: }
846: ';
847: } else {
848: $setsections .= qq|
849: var elementLength = document.$formname.$role_element.length;
850: var allroles = Array($rolestr);
851: var courserolenames = Array($courserolestr);
852: var communityrolenames = Array($communityrolestr);
853: if (elementLength != undefined) {
854: if (document.$formname.$role_element.options[5].value == 'cc') {
855: if (crstype == 'Course') {
856: return;
857: } else {
858: allroles[5] = 'co';
859: for (var i=0; i<6; i++) {
860: document.$formname.$role_element.options[i].value = allroles[i];
861: document.$formname.$role_element.options[i].text = communityrolenames[i];
862: }
863: }
864: } else {
865: if (crstype == 'Community') {
866: return;
867: } else {
868: allroles[5] = 'cc';
869: for (var i=0; i<6; i++) {
870: document.$formname.$role_element.options[i].value = allroles[i];
871: document.$formname.$role_element.options[i].text = courserolenames[i];
872: }
873: }
874: }
875: }
876: return;
877: }
878: |;
879: }
880: if ($credits_element) {
881: $setsections .= qq|
882: function setCredits(defaultcredits) {
883: document.$formname.$credits_element.value = defaultcredits;
884: return;
885: }
886: |;
887: }
888: return $setsections;
889: }
890:
891: sub selectcourse_link {
892: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
893: $typeelement) = @_;
894: my $type = $selecttype;
895: my $linktext = &mt('Select Course');
896: if ($selecttype eq 'Community') {
897: $linktext = &mt('Select Community');
898: } elsif ($selecttype eq 'Placement') {
899: $linktext = &mt('Select Placement Test');
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,$disabled)=@_;
961: my $output='<select name="'.$name.'" '.$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:
1053: =item * &list_languages()
1054:
1055: Returns an array reference that is suitable for use in language prompters.
1056: Each array element is itself a two element array. The first element
1057: is the language code. The second element a descsriptiuon of the
1058: language itself. This is suitable for use in e.g.
1059: &Apache::edit::select_arg (once dereferenced that is).
1060:
1061: =cut
1062:
1063: sub list_languages {
1064: my @lang_choices;
1065:
1066: foreach my $id (&languageids()) {
1067: my $code = &supportedlanguagecode($id);
1068: if ($code) {
1069: my $selector = $supported_codes{$id};
1070: my $description = &plainlanguagedescription($id);
1071: push(@lang_choices, [$selector, $description]);
1072: }
1073: }
1074: return \@lang_choices;
1075: }
1076:
1077: =pod
1078:
1079: =item * &linked_select_forms(...)
1080:
1081: linked_select_forms returns a string containing a <script></script> block
1082: and html for two <select> menus. The select menus will be linked in that
1083: changing the value of the first menu will result in new values being placed
1084: in the second menu. The values in the select menu will appear in alphabetical
1085: order unless a defined order is provided.
1086:
1087: linked_select_forms takes the following ordered inputs:
1088:
1089: =over 4
1090:
1091: =item * $formname, the name of the <form> tag
1092:
1093: =item * $middletext, the text which appears between the <select> tags
1094:
1095: =item * $firstdefault, the default value for the first menu
1096:
1097: =item * $firstselectname, the name of the first <select> tag
1098:
1099: =item * $secondselectname, the name of the second <select> tag
1100:
1101: =item * $hashref, a reference to a hash containing the data for the menus.
1102:
1103: =item * $menuorder, the order of values in the first menu
1104:
1105: =item * $onchangefirst, additional javascript call to execute for an onchange
1106: event for the first <select> tag
1107:
1108: =item * $onchangesecond, additional javascript call to execute for an onchange
1109: event for the second <select> tag
1110:
1111: =item * $suffix, to differentiate separate uses of select2data javascript
1112: objects in a page.
1113:
1114: =back
1115:
1116: Below is an example of such a hash. Only the 'text', 'default', and
1117: 'select2' keys must appear as stated. keys(%menu) are the possible
1118: values for the first select menu. The text that coincides with the
1119: first menu value is given in $menu{$choice1}->{'text'}. The values
1120: and text for the second menu are given in the hash pointed to by
1121: $menu{$choice1}->{'select2'}.
1122:
1123: my %menu = ( A1 => { text =>"Choice A1" ,
1124: default => "B3",
1125: select2 => {
1126: B1 => "Choice B1",
1127: B2 => "Choice B2",
1128: B3 => "Choice B3",
1129: B4 => "Choice B4"
1130: },
1131: order => ['B4','B3','B1','B2'],
1132: },
1133: A2 => { text =>"Choice A2" ,
1134: default => "C2",
1135: select2 => {
1136: C1 => "Choice C1",
1137: C2 => "Choice C2",
1138: C3 => "Choice C3"
1139: },
1140: order => ['C2','C1','C3'],
1141: },
1142: A3 => { text =>"Choice A3" ,
1143: default => "D6",
1144: select2 => {
1145: D1 => "Choice D1",
1146: D2 => "Choice D2",
1147: D3 => "Choice D3",
1148: D4 => "Choice D4",
1149: D5 => "Choice D5",
1150: D6 => "Choice D6",
1151: D7 => "Choice D7"
1152: },
1153: order => ['D4','D3','D2','D1','D7','D6','D5'],
1154: }
1155: );
1156:
1157: =cut
1158:
1159: sub linked_select_forms {
1160: my ($formname,
1161: $middletext,
1162: $firstdefault,
1163: $firstselectname,
1164: $secondselectname,
1165: $hashref,
1166: $menuorder,
1167: $onchangefirst,
1168: $onchangesecond,
1169: $suffix
1170: ) = @_;
1171: my $second = "document.$formname.$secondselectname";
1172: my $first = "document.$formname.$firstselectname";
1173: # output the javascript to do the changing
1174: my $result = '';
1175: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1176: $result.="// <![CDATA[\n";
1177: $result.="var select2data${suffix} = new Object();\n";
1178: $" = '","';
1179: my $debug = '';
1180: foreach my $s1 (sort(keys(%$hashref))) {
1181: $result.="select2data${suffix}['d_$s1'] = new Object();\n";
1182: $result.="select2data${suffix}['d_$s1'].def = new String('".
1183: $hashref->{$s1}->{'default'}."');\n";
1184: $result.="select2data${suffix}['d_$s1'].values = new Array(";
1185: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1186: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1187: @s2values = @{$hashref->{$s1}->{'order'}};
1188: }
1189: $result.="\"@s2values\");\n";
1190: $result.="select2data${suffix}['d_$s1'].texts = new Array(";
1191: my @s2texts;
1192: foreach my $value (@s2values) {
1193: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1194: }
1195: $result.="\"@s2texts\");\n";
1196: }
1197: $"=' ';
1198: $result.= <<"END";
1199:
1200: function select1${suffix}_changed() {
1201: // Determine new choice
1202: var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1203: // update select2
1204: var values = select2data${suffix}[newvalue].values;
1205: var texts = select2data${suffix}[newvalue].texts;
1206: var select2def = select2data${suffix}[newvalue].def;
1207: var i;
1208: // out with the old
1209: $second.options.length = 0;
1210: // in with the new
1211: for (i=0;i<values.length; i++) {
1212: $second.options[i] = new Option(values[i]);
1213: $second.options[i].value = values[i];
1214: $second.options[i].text = texts[i];
1215: if (values[i] == select2def) {
1216: $second.options[i].selected = true;
1217: }
1218: }
1219: }
1220: // ]]>
1221: </script>
1222: END
1223: # output the initial values for the selection lists
1224: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1225: my @order = sort(keys(%{$hashref}));
1226: if (ref($menuorder) eq 'ARRAY') {
1227: @order = @{$menuorder};
1228: }
1229: foreach my $value (@order) {
1230: $result.=" <option value=\"$value\" ";
1231: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1232: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1233: }
1234: $result .= "</select>\n";
1235: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1236: $result .= $middletext;
1237: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1238: if ($onchangesecond) {
1239: $result .= ' onchange="'.$onchangesecond.'"';
1240: }
1241: $result .= ">\n";
1242: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1243:
1244: my @secondorder = sort(keys(%select2));
1245: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1246: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1247: }
1248: foreach my $value (@secondorder) {
1249: $result.=" <option value=\"$value\" ";
1250: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1251: $result.=">".&mt($select2{$value})."</option>\n";
1252: }
1253: $result .= "</select>\n";
1254: # return $debug;
1255: return $result;
1256: } # end of sub linked_select_forms {
1257:
1258: =pod
1259:
1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1261:
1262: Returns a string corresponding to an HTML link to the given help
1263: $topic, where $topic corresponds to the name of a .tex file in
1264: /home/httpd/html/adm/help/tex, with underscores replaced by
1265: spaces.
1266:
1267: $text will optionally be linked to the same topic, allowing you to
1268: link text in addition to the graphic. If you do not want to link
1269: text, but wish to specify one of the later parameters, pass an
1270: empty string.
1271:
1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
1273: the link will not open a new window. If false, the link will open
1274: a new window using Javascript. (Default is false.)
1275:
1276: $width and $height are optional numerical parameters that will
1277: override the width and height of the popped up window, which may
1278: be useful for certain help topics with big pictures included.
1279:
1280: $imgid is the id of the img tag used for the help icon. This may be
1281: used in a javascript call to switch the image src. See
1282: lonhtmlcommon::htmlareaselectactive() for an example.
1283:
1284: $links_target will optionally be set to a target (_top, _parent or _self).
1285:
1286: =cut
1287:
1288: sub help_open_topic {
1289: my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1290: $text = "" if (not defined $text);
1291: $stayOnPage = 0 if (not defined $stayOnPage);
1292: $width = 500 if (not defined $width);
1293: $height = 400 if (not defined $height);
1294: my $filename = $topic;
1295: $filename =~ s/ /_/g;
1296:
1297: my $template = "";
1298: my $link;
1299:
1300: $topic=~s/\W/\_/g;
1301:
1302: if (!$stayOnPage) {
1303: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1304: } elsif ($stayOnPage eq 'popup') {
1305: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1306: } else {
1307: $link = "/adm/help/${filename}.hlp";
1308: }
1309:
1310: # Add the text
1311: my $target = ' target="_top"';
1312: if ($links_target) {
1313: $target = ' target="'.$links_target.'"';
1314: } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1315: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1316: $target = '';
1317: }
1318: if ($text ne "") {
1319: $template.='<span class="LC_help_open_topic">'
1320: .'<a'.$target.' href="'.$link.'">'
1321: .$text.'</a>';
1322: }
1323:
1324: # (Always) Add the graphic
1325: my $title = &mt('Online Help');
1326: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1327: if ($imgid ne '') {
1328: $imgid = ' id="'.$imgid.'"';
1329: }
1330: $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1331: .'<img src="'.$helpicon.'" border="0"'
1332: .' alt="'.&mt('Help: [_1]',$topic).'"'
1333: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1334: .' /></a>';
1335: if ($text ne "") {
1336: $template.='</span>';
1337: }
1338: return $template;
1339:
1340: }
1341:
1342: # This is a quicky function for Latex cheatsheet editing, since it
1343: # appears in at least four places
1344: sub helpLatexCheatsheet {
1345: my ($topic,$text,$not_author,$stayOnPage) = @_;
1346: my $out;
1347: my $addOther = '';
1348: if ($topic) {
1349: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1350: }
1351: $out = '<span>' # Start cheatsheet
1352: .$addOther
1353: .'<span>'
1354: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1355: .'</span> <span>'
1356: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1357: .'</span>';
1358: unless ($not_author) {
1359: $out .= '<span>'
1360: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1361: .'</span> <span>'
1362: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1363: .'</span>';
1364: }
1365: $out .= '</span>'; # End cheatsheet
1366: return $out;
1367: }
1368:
1369: sub general_help {
1370: my $helptopic='Student_Intro';
1371: if ($env{'request.role'}=~/^(ca|au)/) {
1372: $helptopic='Authoring_Intro';
1373: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1374: $helptopic='Course_Coordination_Intro';
1375: } elsif ($env{'request.role'}=~/^dc/) {
1376: $helptopic='Domain_Coordination_Intro';
1377: }
1378: return $helptopic;
1379: }
1380:
1381: sub update_help_link {
1382: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1383: my $origurl = $ENV{'REQUEST_URI'};
1384: $origurl=~s|^/~|/priv/|;
1385: my $timestamp = time;
1386: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1387: $$datum = &escape($$datum);
1388: }
1389:
1390: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1391: my $output .= <<"ENDOUTPUT";
1392: <script type="text/javascript">
1393: // <![CDATA[
1394: banner_link = '$banner_link';
1395: // ]]>
1396: </script>
1397: ENDOUTPUT
1398: return $output;
1399: }
1400:
1401: # now just updates the help link and generates a blue icon
1402: sub help_open_menu {
1403: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target)
1404: = @_;
1405: $stayOnPage = 1;
1406: my $output;
1407: if ($component_help) {
1408: if (!$text) {
1409: $output=&help_open_topic($component_help,undef,$stayOnPage,
1410: $width,$height,'',$links_target);
1411: } else {
1412: my $help_text;
1413: $help_text=&unescape($topic);
1414: $output='<table><tr><td>'.
1415: &help_open_topic($component_help,$help_text,$stayOnPage,
1416: $width,$height,'',$links_target).'</td></tr></table>';
1417: }
1418: }
1419: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1420: return $output.$banner_link;
1421: }
1422:
1423: sub top_nav_help {
1424: my ($text,$linkattr) = @_;
1425: $text = &mt($text);
1426: my $stay_on_page = 1;
1427:
1428: my ($link,$banner_link);
1429: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1430: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1431: : "javascript:helpMenu('open')";
1432: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1433: }
1434: my $title = &mt('Get help');
1435: if ($link) {
1436: return <<"END";
1437: $banner_link
1438: <a href="$link" title="$title" $linkattr>$text</a>
1439: END
1440: } else {
1441: return ' '.$text.' ';
1442: }
1443: }
1444:
1445: sub help_menu_js {
1446: my ($httphost) = @_;
1447: my $stayOnPage = 1;
1448: my $width = 620;
1449: my $height = 600;
1450: my $helptopic=&general_help();
1451: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1452: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1453: my $start_page =
1454: &Apache::loncommon::start_page('Help Menu', undef,
1455: {'frameset' => 1,
1456: 'js_ready' => 1,
1457: 'use_absolute' => $httphost,
1458: 'add_entries' => {
1459: 'border' => '0',
1460: 'rows' => "110,*",},});
1461: my $end_page =
1462: &Apache::loncommon::end_page({'frameset' => 1,
1463: 'js_ready' => 1,});
1464:
1465: my $template .= <<"ENDTEMPLATE";
1466: <script type="text/javascript">
1467: // <![CDATA[
1468: // <!-- BEGIN LON-CAPA Internal
1469: var banner_link = '';
1470: function helpMenu(target) {
1471: var caller = this;
1472: if (target == 'open') {
1473: var newWindow = null;
1474: try {
1475: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1476: }
1477: catch(error) {
1478: writeHelp(caller);
1479: return;
1480: }
1481: if (newWindow) {
1482: caller = newWindow;
1483: }
1484: }
1485: writeHelp(caller);
1486: return;
1487: }
1488: function writeHelp(caller) {
1489: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1490: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1491: caller.document.close();
1492: caller.focus();
1493: }
1494: // END LON-CAPA Internal -->
1495: // ]]>
1496: </script>
1497: ENDTEMPLATE
1498: return $template;
1499: }
1500:
1501: sub help_open_bug {
1502: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1503: unless ($env{'user.adv'}) { return ''; }
1504: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1505: $text = "" if (not defined $text);
1506: $stayOnPage=1;
1507: $width = 600 if (not defined $width);
1508: $height = 600 if (not defined $height);
1509:
1510: $topic=~s/\W+/\+/g;
1511: my $link='';
1512: my $template='';
1513: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1514: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1515: if (!$stayOnPage)
1516: {
1517: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1518: }
1519: else
1520: {
1521: $link = $url;
1522: }
1523:
1524: my $target = ' target="_top"';
1525: if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1526: $target = '';
1527: }
1528: if (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1529: $target = ' target="'.$env{'request.deeplink.target'}.'"';
1530: }
1531: # Add the text
1532: if ($text ne "")
1533: {
1534: $template .=
1535: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1536: "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1537: }
1538:
1539: # Add the graphic
1540: my $title = &mt('Report a Bug');
1541: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1542: $template .= <<"ENDTEMPLATE";
1543: <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1544: ENDTEMPLATE
1545: if ($text ne '') { $template.='</td></tr></table>' };
1546: return $template;
1547:
1548: }
1549:
1550: sub help_open_faq {
1551: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1552: unless ($env{'user.adv'}) { return ''; }
1553: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1554: $text = "" if (not defined $text);
1555: $stayOnPage=1;
1556: $width = 350 if (not defined $width);
1557: $height = 400 if (not defined $height);
1558:
1559: $topic=~s/\W+/\+/g;
1560: my $link='';
1561: my $template='';
1562: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1563: if (!$stayOnPage)
1564: {
1565: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1566: }
1567: else
1568: {
1569: $link = $url;
1570: }
1571:
1572: # Add the text
1573: if ($text ne "")
1574: {
1575: $template .=
1576: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1577: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1578: }
1579:
1580: # Add the graphic
1581: my $title = &mt('View the FAQ');
1582: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1583: $template .= <<"ENDTEMPLATE";
1584: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1585: ENDTEMPLATE
1586: if ($text ne '') { $template.='</td></tr></table>' };
1587: return $template;
1588:
1589: }
1590:
1591: ###############################################################
1592: ###############################################################
1593:
1594: =pod
1595:
1596: =item * &change_content_javascript():
1597:
1598: This and the next function allow you to create small sections of an
1599: otherwise static HTML page that you can update on the fly with
1600: Javascript, even in Netscape 4.
1601:
1602: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1603: must be written to the HTML page once. It will prove the Javascript
1604: function "change(name, content)". Calling the change function with the
1605: name of the section
1606: you want to update, matching the name passed to C<changable_area>, and
1607: the new content you want to put in there, will put the content into
1608: that area.
1609:
1610: B<Note>: Netscape 4 only reserves enough space for the changable area
1611: to contain room for the original contents. You need to "make space"
1612: for whatever changes you wish to make, and be B<sure> to check your
1613: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1614: it's adequate for updating a one-line status display, but little more.
1615: This script will set the space to 100% width, so you only need to
1616: worry about height in Netscape 4.
1617:
1618: Modern browsers are much less limiting, and if you can commit to the
1619: user not using Netscape 4, this feature may be used freely with
1620: pretty much any HTML.
1621:
1622: =cut
1623:
1624: sub change_content_javascript {
1625: # If we're on Netscape 4, we need to use Layer-based code
1626: if ($env{'browser.type'} eq 'netscape' &&
1627: $env{'browser.version'} =~ /^4\./) {
1628: return (<<NETSCAPE4);
1629: function change(name, content) {
1630: doc = document.layers[name+"___escape"].layers[0].document;
1631: doc.open();
1632: doc.write(content);
1633: doc.close();
1634: }
1635: NETSCAPE4
1636: } else {
1637: # Otherwise, we need to use semi-standards-compliant code
1638: # (technically, "innerHTML" isn't standard but the equivalent
1639: # is really scary, and every useful browser supports it
1640: return (<<DOMBASED);
1641: function change(name, content) {
1642: element = document.getElementById(name);
1643: element.innerHTML = content;
1644: }
1645: DOMBASED
1646: }
1647: }
1648:
1649: =pod
1650:
1651: =item * &changable_area($name,$origContent):
1652:
1653: This provides a "changable area" that can be modified on the fly via
1654: the Javascript code provided in C<change_content_javascript>. $name is
1655: the name you will use to reference the area later; do not repeat the
1656: same name on a given HTML page more then once. $origContent is what
1657: the area will originally contain, which can be left blank.
1658:
1659: =cut
1660:
1661: sub changable_area {
1662: my ($name, $origContent) = @_;
1663:
1664: if ($env{'browser.type'} eq 'netscape' &&
1665: $env{'browser.version'} =~ /^4\./) {
1666: # If this is netscape 4, we need to use the Layer tag
1667: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1668: } else {
1669: return "<span id='$name'>$origContent</span>";
1670: }
1671: }
1672:
1673: =pod
1674:
1675: =item * &viewport_geometry_js
1676:
1677: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1678:
1679: =cut
1680:
1681:
1682: sub viewport_geometry_js {
1683: return <<"GEOMETRY";
1684: var Geometry = {};
1685: function init_geometry() {
1686: if (Geometry.init) { return };
1687: Geometry.init=1;
1688: if (window.innerHeight) {
1689: Geometry.getViewportHeight = function() { return window.innerHeight; };
1690: Geometry.getViewportWidth = function() { return window.innerWidth; };
1691: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1692: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1693: }
1694: else if (document.documentElement && document.documentElement.clientHeight) {
1695: Geometry.getViewportHeight =
1696: function() { return document.documentElement.clientHeight; };
1697: Geometry.getViewportWidth =
1698: function() { return document.documentElement.clientWidth; };
1699:
1700: Geometry.getHorizontalScroll =
1701: function() { return document.documentElement.scrollLeft; };
1702: Geometry.getVerticalScroll =
1703: function() { return document.documentElement.scrollTop; };
1704: }
1705: else if (document.body.clientHeight) {
1706: Geometry.getViewportHeight =
1707: function() { return document.body.clientHeight; };
1708: Geometry.getViewportWidth =
1709: function() { return document.body.clientWidth; };
1710: Geometry.getHorizontalScroll =
1711: function() { return document.body.scrollLeft; };
1712: Geometry.getVerticalScroll =
1713: function() { return document.body.scrollTop; };
1714: }
1715: }
1716:
1717: GEOMETRY
1718: }
1719:
1720: =pod
1721:
1722: =item * &viewport_size_js()
1723:
1724: 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.
1725:
1726: =cut
1727:
1728: sub viewport_size_js {
1729: my $geometry = &viewport_geometry_js();
1730: return <<"DIMS";
1731:
1732: $geometry
1733:
1734: function getViewportDims(width,height) {
1735: init_geometry();
1736: width.value = Geometry.getViewportWidth();
1737: height.value = Geometry.getViewportHeight();
1738: return;
1739: }
1740:
1741: DIMS
1742: }
1743:
1744: =pod
1745:
1746: =item * &resize_textarea_js()
1747:
1748: emits the needed javascript to resize a textarea to be as big as possible
1749:
1750: creates a function resize_textrea that takes two IDs first should be
1751: the id of the element to resize, second should be the id of a div that
1752: surrounds everything that comes after the textarea, this routine needs
1753: to be attached to the <body> for the onload and onresize events.
1754:
1755: =back
1756:
1757: =cut
1758:
1759: sub resize_textarea_js {
1760: my $geometry = &viewport_geometry_js();
1761: return <<"RESIZE";
1762: <script type="text/javascript">
1763: // <![CDATA[
1764: $geometry
1765:
1766: function getX(element) {
1767: var x = 0;
1768: while (element) {
1769: x += element.offsetLeft;
1770: element = element.offsetParent;
1771: }
1772: return x;
1773: }
1774: function getY(element) {
1775: var y = 0;
1776: while (element) {
1777: y += element.offsetTop;
1778: element = element.offsetParent;
1779: }
1780: return y;
1781: }
1782:
1783:
1784: function resize_textarea(textarea_id,bottom_id) {
1785: init_geometry();
1786: var textarea = document.getElementById(textarea_id);
1787: //alert(textarea);
1788:
1789: var textarea_top = getY(textarea);
1790: var textarea_height = textarea.offsetHeight;
1791: var bottom = document.getElementById(bottom_id);
1792: var bottom_top = getY(bottom);
1793: var bottom_height = bottom.offsetHeight;
1794: var window_height = Geometry.getViewportHeight();
1795: var fudge = 23;
1796: var new_height = window_height-fudge-textarea_top-bottom_height;
1797: if (new_height < 300) {
1798: new_height = 300;
1799: }
1800: textarea.style.height=new_height+'px';
1801: }
1802: // ]]>
1803: </script>
1804: RESIZE
1805:
1806: }
1807:
1808: sub colorfuleditor_js {
1809: my $browse_or_search;
1810: my $respath;
1811: my ($cnum,$cdom) = &crsauthor_url();
1812: if ($cnum) {
1813: $respath = "/res/$cdom/$cnum/";
1814: my %js_lt = &Apache::lonlocal::texthash(
1815: sunm => 'Sub-directory name',
1816: save => 'Save page to make this permanent',
1817: );
1818: &js_escape(\%js_lt);
1819: $browse_or_search = <<"END";
1820:
1821: function toggleChooser(form,element,titleid,only,search) {
1822: var disp = 'none';
1823: if (document.getElementById('chooser_'+element)) {
1824: var curr = document.getElementById('chooser_'+element).style.display;
1825: if (curr == 'none') {
1826: disp='inline';
1827: if (form.elements['chooser_'+element].length) {
1828: for (var i=0; i<form.elements['chooser_'+element].length; i++) {
1829: form.elements['chooser_'+element][i].checked = false;
1830: }
1831: }
1832: toggleResImport(form,element);
1833: }
1834: document.getElementById('chooser_'+element).style.display = disp;
1835: }
1836: }
1837:
1838: function toggleCrsFile(form,element,numdirs) {
1839: if (document.getElementById('chooser_'+element+'_crsres')) {
1840: var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
1841: if (curr == 'none') {
1842: if (numdirs) {
1843: form.elements['coursepath_'+element].selectedIndex = 0;
1844: if (numdirs > 1) {
1845: window['select1'+element+'_changed']();
1846: }
1847: }
1848: }
1849: document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
1850:
1851: }
1852: if (document.getElementById('chooser_'+element+'_upload')) {
1853: document.getElementById('chooser_'+element+'_upload').style.display = 'none';
1854: if (document.getElementById('uploadcrsres_'+element)) {
1855: document.getElementById('uploadcrsres_'+element).value = '';
1856: }
1857: }
1858: return;
1859: }
1860:
1861: function toggleCrsUpload(form,element,numcrsdirs) {
1862: if (document.getElementById('chooser_'+element+'_crsres')) {
1863: document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
1864: }
1865: if (document.getElementById('chooser_'+element+'_upload')) {
1866: var curr = document.getElementById('chooser_'+element+'_upload').style.display;
1867: if (curr == 'none') {
1868: if (numcrsdirs) {
1869: form.elements['crsauthorpath_'+element].selectedIndex = 0;
1870: form.elements['newsubdir_'+element][0].checked = true;
1871: toggleNewsubdir(form,element);
1872: }
1873: }
1874: document.getElementById('chooser_'+element+'_upload').style.display = 'block';
1875: }
1876: return;
1877: }
1878:
1879: function toggleResImport(form,element) {
1880: var choices = new Array('crsres','upload');
1881: for (var i=0; i<choices.length; i++) {
1882: if (document.getElementById('chooser_'+element+'_'+choices[i])) {
1883: document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
1884: }
1885: }
1886: }
1887:
1888: function toggleNewsubdir(form,element) {
1889: var newsub = form.elements['newsubdir_'+element];
1890: if (newsub) {
1891: if (newsub.length) {
1892: for (var j=0; j<newsub.length; j++) {
1893: if (newsub[j].checked) {
1894: if (document.getElementById('newsubdirname_'+element)) {
1895: if (newsub[j].value == '1') {
1896: document.getElementById('newsubdirname_'+element).type = "text";
1897: if (document.getElementById('newsubdir_'+element)) {
1898: document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
1899: }
1900: } else {
1901: document.getElementById('newsubdirname_'+element).type = "hidden";
1902: document.getElementById('newsubdirname_'+element).value = "";
1903: document.getElementById('newsubdir_'+element).innerHTML = "";
1904: }
1905: }
1906: break;
1907: }
1908: }
1909: }
1910: }
1911: }
1912:
1913: function updateCrsFile(form,element) {
1914: var directory = form.elements['coursepath_'+element];
1915: var filename = form.elements['coursefile_'+element];
1916: var path = directory.options[directory.selectedIndex].value;
1917: var file = filename.options[filename.selectedIndex].value;
1918: form.elements[element].value = '$respath';
1919: if (path == '/') {
1920: form.elements[element].value += file;
1921: } else {
1922: form.elements[element].value += path+'/'+file;
1923: }
1924: unClean();
1925: if (document.getElementById('previewimg_'+element)) {
1926: document.getElementById('previewimg_'+element).src = form.elements[element].value;
1927: var newsrc = document.getElementById('previewimg_'+element).src;
1928: }
1929: if (document.getElementById('showimg_'+element)) {
1930: document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
1931: }
1932: toggleChooser(form,element);
1933: return;
1934: }
1935:
1936: function uploadDone(suffix,name) {
1937: if (name) {
1938: document.forms["lonhomework"].elements[suffix].value = name;
1939: unClean();
1940: toggleChooser(document.forms["lonhomework"],suffix);
1941: }
1942: }
1943:
1944: \$(document).ready(function(){
1945:
1946: \$(document).delegate('form :submit', 'click', function( event ) {
1947: if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
1948: var buttonId = this.id;
1949: var suffix = buttonId.toString();
1950: suffix = suffix.replace(/^crsupload_/,'');
1951: event.preventDefault();
1952: document.lonhomework.target = 'crsupload_target_'+suffix;
1953: document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
1954: \$(this.form).submit();
1955: document.lonhomework.target = '';
1956: if (document.getElementById('crsuploadto_'+suffix)) {
1957: document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
1958: }
1959: return false;
1960: }
1961: });
1962: });
1963: END
1964: }
1965: return <<"COLORFULEDIT"
1966: <script type="text/javascript">
1967: // <![CDATA[>
1968: function fold_box(curDepth, lastresource){
1969:
1970: // we need a list because there can be several blocks you need to fold in one tag
1971: var block = document.getElementsByName('foldblock_'+curDepth);
1972: // but there is only one folding button per tag
1973: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1974:
1975: if(block.item(0).style.display == 'none'){
1976:
1977: foldbutton.value = '@{[&mt("Hide")]}';
1978: for (i = 0; i < block.length; i++){
1979: block.item(i).style.display = '';
1980: }
1981: }else{
1982:
1983: foldbutton.value = '@{[&mt("Show")]}';
1984: for (i = 0; i < block.length; i++){
1985: // block.item(i).style.visibility = 'collapse';
1986: block.item(i).style.display = 'none';
1987: }
1988: };
1989: saveState(lastresource);
1990: }
1991:
1992: function saveState (lastresource) {
1993:
1994: var tag_list = getTagList();
1995: if(tag_list != null){
1996: var timestamp = new Date().getTime();
1997: var key = lastresource;
1998:
1999: // the value pattern is: 'time;key1,value1;key2,value2; ... '
2000: // starting with timestamp
2001: var value = timestamp+';';
2002:
2003: // building the list of key-value pairs
2004: for(var i = 0; i < tag_list.length; i++){
2005: value += tag_list[i]+',';
2006: value += document.getElementsByName(tag_list[i])[0].style.display+';';
2007: }
2008:
2009: // only iterate whole storage if nothing to override
2010: if(localStorage.getItem(key) == null){
2011:
2012: // prevent storage from growing large
2013: if(localStorage.length > 50){
2014: var regex_getTimestamp = /^(?:\d)+;/;
2015: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
2016: var oldest_key;
2017:
2018: for(var i = 1; i < localStorage.length; i++){
2019: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
2020: oldest_key = localStorage.key(i);
2021: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
2022: }
2023: }
2024: localStorage.removeItem(oldest_key);
2025: }
2026: }
2027: localStorage.setItem(key,value);
2028: }
2029: }
2030:
2031: // restore folding status of blocks (on page load)
2032: function restoreState (lastresource) {
2033: if(localStorage.getItem(lastresource) != null){
2034: var key = lastresource;
2035: var value = localStorage.getItem(key);
2036: var regex_delTimestamp = /^\d+;/;
2037:
2038: value.replace(regex_delTimestamp, '');
2039:
2040: var valueArr = value.split(';');
2041: var pairs;
2042: var elements;
2043: for (var i = 0; i < valueArr.length; i++){
2044: pairs = valueArr[i].split(',');
2045: elements = document.getElementsByName(pairs[0]);
2046:
2047: for (var j = 0; j < elements.length; j++){
2048: elements[j].style.display = pairs[1];
2049: if (pairs[1] == "none"){
2050: var regex_id = /([_\\d]+)\$/;
2051: regex_id.exec(pairs[0]);
2052: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
2053: }
2054: }
2055: }
2056: }
2057: }
2058:
2059: function getTagList () {
2060:
2061: var stringToSearch = document.lonhomework.innerHTML;
2062:
2063: var ret = new Array();
2064: var regex_findBlock = /(foldblock_.*?)"/g;
2065: var tag_list = stringToSearch.match(regex_findBlock);
2066:
2067: if(tag_list != null){
2068: for(var i = 0; i < tag_list.length; i++){
2069: ret.push(tag_list[i].replace(/"/, ''));
2070: }
2071: }
2072: return ret;
2073: }
2074:
2075: function saveScrollPosition (resource) {
2076: var tag_list = getTagList();
2077:
2078: // we dont always want to jump to the first block
2079: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
2080: if(\$(window).scrollTop() > 170){
2081: if(tag_list != null){
2082: var result;
2083: for(var i = 0; i < tag_list.length; i++){
2084: if(isElementInViewport(tag_list[i])){
2085: result += tag_list[i]+';';
2086: }
2087: }
2088: sessionStorage.setItem('anchor_'+resource, result);
2089: }
2090: } else {
2091: // we dont need to save zero, just delete the item to leave everything tidy
2092: sessionStorage.removeItem('anchor_'+resource);
2093: }
2094: }
2095:
2096: function restoreScrollPosition(resource){
2097:
2098: var elem = sessionStorage.getItem('anchor_'+resource);
2099: if(elem != null){
2100: var tag_list = elem.split(';');
2101: var elem_list;
2102:
2103: for(var i = 0; i < tag_list.length; i++){
2104: elem_list = document.getElementsByName(tag_list[i]);
2105:
2106: if(elem_list.length > 0){
2107: elem = elem_list[0];
2108: break;
2109: }
2110: }
2111: elem.scrollIntoView();
2112: }
2113: }
2114:
2115: function isElementInViewport(el) {
2116:
2117: // change to last element instead of first
2118: var elem = document.getElementsByName(el);
2119: var rect = elem[0].getBoundingClientRect();
2120:
2121: return (
2122: rect.top >= 0 &&
2123: rect.left >= 0 &&
2124: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
2125: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
2126: );
2127: }
2128:
2129: function autosize(depth){
2130: var cmInst = window['cm'+depth];
2131: var fitsizeButton = document.getElementById('fitsize'+depth);
2132:
2133: // is fixed size, switching to dynamic
2134: if (sessionStorage.getItem("autosized_"+depth) == null) {
2135: cmInst.setSize("","auto");
2136: fitsizeButton.value = "@{[&mt('Fixed size')]}";
2137: sessionStorage.setItem("autosized_"+depth, "yes");
2138:
2139: // is dynamic size, switching to fixed
2140: } else {
2141: cmInst.setSize("","300px");
2142: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
2143: sessionStorage.removeItem("autosized_"+depth);
2144: }
2145: }
2146:
2147: $browse_or_search
2148:
2149: // ]]>
2150: </script>
2151: COLORFULEDIT
2152: }
2153:
2154: sub xmleditor_js {
2155: return <<XMLEDIT
2156: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
2157: <script type="text/javascript">
2158: // <![CDATA[>
2159:
2160: function saveScrollPosition (resource) {
2161:
2162: var scrollPos = \$(window).scrollTop();
2163: sessionStorage.setItem(resource,scrollPos);
2164: }
2165:
2166: function restoreScrollPosition(resource){
2167:
2168: var scrollPos = sessionStorage.getItem(resource);
2169: \$(window).scrollTop(scrollPos);
2170: }
2171:
2172: // unless internet explorer
2173: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
2174:
2175: \$(document).ready(function() {
2176: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
2177: });
2178: }
2179:
2180: // inserts text at cursor position into codemirror (xml editor only)
2181: function insertText(text){
2182: cm.focus();
2183: var curPos = cm.getCursor();
2184: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2185: }
2186: // ]]>
2187: </script>
2188: XMLEDIT
2189: }
2190:
2191: sub insert_folding_button {
2192: my $curDepth = $Apache::lonxml::curdepth;
2193: my $lastresource = $env{'request.ambiguous'};
2194:
2195: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2196: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2197: }
2198:
2199: sub crsauthor_url {
2200: my ($url) = @_;
2201: if ($url eq '') {
2202: $url = $ENV{'REQUEST_URI'};
2203: }
2204: my ($cnum,$cdom);
2205: if ($env{'request.course.id'}) {
2206: my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
2207: if ($audom ne '' && $auname ne '') {
2208: if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
2209: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
2210: $cnum = $auname;
2211: $cdom = $audom;
2212: }
2213: }
2214: }
2215: return ($cnum,$cdom);
2216: }
2217:
2218: sub import_crsauthor_form {
2219: my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
2220: return (0) unless ($env{'request.course.id'});
2221: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2222: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2223: my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
2224: return (0) unless (($cnum ne '') && ($cdom ne ''));
2225: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
2226: my @ids=&Apache::lonnet::current_machine_ids();
2227: my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
2228:
2229: if (grep(/^\Q$crshome\E$/,@ids)) {
2230: $is_home = 1;
2231: }
2232: $relpath = "/priv/$cdom/$cnum";
2233: &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
2234: my %lt = &Apache::lonlocal::texthash (
2235: fnam => 'Filename',
2236: dire => 'Directory',
2237: );
2238: my $numdirs = scalar(keys(%files));
2239: my (%possexts,$singledir,@singledirfiles);
2240: if ($only) {
2241: map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
2242: }
2243: my (%nonemptydirs,$possdirs);
2244: if ($numdirs > 1) {
2245: my @order;
2246: foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
2247: if (ref($files{$key}) eq 'HASH') {
2248: my $shown = $key;
2249: if ($key eq '') {
2250: $shown = '/';
2251: }
2252: my @ordered = ();
2253: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
2254: next if ($file =~ /\.rights$/);
2255: if ($only) {
2256: my ($ext) = ($file =~ /\.([^.]+)$/);
2257: unless ($possexts{lc($ext)}) {
2258: next;
2259: }
2260: }
2261: $selimport_menus{$key}->{'select2'}->{$file} = $file;
2262: push(@ordered,$file);
2263: }
2264: if (@ordered) {
2265: push(@order,$key);
2266: $nonemptydirs{$key} = 1;
2267: $selimport_menus{$key}->{'text'} = $shown;
2268: $selimport_menus{$key}->{'default'} = '';
2269: $selimport_menus{$key}->{'select2'}->{''} = '';
2270: $selimport_menus{$key}->{'order'} = \@ordered;
2271: }
2272: }
2273: }
2274: $possdirs = scalar(keys(%nonemptydirs));
2275: if ($possdirs > 1) {
2276: my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
2277: $output = $lt{'dire'}.
2278: &linked_select_forms($form,'<br />'.
2279: $lt{'fnam'},'',
2280: $firstselectname,$secondselectname,
2281: \%selimport_menus,\@order,
2282: $onchangefirst,'',$suffix).'<br />';
2283: } elsif ($possdirs == 1) {
2284: $singledir = (keys(%nonemptydirs))[0];
2285: if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
2286: @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
2287: }
2288: delete($selimport_menus{$singledir});
2289: }
2290: } elsif ($numdirs == 1) {
2291: $singledir = (keys(%files))[0];
2292: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
2293: if ($only) {
2294: my ($ext) = ($file =~ /\.([^.]+)$/);
2295: unless ($possexts{lc($ext)}) {
2296: next;
2297: }
2298: } else {
2299: next if ($file =~ /\.rights$/);
2300: }
2301: push(@singledirfiles,$file);
2302: }
2303: if (@singledirfiles) {
2304: $possdirs = 1;
2305: }
2306: }
2307: if (($possdirs == 1) && (@singledirfiles)) {
2308: my $showdir = $singledir;
2309: if ($singledir eq '') {
2310: $showdir = '/';
2311: }
2312: $output = $lt{'dire'}.
2313: '<select name="'.$firstselectname.'">'.
2314: '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
2315: '</select><br />'.
2316: $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
2317: '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
2318: foreach my $file (@singledirfiles) {
2319: $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
2320: }
2321: $output .= '</select><br />'."\n";
2322: }
2323: return ($possdirs,$output);
2324: }
2325:
2326: =pod
2327:
2328: =head1 Excel and CSV file utility routines
2329:
2330: =cut
2331:
2332: ###############################################################
2333: ###############################################################
2334:
2335: =pod
2336:
2337: =over 4
2338:
2339: =item * &csv_translate($text)
2340:
2341: Translate $text to allow it to be output as a 'comma separated values'
2342: format.
2343:
2344: =cut
2345:
2346: ###############################################################
2347: ###############################################################
2348: sub csv_translate {
2349: my $text = shift;
2350: $text =~ s/\"/\"\"/g;
2351: $text =~ s/\n/ /g;
2352: return $text;
2353: }
2354:
2355: ###############################################################
2356: ###############################################################
2357:
2358: =pod
2359:
2360: =item * &define_excel_formats()
2361:
2362: Define some commonly used Excel cell formats.
2363:
2364: Currently supported formats:
2365:
2366: =over 4
2367:
2368: =item header
2369:
2370: =item bold
2371:
2372: =item h1
2373:
2374: =item h2
2375:
2376: =item h3
2377:
2378: =item h4
2379:
2380: =item i
2381:
2382: =item date
2383:
2384: =back
2385:
2386: Inputs: $workbook
2387:
2388: Returns: $format, a hash reference.
2389:
2390:
2391: =cut
2392:
2393: ###############################################################
2394: ###############################################################
2395: sub define_excel_formats {
2396: my ($workbook) = @_;
2397: my $format;
2398: $format->{'header'} = $workbook->add_format(bold => 1,
2399: bottom => 1,
2400: align => 'center');
2401: $format->{'bold'} = $workbook->add_format(bold=>1);
2402: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2403: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2404: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2405: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2406: $format->{'i'} = $workbook->add_format(italic=>1);
2407: $format->{'date'} = $workbook->add_format(num_format=>
2408: 'mm/dd/yyyy hh:mm:ss');
2409: return $format;
2410: }
2411:
2412: ###############################################################
2413: ###############################################################
2414:
2415: =pod
2416:
2417: =item * &create_workbook()
2418:
2419: Create an Excel worksheet. If it fails, output message on the
2420: request object and return undefs.
2421:
2422: Inputs: Apache request object
2423:
2424: Returns (undef) on failure,
2425: Excel worksheet object, scalar with filename, and formats
2426: from &Apache::loncommon::define_excel_formats on success
2427:
2428: =cut
2429:
2430: ###############################################################
2431: ###############################################################
2432: sub create_workbook {
2433: my ($r) = @_;
2434: #
2435: # Create the excel spreadsheet
2436: my $filename = '/prtspool/'.
2437: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2438: time.'_'.rand(1000000000).'.xls';
2439: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2440: if (! defined($workbook)) {
2441: $r->log_error("Error creating excel spreadsheet $filename: $!");
2442: $r->print(
2443: '<p class="LC_error">'
2444: .&mt('Problems occurred in creating the new Excel file.')
2445: .' '.&mt('This error has been logged.')
2446: .' '.&mt('Please alert your LON-CAPA administrator.')
2447: .'</p>'
2448: );
2449: return (undef);
2450: }
2451: #
2452: $workbook->set_tempdir(LONCAPA::tempdir());
2453: #
2454: my $format = &Apache::loncommon::define_excel_formats($workbook);
2455: return ($workbook,$filename,$format);
2456: }
2457:
2458: ###############################################################
2459: ###############################################################
2460:
2461: =pod
2462:
2463: =item * &create_text_file()
2464:
2465: Create a file to write to and eventually make available to the user.
2466: If file creation fails, outputs an error message on the request object and
2467: return undefs.
2468:
2469: Inputs: Apache request object, and file suffix
2470:
2471: Returns (undef) on failure,
2472: Filehandle and filename on success.
2473:
2474: =cut
2475:
2476: ###############################################################
2477: ###############################################################
2478: sub create_text_file {
2479: my ($r,$suffix) = @_;
2480: if (! defined($suffix)) { $suffix = 'txt'; };
2481: my $fh;
2482: my $filename = '/prtspool/'.
2483: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2484: time.'_'.rand(1000000000).'.'.$suffix;
2485: $fh = Apache::File->new('>/home/httpd'.$filename);
2486: if (! defined($fh)) {
2487: $r->log_error("Couldn't open $filename for output $!");
2488: $r->print(
2489: '<p class="LC_error">'
2490: .&mt('Problems occurred in creating the output file.')
2491: .' '.&mt('This error has been logged.')
2492: .' '.&mt('Please alert your LON-CAPA administrator.')
2493: .'</p>'
2494: );
2495: }
2496: return ($fh,$filename)
2497: }
2498:
2499:
2500: =pod
2501:
2502: =back
2503:
2504: =cut
2505:
2506: ###############################################################
2507: ## Home server <option> list generating code ##
2508: ###############################################################
2509:
2510: # ------------------------------------------
2511:
2512: sub domain_select {
2513: my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
2514: my @possdoms;
2515: if (ref($incdoms) eq 'ARRAY') {
2516: @possdoms = @{$incdoms};
2517: } else {
2518: @possdoms = &Apache::lonnet::all_domains();
2519: }
2520:
2521: my %domains=map {
2522: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2523: } @possdoms;
2524:
2525: if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
2526: foreach my $dom (@{$excdoms}) {
2527: delete($domains{$dom});
2528: }
2529: }
2530:
2531: if ($multiple) {
2532: $domains{''}=&mt('Any domain');
2533: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2534: return &multiple_select_form($name,$value,4,\%domains);
2535: } else {
2536: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2537: return &select_form($name,$value,\%domains);
2538: }
2539: }
2540:
2541: #-------------------------------------------
2542:
2543: =pod
2544:
2545: =head1 Routines for form select boxes
2546:
2547: =over 4
2548:
2549: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2550:
2551: Returns a string containing a <select> element int multiple mode
2552:
2553:
2554: Args:
2555: $name - name of the <select> element
2556: $value - scalar or array ref of values that should already be selected
2557: $size - number of rows long the select element is
2558: $hash - the elements should be 'option' => 'shown text'
2559: (shown text should already have been &mt())
2560: $order - (optional) array ref of the order to show the elements in
2561:
2562: =cut
2563:
2564: #-------------------------------------------
2565: sub multiple_select_form {
2566: my ($name,$value,$size,$hash,$order)=@_;
2567: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2568: my $output='';
2569: if (! defined($size)) {
2570: $size = 4;
2571: if (scalar(keys(%$hash))<4) {
2572: $size = scalar(keys(%$hash));
2573: }
2574: }
2575: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2576: my @order;
2577: if (ref($order) eq 'ARRAY') {
2578: @order = @{$order};
2579: } else {
2580: @order = sort(keys(%$hash));
2581: }
2582: if (exists($$hash{'select_form_order'})) {
2583: @order = @{$$hash{'select_form_order'}};
2584: }
2585:
2586: foreach my $key (@order) {
2587: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2588: $output.='selected="selected" ' if ($selected{$key});
2589: $output.='>'.$hash->{$key}."</option>\n";
2590: }
2591: $output.="</select>\n";
2592: return $output;
2593: }
2594:
2595: #-------------------------------------------
2596:
2597: =pod
2598:
2599: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2600:
2601: Returns a string containing a <select name='$name' size='1'> form to
2602: allow a user to select options from a ref to a hash containing:
2603: option_name => displayed text. An optional $onchange can include
2604: a javascript onchange item, e.g., onchange="this.form.submit();".
2605: An optional arg -- $readonly -- if true will cause the select form
2606: to be disabled, e.g., for the case where an instructor has a section-
2607: specific role, and is viewing/modifying parameters.
2608:
2609: See lonrights.pm for an example invocation and use.
2610:
2611: =cut
2612:
2613: #-------------------------------------------
2614: sub select_form {
2615: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2616: return unless (ref($hashref) eq 'HASH');
2617: if ($onchange) {
2618: $onchange = ' onchange="'.$onchange.'"';
2619: }
2620: my $disabled;
2621: if ($readonly) {
2622: $disabled = ' disabled="disabled"';
2623: }
2624: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2625: my @keys;
2626: if (exists($hashref->{'select_form_order'})) {
2627: @keys=@{$hashref->{'select_form_order'}};
2628: } else {
2629: @keys=sort(keys(%{$hashref}));
2630: }
2631: foreach my $key (@keys) {
2632: $selectform.=
2633: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2634: ($key eq $def ? 'selected="selected" ' : '').
2635: ">".$hashref->{$key}."</option>\n";
2636: }
2637: $selectform.="</select>";
2638: return $selectform;
2639: }
2640:
2641: # For display filters
2642:
2643: sub display_filter {
2644: my ($context) = @_;
2645: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2646: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2647: my $phraseinput = 'hidden';
2648: my $includeinput = 'hidden';
2649: my ($checked,$includetypestext);
2650: if ($env{'form.displayfilter'} eq 'containing') {
2651: $phraseinput = 'text';
2652: if ($context eq 'parmslog') {
2653: $includeinput = 'checkbox';
2654: if ($env{'form.includetypes'}) {
2655: $checked = ' checked="checked"';
2656: }
2657: $includetypestext = &mt('Include parameter types');
2658: }
2659: } else {
2660: $includetypestext = ' ';
2661: }
2662: my ($additional,$secondid,$thirdid);
2663: if ($context eq 'parmslog') {
2664: $additional =
2665: '<label><input type="'.$includeinput.'" name="includetypes"'.
2666: $checked.' name="includetypes" value="1" id="includetypes" />'.
2667: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2668: '</label>';
2669: $secondid = 'includetypes';
2670: $thirdid = 'includetypestext';
2671: }
2672: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2673: '$secondid','$thirdid')";
2674: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2675: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2676: (&mt('all'),10,20,50,100,1000,10000))).
2677: '</label></span> <span class="LC_nobreak">'.
2678: &mt('Filter: [_1]',
2679: &select_form($env{'form.displayfilter'},
2680: 'displayfilter',
2681: {'currentfolder' => 'Current folder/page',
2682: 'containing' => 'Containing phrase',
2683: 'none' => 'None'},$onchange)).' '.
2684: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2685: &HTML::Entities::encode($env{'form.containingphrase'}).
2686: '" />'.$additional;
2687: }
2688:
2689: sub display_filter_js {
2690: my $includetext = &mt('Include parameter types');
2691: return <<"ENDJS";
2692:
2693: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2694: var firstType = 'hidden';
2695: if (setter.options[setter.selectedIndex].value == 'containing') {
2696: firstType = 'text';
2697: }
2698: firstObject = document.getElementById(firstid);
2699: if (typeof(firstObject) == 'object') {
2700: if (firstObject.type != firstType) {
2701: changeInputType(firstObject,firstType);
2702: }
2703: }
2704: if (context == 'parmslog') {
2705: var secondType = 'hidden';
2706: if (firstType == 'text') {
2707: secondType = 'checkbox';
2708: }
2709: secondObject = document.getElementById(secondid);
2710: if (typeof(secondObject) == 'object') {
2711: if (secondObject.type != secondType) {
2712: changeInputType(secondObject,secondType);
2713: }
2714: }
2715: var textItem = document.getElementById(thirdid);
2716: var currtext = textItem.innerHTML;
2717: var newtext;
2718: if (firstType == 'text') {
2719: newtext = '$includetext';
2720: } else {
2721: newtext = ' ';
2722: }
2723: if (currtext != newtext) {
2724: textItem.innerHTML = newtext;
2725: }
2726: }
2727: return;
2728: }
2729:
2730: function changeInputType(oldObject,newType) {
2731: var newObject = document.createElement('input');
2732: newObject.type = newType;
2733: if (oldObject.size) {
2734: newObject.size = oldObject.size;
2735: }
2736: if (oldObject.value) {
2737: newObject.value = oldObject.value;
2738: }
2739: if (oldObject.name) {
2740: newObject.name = oldObject.name;
2741: }
2742: if (oldObject.id) {
2743: newObject.id = oldObject.id;
2744: }
2745: oldObject.parentNode.replaceChild(newObject,oldObject);
2746: return;
2747: }
2748:
2749: ENDJS
2750: }
2751:
2752: sub gradeleveldescription {
2753: my $gradelevel=shift;
2754: my %gradelevels=(0 => 'Not specified',
2755: 1 => 'Grade 1',
2756: 2 => 'Grade 2',
2757: 3 => 'Grade 3',
2758: 4 => 'Grade 4',
2759: 5 => 'Grade 5',
2760: 6 => 'Grade 6',
2761: 7 => 'Grade 7',
2762: 8 => 'Grade 8',
2763: 9 => 'Grade 9',
2764: 10 => 'Grade 10',
2765: 11 => 'Grade 11',
2766: 12 => 'Grade 12',
2767: 13 => 'Grade 13',
2768: 14 => '100 Level',
2769: 15 => '200 Level',
2770: 16 => '300 Level',
2771: 17 => '400 Level',
2772: 18 => 'Graduate Level');
2773: return &mt($gradelevels{$gradelevel});
2774: }
2775:
2776: sub select_level_form {
2777: my ($deflevel,$name)=@_;
2778: unless ($deflevel) { $deflevel=0; }
2779: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2780: for (my $i=0; $i<=18; $i++) {
2781: $selectform.="<option value=\"$i\" ".
2782: ($i==$deflevel ? 'selected="selected" ' : '').
2783: ">".&gradeleveldescription($i)."</option>\n";
2784: }
2785: $selectform.="</select>";
2786: return $selectform;
2787: }
2788:
2789: #-------------------------------------------
2790:
2791: =pod
2792:
2793: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2794:
2795: Returns a string containing a <select name='$name' size='1'> form to
2796: allow a user to select the domain to preform an operation in.
2797: See loncreateuser.pm for an example invocation and use.
2798:
2799: If the $includeempty flag is set, it also includes an empty choice ("no domain
2800: selected");
2801:
2802: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2803:
2804: 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.
2805:
2806: The optional $incdoms is a reference to an array of domains which will be the only available options.
2807:
2808: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2809:
2810: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2811:
2812: =cut
2813:
2814: #-------------------------------------------
2815: sub select_dom_form {
2816: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2817: if ($onchange) {
2818: $onchange = ' onchange="'.$onchange.'"';
2819: }
2820: if ($disabled) {
2821: $disabled = ' disabled="disabled"';
2822: }
2823: my (@domains,%exclude);
2824: if (ref($incdoms) eq 'ARRAY') {
2825: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2826: } else {
2827: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2828: }
2829: if ($includeempty) { @domains=('',@domains); }
2830: if (ref($excdoms) eq 'ARRAY') {
2831: map { $exclude{$_} = 1; } @{$excdoms};
2832: }
2833: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2834: foreach my $dom (@domains) {
2835: next if ($exclude{$dom});
2836: $selectdomain.="<option value=\"$dom\" ".
2837: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2838: if ($showdomdesc) {
2839: if ($dom ne '') {
2840: my $domdesc = &Apache::lonnet::domain($dom,'description');
2841: if ($domdesc ne '') {
2842: $selectdomain .= ' ('.$domdesc.')';
2843: }
2844: }
2845: }
2846: $selectdomain .= "</option>\n";
2847: }
2848: $selectdomain.="</select>";
2849: return $selectdomain;
2850: }
2851:
2852: #-------------------------------------------
2853:
2854: =pod
2855:
2856: =item * &home_server_form_item($domain,$name,$defaultflag)
2857:
2858: input: 4 arguments (two required, two optional) -
2859: $domain - domain of new user
2860: $name - name of form element
2861: $default - Value of 'default' causes a default item to be first
2862: option, and selected by default.
2863: $hide - Value of 'hide' causes hiding of the name of the server,
2864: if 1 server found, or default, if 0 found.
2865: output: returns 2 items:
2866: (a) form element which contains either:
2867: (i) <select name="$name">
2868: <option value="$hostid1">$hostid $servers{$hostid}</option>
2869: <option value="$hostid2">$hostid $servers{$hostid}</option>
2870: </select>
2871: form item if there are multiple library servers in $domain, or
2872: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2873: if there is only one library server in $domain.
2874:
2875: (b) number of library servers found.
2876:
2877: See loncreateuser.pm for example of use.
2878:
2879: =cut
2880:
2881: #-------------------------------------------
2882: sub home_server_form_item {
2883: my ($domain,$name,$default,$hide) = @_;
2884: my %servers = &Apache::lonnet::get_servers($domain,'library');
2885: my $result;
2886: my $numlib = keys(%servers);
2887: if ($numlib > 1) {
2888: $result .= '<select name="'.$name.'" />'."\n";
2889: if ($default) {
2890: $result .= '<option value="default" selected="selected">'.&mt('default').
2891: '</option>'."\n";
2892: }
2893: foreach my $hostid (sort(keys(%servers))) {
2894: $result.= '<option value="'.$hostid.'">'.
2895: $hostid.' '.$servers{$hostid}."</option>\n";
2896: }
2897: $result .= '</select>'."\n";
2898: } elsif ($numlib == 1) {
2899: my $hostid;
2900: foreach my $item (keys(%servers)) {
2901: $hostid = $item;
2902: }
2903: $result .= '<input type="hidden" name="'.$name.'" value="'.
2904: $hostid.'" />';
2905: if (!$hide) {
2906: $result .= $hostid.' '.$servers{$hostid};
2907: }
2908: $result .= "\n";
2909: } elsif ($default) {
2910: $result .= '<input type="hidden" name="'.$name.
2911: '" value="default" />';
2912: if (!$hide) {
2913: $result .= &mt('default');
2914: }
2915: $result .= "\n";
2916: }
2917: return ($result,$numlib);
2918: }
2919:
2920: =pod
2921:
2922: =back
2923:
2924: =cut
2925:
2926: ###############################################################
2927: ## Decoding User Agent ##
2928: ###############################################################
2929:
2930: =pod
2931:
2932: =head1 Decoding the User Agent
2933:
2934: =over 4
2935:
2936: =item * &decode_user_agent()
2937:
2938: Inputs: $r
2939:
2940: Outputs:
2941:
2942: =over 4
2943:
2944: =item * $httpbrowser
2945:
2946: =item * $clientbrowser
2947:
2948: =item * $clientversion
2949:
2950: =item * $clientmathml
2951:
2952: =item * $clientunicode
2953:
2954: =item * $clientos
2955:
2956: =item * $clientmobile
2957:
2958: =item * $clientinfo
2959:
2960: =item * $clientosversion
2961:
2962: =back
2963:
2964: =back
2965:
2966: =cut
2967:
2968: ###############################################################
2969: ###############################################################
2970: sub decode_user_agent {
2971: my ($r)=@_;
2972: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2973: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2974: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2975: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2976: my $clientbrowser='unknown';
2977: my $clientversion='0';
2978: my $clientmathml='';
2979: my $clientunicode='0';
2980: my $clientmobile=0;
2981: my $clientosversion='';
2982: for (my $i=0;$i<=$#browsertype;$i++) {
2983: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2984: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2985: $clientbrowser=$bname;
2986: $httpbrowser=~/$vreg/i;
2987: $clientversion=$1;
2988: $clientmathml=($clientversion>=$minv);
2989: $clientunicode=($clientversion>=$univ);
2990: }
2991: }
2992: my $clientos='unknown';
2993: my $clientinfo;
2994: if (($httpbrowser=~/linux/i) ||
2995: ($httpbrowser=~/unix/i) ||
2996: ($httpbrowser=~/ux/i) ||
2997: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2998: if (($httpbrowser=~/vax/i) ||
2999: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
3000: if ($httpbrowser=~/next/i) { $clientos='next'; }
3001: if (($httpbrowser=~/mac/i) ||
3002: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
3003: if ($httpbrowser=~/win/i) {
3004: $clientos='win';
3005: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
3006: $clientosversion = $1;
3007: }
3008: }
3009: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
3010: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
3011: $clientmobile=lc($1);
3012: }
3013: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
3014: $clientinfo = 'firefox-'.$1;
3015: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
3016: $clientinfo = 'chromeframe-'.$1;
3017: }
3018: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
3019: $clientunicode,$clientos,$clientmobile,$clientinfo,
3020: $clientosversion);
3021: }
3022:
3023: ###############################################################
3024: ## Authentication changing form generation subroutines ##
3025: ###############################################################
3026: ##
3027: ## All of the authform_xxxxxxx subroutines take their inputs in a
3028: ## hash, and have reasonable default values.
3029: ##
3030: ## formname = the name given in the <form> tag.
3031: #-------------------------------------------
3032:
3033: =pod
3034:
3035: =head1 Authentication Routines
3036:
3037: =over 4
3038:
3039: =item * &authform_xxxxxx()
3040:
3041: The authform_xxxxxx subroutines provide javascript and html forms which
3042: handle some of the conveniences required for authentication forms.
3043: This is not an optimal method, but it works.
3044:
3045: =over 4
3046:
3047: =item * authform_header
3048:
3049: =item * authform_authorwarning
3050:
3051: =item * authform_nochange
3052:
3053: =item * authform_kerberos
3054:
3055: =item * authform_internal
3056:
3057: =item * authform_filesystem
3058:
3059: =item * authform_lti
3060:
3061: =back
3062:
3063: See loncreateuser.pm for invocation and use examples.
3064:
3065: =cut
3066:
3067: #-------------------------------------------
3068: sub authform_header{
3069: my %in = (
3070: formname => 'cu',
3071: kerb_def_dom => '',
3072: @_,
3073: );
3074: $in{'formname'} = 'document.' . $in{'formname'};
3075: my $result='';
3076:
3077: #---------------------------------------------- Code for upper case translation
3078: my $Javascript_toUpperCase;
3079: unless ($in{kerb_def_dom}) {
3080: $Javascript_toUpperCase =<<"END";
3081: switch (choice) {
3082: case 'krb': currentform.elements[choicearg].value =
3083: currentform.elements[choicearg].value.toUpperCase();
3084: break;
3085: default:
3086: }
3087: END
3088: } else {
3089: $Javascript_toUpperCase = "";
3090: }
3091:
3092: my $radioval = "'nochange'";
3093: if (defined($in{'curr_authtype'})) {
3094: if ($in{'curr_authtype'} ne '') {
3095: $radioval = "'".$in{'curr_authtype'}."arg'";
3096: }
3097: }
3098: my $argfield = 'null';
3099: if (defined($in{'mode'})) {
3100: if ($in{'mode'} eq 'modifycourse') {
3101: if (defined($in{'curr_autharg'})) {
3102: if ($in{'curr_autharg'} ne '') {
3103: $argfield = "'$in{'curr_autharg'}'";
3104: }
3105: }
3106: }
3107: }
3108:
3109: $result.=<<"END";
3110: var current = new Object();
3111: current.radiovalue = $radioval;
3112: current.argfield = $argfield;
3113:
3114: function changed_radio(choice,currentform) {
3115: var choicearg = choice + 'arg';
3116: // If a radio button in changed, we need to change the argfield
3117: if (current.radiovalue != choice) {
3118: current.radiovalue = choice;
3119: if (current.argfield != null) {
3120: currentform.elements[current.argfield].value = '';
3121: }
3122: if (choice == 'nochange') {
3123: current.argfield = null;
3124: } else {
3125: current.argfield = choicearg;
3126: switch(choice) {
3127: case 'krb':
3128: currentform.elements[current.argfield].value =
3129: "$in{'kerb_def_dom'}";
3130: break;
3131: default:
3132: break;
3133: }
3134: }
3135: }
3136: return;
3137: }
3138:
3139: function changed_text(choice,currentform) {
3140: var choicearg = choice + 'arg';
3141: if (currentform.elements[choicearg].value !='') {
3142: $Javascript_toUpperCase
3143: // clear old field
3144: if ((current.argfield != choicearg) && (current.argfield != null)) {
3145: currentform.elements[current.argfield].value = '';
3146: }
3147: current.argfield = choicearg;
3148: }
3149: set_auth_radio_buttons(choice,currentform);
3150: return;
3151: }
3152:
3153: function set_auth_radio_buttons(newvalue,currentform) {
3154: var numauthchoices = currentform.login.length;
3155: if (typeof numauthchoices == "undefined") {
3156: return;
3157: }
3158: var i=0;
3159: while (i < numauthchoices) {
3160: if (currentform.login[i].value == newvalue) { break; }
3161: i++;
3162: }
3163: if (i == numauthchoices) {
3164: return;
3165: }
3166: current.radiovalue = newvalue;
3167: currentform.login[i].checked = true;
3168: return;
3169: }
3170: END
3171: return $result;
3172: }
3173:
3174: sub authform_authorwarning {
3175: my $result='';
3176: $result='<i>'.
3177: &mt('As a general rule, only authors or co-authors should be '.
3178: 'filesystem authenticated '.
3179: '(which allows access to the server filesystem).')."</i>\n";
3180: return $result;
3181: }
3182:
3183: sub authform_nochange {
3184: my %in = (
3185: formname => 'document.cu',
3186: kerb_def_dom => 'MSU.EDU',
3187: @_,
3188: );
3189: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3190: my $result;
3191: if (!$authnum) {
3192: $result = &mt('Under your current role you are not permitted to change login settings for this user');
3193: } else {
3194: $result = '<label>'.&mt('[_1] Do not change login data',
3195: '<input type="radio" name="login" value="nochange" '.
3196: 'checked="checked" onclick="'.
3197: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
3198: '</label>';
3199: }
3200: return $result;
3201: }
3202:
3203: sub authform_kerberos {
3204: my %in = (
3205: formname => 'document.cu',
3206: kerb_def_dom => 'MSU.EDU',
3207: kerb_def_auth => 'krb4',
3208: @_,
3209: );
3210: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
3211: $autharg,$jscall,$disabled);
3212: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3213: if ($in{'kerb_def_auth'} eq 'krb5') {
3214: $check5 = ' checked="checked"';
3215: } else {
3216: $check4 = ' checked="checked"';
3217: }
3218: if ($in{'readonly'}) {
3219: $disabled = ' disabled="disabled"';
3220: }
3221: $krbarg = $in{'kerb_def_dom'};
3222: if (defined($in{'curr_authtype'})) {
3223: if ($in{'curr_authtype'} eq 'krb') {
3224: $krbcheck = ' checked="checked"';
3225: if (defined($in{'mode'})) {
3226: if ($in{'mode'} eq 'modifyuser') {
3227: $krbcheck = '';
3228: }
3229: }
3230: if (defined($in{'curr_kerb_ver'})) {
3231: if ($in{'curr_krb_ver'} eq '5') {
3232: $check5 = ' checked="checked"';
3233: $check4 = '';
3234: } else {
3235: $check4 = ' checked="checked"';
3236: $check5 = '';
3237: }
3238: }
3239: if (defined($in{'curr_autharg'})) {
3240: $krbarg = $in{'curr_autharg'};
3241: }
3242: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3243: if (defined($in{'curr_autharg'})) {
3244: $result =
3245: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3246: $in{'curr_autharg'},$krbver);
3247: } else {
3248: $result =
3249: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3250: }
3251: return $result;
3252: }
3253: }
3254: } else {
3255: if ($authnum == 1) {
3256: $authtype = '<input type="hidden" name="login" value="krb" />';
3257: }
3258: }
3259: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3260: return;
3261: } elsif ($authtype eq '') {
3262: if (defined($in{'mode'})) {
3263: if ($in{'mode'} eq 'modifycourse') {
3264: if ($authnum == 1) {
3265: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
3266: }
3267: }
3268: }
3269: }
3270: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3271: if ($authtype eq '') {
3272: $authtype = '<input type="radio" name="login" value="krb" '.
3273: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3274: $krbcheck.$disabled.' />';
3275: }
3276: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3277: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3278: $in{'curr_authtype'} eq 'krb5') ||
3279: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3280: $in{'curr_authtype'} eq 'krb4')) {
3281: $result .= &mt
3282: ('[_1] Kerberos authenticated with domain [_2] '.
3283: '[_3] Version 4 [_4] Version 5 [_5]',
3284: '<label>'.$authtype,
3285: '</label><input type="text" size="10" name="krbarg" '.
3286: 'value="'.$krbarg.'" '.
3287: 'onchange="'.$jscall.'"'.$disabled.' />',
3288: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
3289: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
3290: '</label>');
3291: } elsif ($can_assign{'krb4'}) {
3292: $result .= &mt
3293: ('[_1] Kerberos authenticated with domain [_2] '.
3294: '[_3] Version 4 [_4]',
3295: '<label>'.$authtype,
3296: '</label><input type="text" size="10" name="krbarg" '.
3297: 'value="'.$krbarg.'" '.
3298: 'onchange="'.$jscall.'"'.$disabled.' />',
3299: '<label><input type="hidden" name="krbver" value="4" />',
3300: '</label>');
3301: } elsif ($can_assign{'krb5'}) {
3302: $result .= &mt
3303: ('[_1] Kerberos authenticated with domain [_2] '.
3304: '[_3] Version 5 [_4]',
3305: '<label>'.$authtype,
3306: '</label><input type="text" size="10" name="krbarg" '.
3307: 'value="'.$krbarg.'" '.
3308: 'onchange="'.$jscall.'"'.$disabled.' />',
3309: '<label><input type="hidden" name="krbver" value="5" />',
3310: '</label>');
3311: }
3312: return $result;
3313: }
3314:
3315: sub authform_internal {
3316: my %in = (
3317: formname => 'document.cu',
3318: kerb_def_dom => 'MSU.EDU',
3319: @_,
3320: );
3321: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
3322: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3323: if ($in{'readonly'}) {
3324: $disabled = ' disabled="disabled"';
3325: }
3326: if (defined($in{'curr_authtype'})) {
3327: if ($in{'curr_authtype'} eq 'int') {
3328: if ($can_assign{'int'}) {
3329: $intcheck = 'checked="checked" ';
3330: if (defined($in{'mode'})) {
3331: if ($in{'mode'} eq 'modifyuser') {
3332: $intcheck = '';
3333: }
3334: }
3335: if (defined($in{'curr_autharg'})) {
3336: $intarg = $in{'curr_autharg'};
3337: }
3338: } else {
3339: $result = &mt('Currently internally authenticated.');
3340: return $result;
3341: }
3342: }
3343: } else {
3344: if ($authnum == 1) {
3345: $authtype = '<input type="hidden" name="login" value="int" />';
3346: }
3347: }
3348: if (!$can_assign{'int'}) {
3349: return;
3350: } elsif ($authtype eq '') {
3351: if (defined($in{'mode'})) {
3352: if ($in{'mode'} eq 'modifycourse') {
3353: if ($authnum == 1) {
3354: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3355: }
3356: }
3357: }
3358: }
3359: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3360: if ($authtype eq '') {
3361: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3362: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3363: }
3364: $autharg = '<input type="password" size="10" name="intarg" value="'.
3365: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3366: $result = &mt
3367: ('[_1] Internally authenticated (with initial password [_2])',
3368: '<label>'.$authtype,'</label>'.$autharg);
3369: $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>';
3370: return $result;
3371: }
3372:
3373: sub authform_local {
3374: my %in = (
3375: formname => 'document.cu',
3376: kerb_def_dom => 'MSU.EDU',
3377: @_,
3378: );
3379: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3380: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3381: if ($in{'readonly'}) {
3382: $disabled = ' disabled="disabled"';
3383: }
3384: if (defined($in{'curr_authtype'})) {
3385: if ($in{'curr_authtype'} eq 'loc') {
3386: if ($can_assign{'loc'}) {
3387: $loccheck = 'checked="checked" ';
3388: if (defined($in{'mode'})) {
3389: if ($in{'mode'} eq 'modifyuser') {
3390: $loccheck = '';
3391: }
3392: }
3393: if (defined($in{'curr_autharg'})) {
3394: $locarg = $in{'curr_autharg'};
3395: }
3396: } else {
3397: $result = &mt('Currently using local (institutional) authentication.');
3398: return $result;
3399: }
3400: }
3401: } else {
3402: if ($authnum == 1) {
3403: $authtype = '<input type="hidden" name="login" value="loc" />';
3404: }
3405: }
3406: if (!$can_assign{'loc'}) {
3407: return;
3408: } elsif ($authtype eq '') {
3409: if (defined($in{'mode'})) {
3410: if ($in{'mode'} eq 'modifycourse') {
3411: if ($authnum == 1) {
3412: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3413: }
3414: }
3415: }
3416: }
3417: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3418: if ($authtype eq '') {
3419: $authtype = '<input type="radio" name="login" value="loc" '.
3420: $loccheck.' onchange="'.$jscall.'" onclick="'.
3421: $jscall.'"'.$disabled.' />';
3422: }
3423: $autharg = '<input type="text" size="10" name="locarg" value="'.
3424: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3425: $result = &mt('[_1] Local Authentication with argument [_2]',
3426: '<label>'.$authtype,'</label>'.$autharg);
3427: return $result;
3428: }
3429:
3430: sub authform_filesystem {
3431: my %in = (
3432: formname => 'document.cu',
3433: kerb_def_dom => 'MSU.EDU',
3434: @_,
3435: );
3436: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3437: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3438: if ($in{'readonly'}) {
3439: $disabled = ' disabled="disabled"';
3440: }
3441: if (defined($in{'curr_authtype'})) {
3442: if ($in{'curr_authtype'} eq 'fsys') {
3443: if ($can_assign{'fsys'}) {
3444: $fsyscheck = 'checked="checked" ';
3445: if (defined($in{'mode'})) {
3446: if ($in{'mode'} eq 'modifyuser') {
3447: $fsyscheck = '';
3448: }
3449: }
3450: } else {
3451: $result = &mt('Currently Filesystem Authenticated.');
3452: return $result;
3453: }
3454: }
3455: } else {
3456: if ($authnum == 1) {
3457: $authtype = '<input type="hidden" name="login" value="fsys" />';
3458: }
3459: }
3460: if (!$can_assign{'fsys'}) {
3461: return;
3462: } elsif ($authtype eq '') {
3463: if (defined($in{'mode'})) {
3464: if ($in{'mode'} eq 'modifycourse') {
3465: if ($authnum == 1) {
3466: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3467: }
3468: }
3469: }
3470: }
3471: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3472: if ($authtype eq '') {
3473: $authtype = '<input type="radio" name="login" value="fsys" '.
3474: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3475: $jscall.'"'.$disabled.' />';
3476: }
3477: $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
3478: ' onchange="'.$jscall.'"'.$disabled.' />';
3479: $result = &mt
3480: ('[_1] Filesystem Authenticated (with initial password [_2])',
3481: '<label>'.$authtype,'</label>'.$autharg);
3482: return $result;
3483: }
3484:
3485: sub authform_lti {
3486: my %in = (
3487: formname => 'document.cu',
3488: kerb_def_dom => 'MSU.EDU',
3489: @_,
3490: );
3491: my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
3492: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3493: if ($in{'readonly'}) {
3494: $disabled = ' disabled="disabled"';
3495: }
3496: if (defined($in{'curr_authtype'})) {
3497: if ($in{'curr_authtype'} eq 'lti') {
3498: if ($can_assign{'lti'}) {
3499: $lticheck = 'checked="checked" ';
3500: if (defined($in{'mode'})) {
3501: if ($in{'mode'} eq 'modifyuser') {
3502: $lticheck = '';
3503: }
3504: }
3505: } else {
3506: $result = &mt('Currently LTI Authenticated.');
3507: return $result;
3508: }
3509: }
3510: } else {
3511: if ($authnum == 1) {
3512: $authtype = '<input type="hidden" name="login" value="lti" />';
3513: }
3514: }
3515: if (!$can_assign{'lti'}) {
3516: return;
3517: } elsif ($authtype eq '') {
3518: if (defined($in{'mode'})) {
3519: if ($in{'mode'} eq 'modifycourse') {
3520: if ($authnum == 1) {
3521: $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
3522: }
3523: }
3524: }
3525: }
3526: $jscall = "javascript:changed_radio('lti',$in{'formname'});";
3527: if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
3528: $authtype = '<input type="radio" name="login" value="lti" '.
3529: $lticheck.' onchange="'.$jscall.'" onclick="'.
3530: $jscall.'"'.$disabled.' />';
3531: }
3532: $autharg = '<input type="hidden" name="ltiarg" value="" />';
3533: if ($authtype) {
3534: $result = &mt('[_1] LTI Authenticated',
3535: '<label>'.$authtype.'</label>'.$autharg);
3536: } else {
3537: $result = '<b>'.&mt('LTI Authenticated').'</b>'.
3538: $autharg;
3539: }
3540: return $result;
3541: }
3542:
3543: sub get_assignable_auth {
3544: my ($dom) = @_;
3545: if ($dom eq '') {
3546: $dom = $env{'request.role.domain'};
3547: }
3548: my %can_assign = (
3549: krb4 => 1,
3550: krb5 => 1,
3551: int => 1,
3552: loc => 1,
3553: lti => 1,
3554: );
3555: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3556: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3557: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3558: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3559: my $context;
3560: if ($env{'request.role'} =~ /^au/) {
3561: $context = 'author';
3562: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3563: $context = 'domain';
3564: } elsif ($env{'request.course.id'}) {
3565: $context = 'course';
3566: }
3567: if ($context) {
3568: if (ref($authhash->{$context}) eq 'HASH') {
3569: %can_assign = %{$authhash->{$context}};
3570: }
3571: }
3572: }
3573: }
3574: my $authnum = 0;
3575: foreach my $key (keys(%can_assign)) {
3576: if ($can_assign{$key}) {
3577: $authnum ++;
3578: }
3579: }
3580: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3581: $authnum --;
3582: }
3583: return ($authnum,%can_assign);
3584: }
3585:
3586: sub check_passwd_rules {
3587: my ($domain,$plainpass) = @_;
3588: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3589: my ($min,$max,@chars,@brokerule,$warning);
3590: $min = $Apache::lonnet::passwdmin;
3591: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3592: if ($passwdconf{'min'} =~ /^\d+$/) {
3593: if ($passwdconf{'min'} > $min) {
3594: $min = $passwdconf{'min'};
3595: }
3596: }
3597: if ($passwdconf{'max'} =~ /^\d+$/) {
3598: $max = $passwdconf{'max'};
3599: }
3600: @chars = @{$passwdconf{'chars'}};
3601: }
3602: if (($min) && (length($plainpass) < $min)) {
3603: push(@brokerule,'min');
3604: }
3605: if (($max) && (length($plainpass) > $max)) {
3606: push(@brokerule,'max');
3607: }
3608: if (@chars) {
3609: my %rules;
3610: map { $rules{$_} = 1; } @chars;
3611: if ($rules{'uc'}) {
3612: unless ($plainpass =~ /[A-Z]/) {
3613: push(@brokerule,'uc');
3614: }
3615: }
3616: if ($rules{'lc'}) {
3617: unless ($plainpass =~ /[a-z]/) {
3618: push(@brokerule,'lc');
3619: }
3620: }
3621: if ($rules{'num'}) {
3622: unless ($plainpass =~ /\d/) {
3623: push(@brokerule,'num');
3624: }
3625: }
3626: if ($rules{'spec'}) {
3627: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3628: push(@brokerule,'spec');
3629: }
3630: }
3631: }
3632: if (@brokerule) {
3633: my %rulenames = &Apache::lonlocal::texthash(
3634: uc => 'At least one upper case letter',
3635: lc => 'At least one lower case letter',
3636: num => 'At least one number',
3637: spec => 'At least one non-alphanumeric',
3638: );
3639: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3640: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3641: $rulenames{'num'} .= ': 0123456789';
3642: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3643: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3644: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3645: $warning = &mt('Password did not satisfy the following:').'<ul>';
3646: foreach my $rule ('min','max','uc','lc','num','spec') {
3647: if (grep(/^$rule$/,@brokerule)) {
3648: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3649: }
3650: }
3651: $warning .= '</ul>';
3652: }
3653: if (wantarray) {
3654: return @brokerule;
3655: }
3656: return $warning;
3657: }
3658:
3659: sub passwd_validation_js {
3660: my ($currpasswdval,$domain,$context,$id) = @_;
3661: my (%passwdconf,$alertmsg);
3662: if ($context eq 'linkprot') {
3663: my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
3664: if (ref($domconfig{'ltisec'}) eq 'HASH') {
3665: if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
3666: %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
3667: }
3668: }
3669: if ($id eq 'add') {
3670: $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
3671: } elsif ($id =~ /^\d+$/) {
3672: my $pos = $id+1;
3673: $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
3674: } else {
3675: $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
3676: }
3677: } else {
3678: %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3679: $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
3680: }
3681: my ($min,$max,@chars,$numrules,$intargjs,%alert);
3682: $numrules = 0;
3683: $min = $Apache::lonnet::passwdmin;
3684: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3685: if ($passwdconf{'min'} =~ /^\d+$/) {
3686: if ($passwdconf{'min'} > $min) {
3687: $min = $passwdconf{'min'};
3688: }
3689: }
3690: if ($passwdconf{'max'} =~ /^\d+$/) {
3691: $max = $passwdconf{'max'};
3692: $numrules ++;
3693: }
3694: @chars = @{$passwdconf{'chars'}};
3695: if (@chars) {
3696: $numrules ++;
3697: }
3698: }
3699: if ($min > 0) {
3700: $numrules ++;
3701: }
3702: if (($min > 0) || ($max ne '') || (@chars > 0)) {
3703: if ($min) {
3704: $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
3705: }
3706: if ($max) {
3707: $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
3708: }
3709: my (@charalerts,@charrules);
3710: if (@chars) {
3711: if (grep(/^uc$/,@chars)) {
3712: push(@charalerts,&mt('contain at least one upper case letter'));
3713: push(@charrules,'uc');
3714: }
3715: if (grep(/^lc$/,@chars)) {
3716: push(@charalerts,&mt('contain at least one lower case letter'));
3717: push(@charrules,'lc');
3718: }
3719: if (grep(/^num$/,@chars)) {
3720: push(@charalerts,&mt('contain at least one number'));
3721: push(@charrules,'num');
3722: }
3723: if (grep(/^spec$/,@chars)) {
3724: push(@charalerts,&mt('contain at least one non-alphanumeric'));
3725: push(@charrules,'spec');
3726: }
3727: }
3728: $intargjs = qq| var rulesmsg = '';\n|.
3729: qq| var currpwval = $currpasswdval;\n|;
3730: if ($min) {
3731: $intargjs .= qq|
3732: if (currpwval.length < $min) {
3733: rulesmsg += ' - $alert{min}';
3734: }
3735: |;
3736: }
3737: if ($max) {
3738: $intargjs .= qq|
3739: if (currpwval.length > $max) {
3740: rulesmsg += ' - $alert{max}';
3741: }
3742: |;
3743: }
3744: if (@chars > 0) {
3745: my $charrulestr = '"'.join('","',@charrules).'"';
3746: my $charalertstr = '"'.join('","',@charalerts).'"';
3747: $intargjs .= qq| var brokerules = new Array();\n|.
3748: qq| var charrules = new Array($charrulestr);\n|.
3749: qq| var charalerts = new Array($charalertstr);\n|;
3750: my %rules;
3751: map { $rules{$_} = 1; } @chars;
3752: if ($rules{'uc'}) {
3753: $intargjs .= qq|
3754: var ucRegExp = /[A-Z]/;
3755: if (!ucRegExp.test(currpwval)) {
3756: brokerules.push('uc');
3757: }
3758: |;
3759: }
3760: if ($rules{'lc'}) {
3761: $intargjs .= qq|
3762: var lcRegExp = /[a-z]/;
3763: if (!lcRegExp.test(currpwval)) {
3764: brokerules.push('lc');
3765: }
3766: |;
3767: }
3768: if ($rules{'num'}) {
3769: $intargjs .= qq|
3770: var numRegExp = /[0-9]/;
3771: if (!numRegExp.test(currpwval)) {
3772: brokerules.push('num');
3773: }
3774: |;
3775: }
3776: if ($rules{'spec'}) {
3777: $intargjs .= q|
3778: var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
3779: if (!specRegExp.test(currpwval)) {
3780: brokerules.push('spec');
3781: }
3782: |;
3783: }
3784: $intargjs .= qq|
3785: if (brokerules.length > 0) {
3786: for (var i=0; i<brokerules.length; i++) {
3787: for (var j=0; j<charrules.length; j++) {
3788: if (brokerules[i] == charrules[j]) {
3789: rulesmsg += ' - '+charalerts[j]+'\\n';
3790: break;
3791: }
3792: }
3793: }
3794: }
3795: |;
3796: }
3797: $intargjs .= qq|
3798: if (rulesmsg != '') {
3799: rulesmsg = '$alertmsg'+rulesmsg;
3800: alert(rulesmsg);
3801: return false;
3802: }
3803: |;
3804: }
3805: return ($numrules,$intargjs);
3806: }
3807:
3808: ###############################################################
3809: ## Get Kerberos Defaults for Domain ##
3810: ###############################################################
3811: ##
3812: ## Returns default kerberos version and an associated argument
3813: ## as listed in file domain.tab. If not listed, provides
3814: ## appropriate default domain and kerberos version.
3815: ##
3816: #-------------------------------------------
3817:
3818: =pod
3819:
3820: =item * &get_kerberos_defaults()
3821:
3822: get_kerberos_defaults($target_domain) returns the default kerberos
3823: version and domain. If not found, it defaults to version 4 and the
3824: domain of the server.
3825:
3826: =over 4
3827:
3828: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3829:
3830: =back
3831:
3832: =back
3833:
3834: =cut
3835:
3836: #-------------------------------------------
3837: sub get_kerberos_defaults {
3838: my $domain=shift;
3839: my ($krbdef,$krbdefdom);
3840: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3841: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3842: $krbdef = $domdefaults{'auth_def'};
3843: $krbdefdom = $domdefaults{'auth_arg_def'};
3844: } else {
3845: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3846: my $krbdefdom=$1;
3847: $krbdefdom=~tr/a-z/A-Z/;
3848: $krbdef = "krb4";
3849: }
3850: return ($krbdef,$krbdefdom);
3851: }
3852:
3853:
3854: ###############################################################
3855: ## Thesaurus Functions ##
3856: ###############################################################
3857:
3858: =pod
3859:
3860: =head1 Thesaurus Functions
3861:
3862: =over 4
3863:
3864: =item * &initialize_keywords()
3865:
3866: Initializes the package variable %Keywords if it is empty. Uses the
3867: package variable $thesaurus_db_file.
3868:
3869: =cut
3870:
3871: ###################################################
3872:
3873: sub initialize_keywords {
3874: return 1 if (scalar keys(%Keywords));
3875: # If we are here, %Keywords is empty, so fill it up
3876: # Make sure the file we need exists...
3877: if (! -e $thesaurus_db_file) {
3878: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3879: " failed because it does not exist");
3880: return 0;
3881: }
3882: # Set up the hash as a database
3883: my %thesaurus_db;
3884: if (! tie(%thesaurus_db,'GDBM_File',
3885: $thesaurus_db_file,&GDBM_READER(),0640)){
3886: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3887: $thesaurus_db_file);
3888: return 0;
3889: }
3890: # Get the average number of appearances of a word.
3891: my $avecount = $thesaurus_db{'average.count'};
3892: # Put keywords (those that appear > average) into %Keywords
3893: while (my ($word,$data)=each (%thesaurus_db)) {
3894: my ($count,undef) = split /:/,$data;
3895: $Keywords{$word}++ if ($count > $avecount);
3896: }
3897: untie %thesaurus_db;
3898: # Remove special values from %Keywords.
3899: foreach my $value ('total.count','average.count') {
3900: delete($Keywords{$value}) if (exists($Keywords{$value}));
3901: }
3902: return 1;
3903: }
3904:
3905: ###################################################
3906:
3907: =pod
3908:
3909: =item * &keyword($word)
3910:
3911: Returns true if $word is a keyword. A keyword is a word that appears more
3912: than the average number of times in the thesaurus database. Calls
3913: &initialize_keywords
3914:
3915: =cut
3916:
3917: ###################################################
3918:
3919: sub keyword {
3920: return if (!&initialize_keywords());
3921: my $word=lc(shift());
3922: $word=~s/\W//g;
3923: return exists($Keywords{$word});
3924: }
3925:
3926: ###############################################################
3927:
3928: =pod
3929:
3930: =item * &get_related_words()
3931:
3932: Look up a word in the thesaurus. Takes a scalar argument and returns
3933: an array of words. If the keyword is not in the thesaurus, an empty array
3934: will be returned. The order of the words returned is determined by the
3935: database which holds them.
3936:
3937: Uses global $thesaurus_db_file.
3938:
3939:
3940: =cut
3941:
3942: ###############################################################
3943: sub get_related_words {
3944: my $keyword = shift;
3945: my %thesaurus_db;
3946: if (! -e $thesaurus_db_file) {
3947: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3948: "failed because the file does not exist");
3949: return ();
3950: }
3951: if (! tie(%thesaurus_db,'GDBM_File',
3952: $thesaurus_db_file,&GDBM_READER(),0640)){
3953: return ();
3954: }
3955: my @Words=();
3956: my $count=0;
3957: if (exists($thesaurus_db{$keyword})) {
3958: # The first element is the number of times
3959: # the word appears. We do not need it now.
3960: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3961: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3962: my $threshold=$mostfrequentcount/10;
3963: foreach my $possibleword (@RelatedWords) {
3964: my ($word,$wordcount)=split(/\,/,$possibleword);
3965: if ($wordcount>$threshold) {
3966: push(@Words,$word);
3967: $count++;
3968: if ($count>10) { last; }
3969: }
3970: }
3971: }
3972: untie %thesaurus_db;
3973: return @Words;
3974: }
3975: ###############################################################
3976: #
3977: # Spell checking
3978: #
3979:
3980: =pod
3981:
3982: =back
3983:
3984: =head1 Spell checking
3985:
3986: =over 4
3987:
3988: =item * &check_spelling($wordlist $language)
3989:
3990: Takes a string containing words and feeds it to an external
3991: spellcheck program via a pipeline. Returns a string containing
3992: them mis-spelled words.
3993:
3994: Parameters:
3995:
3996: =over 4
3997:
3998: =item - $wordlist
3999:
4000: String that will be fed into the spellcheck program.
4001:
4002: =item - $language
4003:
4004: Language string that specifies the language for which the spell
4005: check will be performed.
4006:
4007: =back
4008:
4009: =back
4010:
4011: Note: This sub assumes that aspell is installed.
4012:
4013:
4014: =cut
4015:
4016:
4017: sub check_spelling {
4018: my ($wordlist, $language) = @_;
4019: my @misspellings;
4020:
4021: # Generate the speller and set the langauge.
4022: # if explicitly selected:
4023:
4024: my $speller = Text::Aspell->new;
4025: if ($language) {
4026: $speller->set_option('lang', $language);
4027: }
4028:
4029: # Turn the word list into an array of words by splittingon whitespace
4030:
4031: my @words = split(/\s+/, $wordlist);
4032:
4033: foreach my $word (@words) {
4034: if(! $speller->check($word)) {
4035: push(@misspellings, $word);
4036: }
4037: }
4038: return join(' ', @misspellings);
4039:
4040: }
4041:
4042: # -------------------------------------------------------------- Plaintext name
4043: =pod
4044:
4045: =head1 User Name Functions
4046:
4047: =over 4
4048:
4049: =item * &plainname($uname,$udom,$first)
4050:
4051: Takes a users logon name and returns it as a string in
4052: "first middle last generation" form
4053: if $first is set to 'lastname' then it returns it as
4054: 'lastname generation, firstname middlename' if their is a lastname
4055:
4056: =cut
4057:
4058:
4059: ###############################################################
4060: sub plainname {
4061: my ($uname,$udom,$first)=@_;
4062: return if (!defined($uname) || !defined($udom));
4063: my %names=&getnames($uname,$udom);
4064: my $name=&Apache::lonnet::format_name($names{'firstname'},
4065: $names{'middlename'},
4066: $names{'lastname'},
4067: $names{'generation'},$first);
4068: $name=~s/^\s+//;
4069: $name=~s/\s+$//;
4070: $name=~s/\s+/ /g;
4071: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
4072: return $name;
4073: }
4074:
4075: # -------------------------------------------------------------------- Nickname
4076: =pod
4077:
4078: =item * &nickname($uname,$udom)
4079:
4080: Gets a users name and returns it as a string as
4081:
4082: ""nickname""
4083:
4084: if the user has a nickname or
4085:
4086: "first middle last generation"
4087:
4088: if the user does not
4089:
4090: =cut
4091:
4092: sub nickname {
4093: my ($uname,$udom)=@_;
4094: return if (!defined($uname) || !defined($udom));
4095: my %names=&getnames($uname,$udom);
4096: my $name=$names{'nickname'};
4097: if ($name) {
4098: $name='"'.$name.'"';
4099: } else {
4100: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
4101: $names{'lastname'}.' '.$names{'generation'};
4102: $name=~s/\s+$//;
4103: $name=~s/\s+/ /g;
4104: }
4105: return $name;
4106: }
4107:
4108: sub getnames {
4109: my ($uname,$udom)=@_;
4110: return if (!defined($uname) || !defined($udom));
4111: if ($udom eq 'public' && $uname eq 'public') {
4112: return ('lastname' => &mt('Public'));
4113: }
4114: my $id=$uname.':'.$udom;
4115: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
4116: if ($cached) {
4117: return %{$names};
4118: } else {
4119: my %loadnames=&Apache::lonnet::get('environment',
4120: ['firstname','middlename','lastname','generation','nickname'],
4121: $udom,$uname);
4122: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
4123: return %loadnames;
4124: }
4125: }
4126:
4127: # -------------------------------------------------------------------- getemails
4128:
4129: =pod
4130:
4131: =item * &getemails($uname,$udom)
4132:
4133: Gets a user's email information and returns it as a hash with keys:
4134: notification, critnotification, permanentemail
4135:
4136: For notification and critnotification, values are comma-separated lists
4137: of e-mail addresses; for permanentemail, value is a single e-mail address.
4138:
4139:
4140: =cut
4141:
4142:
4143: sub getemails {
4144: my ($uname,$udom)=@_;
4145: if ($udom eq 'public' && $uname eq 'public') {
4146: return;
4147: }
4148: if (!$udom) { $udom=$env{'user.domain'}; }
4149: if (!$uname) { $uname=$env{'user.name'}; }
4150: my $id=$uname.':'.$udom;
4151: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
4152: if ($cached) {
4153: return %{$names};
4154: } else {
4155: my %loadnames=&Apache::lonnet::get('environment',
4156: ['notification','critnotification',
4157: 'permanentemail'],
4158: $udom,$uname);
4159: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
4160: return %loadnames;
4161: }
4162: }
4163:
4164: sub flush_email_cache {
4165: my ($uname,$udom)=@_;
4166: if (!$udom) { $udom =$env{'user.domain'}; }
4167: if (!$uname) { $uname=$env{'user.name'}; }
4168: return if ($udom eq 'public' && $uname eq 'public');
4169: my $id=$uname.':'.$udom;
4170: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
4171: }
4172:
4173: # -------------------------------------------------------------------- getlangs
4174:
4175: =pod
4176:
4177: =item * &getlangs($uname,$udom)
4178:
4179: Gets a user's language preference and returns it as a hash with key:
4180: language.
4181:
4182: =cut
4183:
4184:
4185: sub getlangs {
4186: my ($uname,$udom) = @_;
4187: if (!$udom) { $udom =$env{'user.domain'}; }
4188: if (!$uname) { $uname=$env{'user.name'}; }
4189: my $id=$uname.':'.$udom;
4190: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
4191: if ($cached) {
4192: return %{$langs};
4193: } else {
4194: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
4195: $udom,$uname);
4196: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
4197: return %loadlangs;
4198: }
4199: }
4200:
4201: sub flush_langs_cache {
4202: my ($uname,$udom)=@_;
4203: if (!$udom) { $udom =$env{'user.domain'}; }
4204: if (!$uname) { $uname=$env{'user.name'}; }
4205: return if ($udom eq 'public' && $uname eq 'public');
4206: my $id=$uname.':'.$udom;
4207: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
4208: }
4209:
4210: # ------------------------------------------------------------------ Screenname
4211:
4212: =pod
4213:
4214: =item * &screenname($uname,$udom)
4215:
4216: Gets a users screenname and returns it as a string
4217:
4218: =cut
4219:
4220: sub screenname {
4221: my ($uname,$udom)=@_;
4222: if ($uname eq $env{'user.name'} &&
4223: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
4224: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
4225: return $names{'screenname'};
4226: }
4227:
4228:
4229: # ------------------------------------------------------------- Confirm Wrapper
4230: =pod
4231:
4232: =item * &confirmwrapper($message)
4233:
4234: Wrap messages about completion of operation in box
4235:
4236: =cut
4237:
4238: sub confirmwrapper {
4239: my ($message)=@_;
4240: if ($message) {
4241: return "\n".'<div class="LC_confirm_box">'."\n"
4242: .$message."\n"
4243: .'</div>'."\n";
4244: } else {
4245: return $message;
4246: }
4247: }
4248:
4249: # ------------------------------------------------------------- Message Wrapper
4250:
4251: sub messagewrapper {
4252: my ($link,$username,$domain,$subject,$text)=@_;
4253: return
4254: '<a href="/adm/email?compose=individual&'.
4255: 'recname='.$username.'&recdom='.$domain.
4256: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
4257: 'title="'.&mt('Send message').'">'.$link.'</a>';
4258: }
4259:
4260: # --------------------------------------------------------------- Notes Wrapper
4261:
4262: sub noteswrapper {
4263: my ($link,$un,$do)=@_;
4264: return
4265: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
4266: }
4267:
4268: # ------------------------------------------------------------- Aboutme Wrapper
4269:
4270: sub aboutmewrapper {
4271: my ($link,$username,$domain,$target,$class)=@_;
4272: if (!defined($username) && !defined($domain)) {
4273: return;
4274: }
4275: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
4276: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
4277: }
4278:
4279: # ------------------------------------------------------------ Syllabus Wrapper
4280:
4281: sub syllabuswrapper {
4282: my ($linktext,$coursedir,$domain)=@_;
4283: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
4284: }
4285:
4286: # -----------------------------------------------------------------------------
4287:
4288: sub track_student_link {
4289: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
4290: my $link ="/adm/trackstudent?";
4291: my $title = 'View recent activity';
4292: if (defined($sname) && $sname !~ /^\s*$/ &&
4293: defined($sdom) && $sdom !~ /^\s*$/) {
4294: $link .= "selected_student=$sname:$sdom";
4295: $title .= ' of this student';
4296: }
4297: if (defined($target) && $target !~ /^\s*$/) {
4298: $target = qq{target="$target"};
4299: } else {
4300: $target = '';
4301: }
4302: if ($start) { $link.='&start='.$start; }
4303: if ($only_body) { $link .= '&only_body=1'; }
4304: $title = &mt($title);
4305: $linktext = &mt($linktext);
4306: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
4307: &help_open_topic('View_recent_activity');
4308: }
4309:
4310: sub slot_reservations_link {
4311: my ($linktext,$sname,$sdom,$target) = @_;
4312: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
4313: my $title = 'View slot reservation history';
4314: if (defined($sname) && $sname !~ /^\s*$/ &&
4315: defined($sdom) && $sdom !~ /^\s*$/) {
4316: $link .= "&uname=$sname&udom=$sdom";
4317: $title .= ' of this student';
4318: }
4319: if (defined($target) && $target !~ /^\s*$/) {
4320: $target = qq{target="$target"};
4321: } else {
4322: $target = '';
4323: }
4324: $title = &mt($title);
4325: $linktext = &mt($linktext);
4326: return qq{<a href="$link" title="$title" $target>$linktext</a>};
4327: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
4328:
4329: }
4330:
4331: # ===================================================== Display a student photo
4332:
4333:
4334: sub student_image_tag {
4335: my ($domain,$user)=@_;
4336: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
4337: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
4338: return '<img src="'.$imgsrc.'" align="right" />';
4339: } else {
4340: return '';
4341: }
4342: }
4343:
4344: =pod
4345:
4346: =back
4347:
4348: =head1 Access .tab File Data
4349:
4350: =over 4
4351:
4352: =item * &languageids()
4353:
4354: returns list of all language ids
4355:
4356: =cut
4357:
4358: sub languageids {
4359: return sort(keys(%language));
4360: }
4361:
4362: =pod
4363:
4364: =item * &languagedescription()
4365:
4366: returns description of a specified language id
4367:
4368: =cut
4369:
4370: sub languagedescription {
4371: my $code=shift;
4372: return ($supported_language{$code}?'* ':'').
4373: $language{$code}.
4374: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4375: }
4376:
4377: =pod
4378:
4379: =item * &plainlanguagedescription
4380:
4381: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4382: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4383:
4384: =cut
4385:
4386: sub plainlanguagedescription {
4387: my $code=shift;
4388: return $language{$code};
4389: }
4390:
4391: =pod
4392:
4393: =item * &supportedlanguagecode
4394:
4395: Returns the supported language code (e.g. sptutf maps to pt) given a language
4396: code.
4397:
4398: =cut
4399:
4400: sub supportedlanguagecode {
4401: my $code=shift;
4402: return $supported_language{$code};
4403: }
4404:
4405: =pod
4406:
4407: =item * &latexlanguage()
4408:
4409: Given a language key code returns the correspondnig language to use
4410: to select the correct hyphenation on LaTeX printouts. This is undef if there
4411: is no supported hyphenation for the language code.
4412:
4413: =cut
4414:
4415: sub latexlanguage {
4416: my $code = shift;
4417: return $latex_language{$code};
4418: }
4419:
4420: =pod
4421:
4422: =item * &latexhyphenation()
4423:
4424: Same as above but what's supplied is the language as it might be stored
4425: in the metadata.
4426:
4427: =cut
4428:
4429: sub latexhyphenation {
4430: my $key = shift;
4431: return $latex_language_bykey{$key};
4432: }
4433:
4434: =pod
4435:
4436: =item * ©rightids()
4437:
4438: returns list of all copyrights
4439:
4440: =cut
4441:
4442: sub copyrightids {
4443: return sort(keys(%cprtag));
4444: }
4445:
4446: =pod
4447:
4448: =item * ©rightdescription()
4449:
4450: returns description of a specified copyright id
4451:
4452: =cut
4453:
4454: sub copyrightdescription {
4455: return &mt($cprtag{shift(@_)});
4456: }
4457:
4458: =pod
4459:
4460: =item * &source_copyrightids()
4461:
4462: returns list of all source copyrights
4463:
4464: =cut
4465:
4466: sub source_copyrightids {
4467: return sort(keys(%scprtag));
4468: }
4469:
4470: =pod
4471:
4472: =item * &source_copyrightdescription()
4473:
4474: returns description of a specified source copyright id
4475:
4476: =cut
4477:
4478: sub source_copyrightdescription {
4479: return &mt($scprtag{shift(@_)});
4480: }
4481:
4482: =pod
4483:
4484: =item * &filecategories()
4485:
4486: returns list of all file categories
4487:
4488: =cut
4489:
4490: sub filecategories {
4491: return sort(keys(%category_extensions));
4492: }
4493:
4494: =pod
4495:
4496: =item * &filecategorytypes()
4497:
4498: returns list of file types belonging to a given file
4499: category
4500:
4501: =cut
4502:
4503: sub filecategorytypes {
4504: my ($cat) = @_;
4505: if (ref($category_extensions{lc($cat)}) eq 'ARRAY') {
4506: return @{$category_extensions{lc($cat)}};
4507: } else {
4508: return ();
4509: }
4510: }
4511:
4512: =pod
4513:
4514: =item * &fileembstyle()
4515:
4516: returns embedding style for a specified file type
4517:
4518: =cut
4519:
4520: sub fileembstyle {
4521: return $fe{lc(shift(@_))};
4522: }
4523:
4524: sub filemimetype {
4525: return $fm{lc(shift(@_))};
4526: }
4527:
4528:
4529: sub filecategoryselect {
4530: my ($name,$value)=@_;
4531: return &select_form($value,$name,
4532: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4533: }
4534:
4535: =pod
4536:
4537: =item * &filedescription()
4538:
4539: returns description for a specified file type
4540:
4541: =cut
4542:
4543: sub filedescription {
4544: my $file_description = $fd{lc(shift())};
4545: $file_description =~ s:([\[\]]):~$1:g;
4546: return &mt($file_description);
4547: }
4548:
4549: =pod
4550:
4551: =item * &filedescriptionex()
4552:
4553: returns description for a specified file type with
4554: extra formatting
4555:
4556: =cut
4557:
4558: sub filedescriptionex {
4559: my $ex=shift;
4560: my $file_description = $fd{lc($ex)};
4561: $file_description =~ s:([\[\]]):~$1:g;
4562: return '.'.$ex.' '.&mt($file_description);
4563: }
4564:
4565: # End of .tab access
4566: =pod
4567:
4568: =back
4569:
4570: =cut
4571:
4572: # ------------------------------------------------------------------ File Types
4573: sub fileextensions {
4574: return sort(keys(%fe));
4575: }
4576:
4577: # ----------------------------------------------------------- Display Languages
4578: # returns a hash with all desired display languages
4579: #
4580:
4581: sub display_languages {
4582: my %languages=();
4583: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4584: $languages{$lang}=1;
4585: }
4586: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4587: if ($env{'form.displaylanguage'}) {
4588: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4589: $languages{$lang}=1;
4590: }
4591: }
4592: return %languages;
4593: }
4594:
4595: sub languages {
4596: my ($possible_langs) = @_;
4597: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4598: if (!ref($possible_langs)) {
4599: if( wantarray ) {
4600: return @preferred_langs;
4601: } else {
4602: return $preferred_langs[0];
4603: }
4604: }
4605: my %possibilities = map { $_ => 1 } (@$possible_langs);
4606: my @preferred_possibilities;
4607: foreach my $preferred_lang (@preferred_langs) {
4608: if (exists($possibilities{$preferred_lang})) {
4609: push(@preferred_possibilities, $preferred_lang);
4610: }
4611: }
4612: if( wantarray ) {
4613: return @preferred_possibilities;
4614: }
4615: return $preferred_possibilities[0];
4616: }
4617:
4618: sub user_lang {
4619: my ($touname,$toudom,$fromcid) = @_;
4620: my @userlangs;
4621: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4622: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4623: $env{'course.'.$fromcid.'.languages'}));
4624: } else {
4625: my %langhash = &getlangs($touname,$toudom);
4626: if ($langhash{'languages'} ne '') {
4627: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4628: } else {
4629: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4630: if ($domdefs{'lang_def'} ne '') {
4631: @userlangs = ($domdefs{'lang_def'});
4632: }
4633: }
4634: }
4635: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4636: my $user_lh = Apache::localize->get_handle(@languages);
4637: return $user_lh;
4638: }
4639:
4640:
4641: ###############################################################
4642: ## Student Answer Attempts ##
4643: ###############################################################
4644:
4645: =pod
4646:
4647: =head1 Alternate Problem Views
4648:
4649: =over 4
4650:
4651: =item * &get_previous_attempt($symb, $username, $domain, $course,
4652: $getattempt, $regexp, $gradesub, $usec, $identifier)
4653:
4654: Return string with previous attempt on problem. Arguments:
4655:
4656: =over 4
4657:
4658: =item * $symb: Problem, including path
4659:
4660: =item * $username: username of the desired student
4661:
4662: =item * $domain: domain of the desired student
4663:
4664: =item * $course: Course ID
4665:
4666: =item * $getattempt: Leave blank for all attempts, otherwise put
4667: something
4668:
4669: =item * $regexp: if string matches this regexp, the string will be
4670: sent to $gradesub
4671:
4672: =item * $gradesub: routine that processes the string if it matches $regexp
4673:
4674: =item * $usec: section of the desired student
4675:
4676: =item * $identifier: counter for student (multiple students one problem) or
4677: problem (one student; whole sequence).
4678:
4679: =back
4680:
4681: The output string is a table containing all desired attempts, if any.
4682:
4683: =cut
4684:
4685: sub get_previous_attempt {
4686: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4687: my $prevattempts='';
4688: no strict 'refs';
4689: if ($symb) {
4690: my (%returnhash)=
4691: &Apache::lonnet::restore($symb,$course,$domain,$username);
4692: if ($returnhash{'version'}) {
4693: my %lasthash=();
4694: my $version;
4695: for ($version=1;$version<=$returnhash{'version'};$version++) {
4696: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4697: if ($key =~ /\.rawrndseed$/) {
4698: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4699: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4700: } else {
4701: $lasthash{$key}=$returnhash{$version.':'.$key};
4702: }
4703: }
4704: }
4705: $prevattempts=&start_data_table().&start_data_table_header_row();
4706: $prevattempts.='<th>'.&mt('History').'</th>';
4707: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4708: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4709: foreach my $key (sort(keys(%lasthash))) {
4710: my ($ign,@parts) = split(/\./,$key);
4711: if ($#parts > 0) {
4712: my $data=$parts[-1];
4713: next if ($data eq 'foilorder');
4714: pop(@parts);
4715: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4716: if ($data eq 'type') {
4717: unless ($showsurv) {
4718: my $id = join(',',@parts);
4719: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4720: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4721: $lasthidden{$ign.'.'.$id} = 1;
4722: }
4723: }
4724: if ($identifier ne '') {
4725: my $id = join(',',@parts);
4726: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4727: $domain,$username,$usec,undef,$course) =~ /^no/) {
4728: $hidestatus{$ign.'.'.$id} = 1;
4729: }
4730: }
4731: } elsif ($data eq 'regrader') {
4732: if (($identifier ne '') && (@parts)) {
4733: my $id = join(',',@parts);
4734: $regraded{$ign.'.'.$id} = 1;
4735: }
4736: }
4737: } else {
4738: if ($#parts == 0) {
4739: $prevattempts.='<th>'.$parts[0].'</th>';
4740: } else {
4741: $prevattempts.='<th>'.$ign.'</th>';
4742: }
4743: }
4744: }
4745: $prevattempts.=&end_data_table_header_row();
4746: if ($getattempt eq '') {
4747: my (%solved,%resets,%probstatus);
4748: if (($identifier ne '') && (keys(%regraded) > 0)) {
4749: for ($version=1;$version<=$returnhash{'version'};$version++) {
4750: foreach my $id (keys(%regraded)) {
4751: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4752: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4753: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4754: push(@{$resets{$id}},$version);
4755: }
4756: }
4757: }
4758: }
4759: for ($version=1;$version<=$returnhash{'version'};$version++) {
4760: my (@hidden,@unsolved);
4761: if (%typeparts) {
4762: foreach my $id (keys(%typeparts)) {
4763: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4764: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4765: push(@hidden,$id);
4766: } elsif ($identifier ne '') {
4767: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4768: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4769: ($hidestatus{$id})) {
4770: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4771: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4772: push(@{$solved{$id}},$version);
4773: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4774: (ref($solved{$id}) eq 'ARRAY')) {
4775: my $skip;
4776: if (ref($resets{$id}) eq 'ARRAY') {
4777: foreach my $reset (@{$resets{$id}}) {
4778: if ($reset > $solved{$id}[-1]) {
4779: $skip=1;
4780: last;
4781: }
4782: }
4783: }
4784: unless ($skip) {
4785: my ($ign,$partslist) = split(/\./,$id,2);
4786: push(@unsolved,$partslist);
4787: }
4788: }
4789: }
4790: }
4791: }
4792: }
4793: $prevattempts.=&start_data_table_row().
4794: '<td>'.&mt('Transaction [_1]',$version);
4795: if (@unsolved) {
4796: $prevattempts .= '<span class="LC_nobreak"><label>'.
4797: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4798: &mt('Hide').'</label></span>';
4799: }
4800: $prevattempts .= '</td>';
4801: if (@hidden) {
4802: foreach my $key (sort(keys(%lasthash))) {
4803: next if ($key =~ /\.foilorder$/);
4804: my $hide;
4805: foreach my $id (@hidden) {
4806: if ($key =~ /^\Q$id\E/) {
4807: $hide = 1;
4808: last;
4809: }
4810: }
4811: if ($hide) {
4812: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4813: if (($data eq 'award') || ($data eq 'awarddetail')) {
4814: my $value = &format_previous_attempt_value($key,
4815: $returnhash{$version.':'.$key});
4816: $prevattempts.='<td>'.$value.' </td>';
4817: } else {
4818: $prevattempts.='<td> </td>';
4819: }
4820: } else {
4821: if ($key =~ /\./) {
4822: my $value = $returnhash{$version.':'.$key};
4823: if ($key =~ /\.rndseed$/) {
4824: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4825: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4826: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4827: }
4828: }
4829: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4830: ' </td>';
4831: } else {
4832: $prevattempts.='<td> </td>';
4833: }
4834: }
4835: }
4836: } else {
4837: foreach my $key (sort(keys(%lasthash))) {
4838: next if ($key =~ /\.foilorder$/);
4839: my $value = $returnhash{$version.':'.$key};
4840: if ($key =~ /\.rndseed$/) {
4841: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4842: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4843: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4844: }
4845: }
4846: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4847: ' </td>';
4848: }
4849: }
4850: $prevattempts.=&end_data_table_row();
4851: }
4852: }
4853: my @currhidden = keys(%lasthidden);
4854: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4855: foreach my $key (sort(keys(%lasthash))) {
4856: next if ($key =~ /\.foilorder$/);
4857: if (%typeparts) {
4858: my $hidden;
4859: foreach my $id (@currhidden) {
4860: if ($key =~ /^\Q$id\E/) {
4861: $hidden = 1;
4862: last;
4863: }
4864: }
4865: if ($hidden) {
4866: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4867: if (($data eq 'award') || ($data eq 'awarddetail')) {
4868: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4869: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4870: $value = &$gradesub($value);
4871: }
4872: $prevattempts.='<td>'. $value.' </td>';
4873: } else {
4874: $prevattempts.='<td> </td>';
4875: }
4876: } else {
4877: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4878: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4879: $value = &$gradesub($value);
4880: }
4881: $prevattempts.='<td>'.$value.' </td>';
4882: }
4883: } else {
4884: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4885: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4886: $value = &$gradesub($value);
4887: }
4888: $prevattempts.='<td>'.$value.' </td>';
4889: }
4890: }
4891: $prevattempts.= &end_data_table_row().&end_data_table();
4892: } else {
4893: my $msg;
4894: if ($symb =~ /ext\.tool$/) {
4895: $msg = &mt('No grade passed back.');
4896: } else {
4897: $msg = &mt('Nothing submitted - no attempts.');
4898: }
4899: $prevattempts=
4900: &start_data_table().&start_data_table_row().
4901: '<td>'.$msg.'</td>'.
4902: &end_data_table_row().&end_data_table();
4903: }
4904: } else {
4905: $prevattempts=
4906: &start_data_table().&start_data_table_row().
4907: '<td>'.&mt('No data.').'</td>'.
4908: &end_data_table_row().&end_data_table();
4909: }
4910: }
4911:
4912: sub format_previous_attempt_value {
4913: my ($key,$value) = @_;
4914: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4915: $value = &Apache::lonlocal::locallocaltime($value);
4916: } elsif (ref($value) eq 'ARRAY') {
4917: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
4918: } elsif ($key =~ /answerstring$/) {
4919: my %answers = &Apache::lonnet::str2hash($value);
4920: my @answer = %answers;
4921: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
4922: my @anskeys = sort(keys(%answers));
4923: if (@anskeys == 1) {
4924: my $answer = $answers{$anskeys[0]};
4925: if ($answer =~ m{\0}) {
4926: $answer =~ s{\0}{,}g;
4927: }
4928: my $tag_internal_answer_name = 'INTERNAL';
4929: if ($anskeys[0] eq $tag_internal_answer_name) {
4930: $value = $answer;
4931: } else {
4932: $value = $anskeys[0].'='.$answer;
4933: }
4934: } else {
4935: foreach my $ans (@anskeys) {
4936: my $answer = $answers{$ans};
4937: if ($answer =~ m{\0}) {
4938: $answer =~ s{\0}{,}g;
4939: }
4940: $value .= $ans.'='.$answer.'<br />';;
4941: }
4942: }
4943: } else {
4944: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
4945: }
4946: return $value;
4947: }
4948:
4949:
4950: sub relative_to_absolute {
4951: my ($url,$output)=@_;
4952: my $parser=HTML::TokeParser->new(\$output);
4953: my $token;
4954: my $thisdir=$url;
4955: my @rlinks=();
4956: while ($token=$parser->get_token) {
4957: if ($token->[0] eq 'S') {
4958: if ($token->[1] eq 'a') {
4959: if ($token->[2]->{'href'}) {
4960: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4961: }
4962: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4963: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4964: } elsif ($token->[1] eq 'base') {
4965: $thisdir=$token->[2]->{'href'};
4966: }
4967: }
4968: }
4969: $thisdir=~s-/[^/]*$--;
4970: foreach my $link (@rlinks) {
4971: unless (($link=~/^https?\:\/\//i) ||
4972: ($link=~/^\//) ||
4973: ($link=~/^javascript:/i) ||
4974: ($link=~/^mailto:/i) ||
4975: ($link=~/^\#/)) {
4976: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4977: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4978: }
4979: }
4980: # -------------------------------------------------- Deal with Applet codebases
4981: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4982: return $output;
4983: }
4984:
4985: =pod
4986:
4987: =item * &get_student_view()
4988:
4989: show a snapshot of what student was looking at
4990:
4991: =cut
4992:
4993: sub get_student_view {
4994: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4995: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4996: my (%form);
4997: my @elements=('symb','courseid','domain','username');
4998: foreach my $element (@elements) {
4999: $form{'grade_'.$element}=eval '$'.$element #'
5000: }
5001: if (defined($moreenv)) {
5002: %form=(%form,%{$moreenv});
5003: }
5004: if (defined($target)) { $form{'grade_target'} = $target; }
5005: $feedurl=&Apache::lonnet::clutter($feedurl);
5006: if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
5007: $feedurl =~ s{^/adm/wrapper}{};
5008: }
5009: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
5010: $userview=~s/\<body[^\>]*\>//gi;
5011: $userview=~s/\<\/body\>//gi;
5012: $userview=~s/\<html\>//gi;
5013: $userview=~s/\<\/html\>//gi;
5014: $userview=~s/\<head\>//gi;
5015: $userview=~s/\<\/head\>//gi;
5016: $userview=~s/action\s*\=/would_be_action\=/gi;
5017: $userview=&relative_to_absolute($feedurl,$userview);
5018: if (wantarray) {
5019: return ($userview,$response);
5020: } else {
5021: return $userview;
5022: }
5023: }
5024:
5025: sub get_student_view_with_retries {
5026: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
5027:
5028: my $ok = 0; # True if we got a good response.
5029: my $content;
5030: my $response;
5031:
5032: # Try to get the student_view done. within the retries count:
5033:
5034: do {
5035: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
5036: $ok = $response->is_success;
5037: if (!$ok) {
5038: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
5039: }
5040: $retries--;
5041: } while (!$ok && ($retries > 0));
5042:
5043: if (!$ok) {
5044: $content = ''; # On error return an empty content.
5045: }
5046: if (wantarray) {
5047: return ($content, $response);
5048: } else {
5049: return $content;
5050: }
5051: }
5052:
5053: sub css_links {
5054: my ($currsymb,$level) = @_;
5055: my ($links,@symbs,%cssrefs,%httpref);
5056: if ($level eq 'map') {
5057: my $navmap = Apache::lonnavmaps::navmap->new();
5058: if (ref($navmap)) {
5059: my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
5060: my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
5061: foreach my $res (@resources) {
5062: if (ref($res) && $res->symb()) {
5063: push(@symbs,$res->symb());
5064: }
5065: }
5066: }
5067: } else {
5068: @symbs = ($currsymb);
5069: }
5070: foreach my $symb (@symbs) {
5071: my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
5072: if ($css_href =~ /\S/) {
5073: unless ($css_href =~ m{https?://}) {
5074: my $url = (&Apache::lonnet::decode_symb($symb))[-1];
5075: my $proburl = &Apache::lonnet::clutter($url);
5076: my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
5077: unless ($css_href =~ m{^/}) {
5078: $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
5079: }
5080: if ($css_href =~ m{^/(res|uploaded)/}) {
5081: unless (($httpref{'httpref.'.$css_href}) ||
5082: (&Apache::lonnet::is_on_map($css_href))) {
5083: my $thisurl = $proburl;
5084: if ($env{'httpref.'.$proburl}) {
5085: $thisurl = $env{'httpref.'.$proburl};
5086: }
5087: $httpref{'httpref.'.$css_href} = $thisurl;
5088: }
5089: }
5090: }
5091: $cssrefs{$css_href} = 1;
5092: }
5093: }
5094: if (keys(%httpref)) {
5095: &Apache::lonnet::appenv(\%httpref);
5096: }
5097: if (keys(%cssrefs)) {
5098: foreach my $css_href (keys(%cssrefs)) {
5099: next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
5100: $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
5101: }
5102: }
5103: return $links;
5104: }
5105:
5106: =pod
5107:
5108: =item * &get_student_answers()
5109:
5110: show a snapshot of how student was answering problem
5111:
5112: =cut
5113:
5114: sub get_student_answers {
5115: my ($symb,$username,$domain,$courseid,%form) = @_;
5116: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
5117: my (%moreenv);
5118: my @elements=('symb','courseid','domain','username');
5119: foreach my $element (@elements) {
5120: $moreenv{'grade_'.$element}=eval '$'.$element #'
5121: }
5122: $moreenv{'grade_target'}='answer';
5123: %moreenv=(%form,%moreenv);
5124: $feedurl = &Apache::lonnet::clutter($feedurl);
5125: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
5126: return $userview;
5127: }
5128:
5129: =pod
5130:
5131: =item * &submlink()
5132:
5133: Inputs: $text $uname $udom $symb $target
5134:
5135: Returns: A link to grades.pm such as to see the SUBM view of a student
5136:
5137: =cut
5138:
5139: ###############################################
5140: sub submlink {
5141: my ($text,$uname,$udom,$symb,$target)=@_;
5142: if (!($uname && $udom)) {
5143: (my $cursymb, my $courseid,$udom,$uname)=
5144: &Apache::lonnet::whichuser($symb);
5145: if (!$symb) { $symb=$cursymb; }
5146: }
5147: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5148: $symb=&escape($symb);
5149: if ($target) { $target=" target=\"$target\""; }
5150: return
5151: '<a href="/adm/grades?command=submission'.
5152: '&symb='.$symb.
5153: '&student='.$uname.
5154: '&userdom='.$udom.'"'.
5155: $target.'>'.$text.'</a>';
5156: }
5157: ##############################################
5158:
5159: =pod
5160:
5161: =item * &pgrdlink()
5162:
5163: Inputs: $text $uname $udom $symb $target
5164:
5165: Returns: A link to grades.pm such as to see the PGRD view of a student
5166:
5167: =cut
5168:
5169: ###############################################
5170: sub pgrdlink {
5171: my $link=&submlink(@_);
5172: $link=~s/(&command=submission)/$1&showgrading=yes/;
5173: return $link;
5174: }
5175: ##############################################
5176:
5177: =pod
5178:
5179: =item * &pprmlink()
5180:
5181: Inputs: $text $uname $udom $symb $target
5182:
5183: Returns: A link to parmset.pm such as to see the PPRM view of a
5184: student and a specific resource
5185:
5186: =cut
5187:
5188: ###############################################
5189: sub pprmlink {
5190: my ($text,$uname,$udom,$symb,$target)=@_;
5191: if (!($uname && $udom)) {
5192: (my $cursymb, my $courseid,$udom,$uname)=
5193: &Apache::lonnet::whichuser($symb);
5194: if (!$symb) { $symb=$cursymb; }
5195: }
5196: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5197: $symb=&escape($symb);
5198: if ($target) { $target="target=\"$target\""; }
5199: return '<a href="/adm/parmset?command=set&'.
5200: 'symb='.$symb.'&uname='.$uname.
5201: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
5202: }
5203: ##############################################
5204:
5205: =pod
5206:
5207: =back
5208:
5209: =cut
5210:
5211: ###############################################
5212:
5213:
5214: sub timehash {
5215: my ($thistime) = @_;
5216: my $timezone = &Apache::lonlocal::gettimezone();
5217: my $dt = DateTime->from_epoch(epoch => $thistime)
5218: ->set_time_zone($timezone);
5219: my $wday = $dt->day_of_week();
5220: if ($wday == 7) { $wday = 0; }
5221: return ( 'second' => $dt->second(),
5222: 'minute' => $dt->minute(),
5223: 'hour' => $dt->hour(),
5224: 'day' => $dt->day_of_month(),
5225: 'month' => $dt->month(),
5226: 'year' => $dt->year(),
5227: 'weekday' => $wday,
5228: 'dayyear' => $dt->day_of_year(),
5229: 'dlsav' => $dt->is_dst() );
5230: }
5231:
5232: sub utc_string {
5233: my ($date)=@_;
5234: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
5235: }
5236:
5237: sub maketime {
5238: my %th=@_;
5239: my ($epoch_time,$timezone,$dt);
5240: $timezone = &Apache::lonlocal::gettimezone();
5241: eval {
5242: $dt = DateTime->new( year => $th{'year'},
5243: month => $th{'month'},
5244: day => $th{'day'},
5245: hour => $th{'hour'},
5246: minute => $th{'minute'},
5247: second => $th{'second'},
5248: time_zone => $timezone,
5249: );
5250: };
5251: if (!$@) {
5252: $epoch_time = $dt->epoch;
5253: if ($epoch_time) {
5254: return $epoch_time;
5255: }
5256: }
5257: return POSIX::mktime(
5258: ($th{'seconds'},$th{'minutes'},$th{'hours'},
5259: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
5260: }
5261:
5262: #########################################
5263:
5264: sub findallcourses {
5265: my ($roles,$uname,$udom) = @_;
5266: my %roles;
5267: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
5268: my %courses;
5269: my $now=time;
5270: if (!defined($uname)) {
5271: $uname = $env{'user.name'};
5272: }
5273: if (!defined($udom)) {
5274: $udom = $env{'user.domain'};
5275: }
5276: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
5277: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
5278: if (!%roles) {
5279: %roles = (
5280: cc => 1,
5281: co => 1,
5282: in => 1,
5283: ep => 1,
5284: ta => 1,
5285: cr => 1,
5286: st => 1,
5287: );
5288: }
5289: foreach my $entry (keys(%roleshash)) {
5290: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
5291: if ($trole =~ /^cr/) {
5292: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
5293: } else {
5294: next if (!exists($roles{$trole}));
5295: }
5296: if ($tend) {
5297: next if ($tend < $now);
5298: }
5299: if ($tstart) {
5300: next if ($tstart > $now);
5301: }
5302: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
5303: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
5304: my $value = $trole.'/'.$cdom.'/';
5305: if ($secpart eq '') {
5306: ($cnum,$role) = split(/_/,$cnumpart);
5307: $sec = 'none';
5308: $value .= $cnum.'/';
5309: } else {
5310: $cnum = $cnumpart;
5311: ($sec,$role) = split(/_/,$secpart);
5312: $value .= $cnum.'/'.$sec;
5313: }
5314: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5315: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5316: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5317: }
5318: } else {
5319: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5320: }
5321: }
5322: } else {
5323: foreach my $key (keys(%env)) {
5324: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
5325: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
5326: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
5327: next if ($role eq 'ca' || $role eq 'aa');
5328: next if (%roles && !exists($roles{$role}));
5329: my ($starttime,$endtime)=split(/\./,$env{$key});
5330: my $active=1;
5331: if ($starttime) {
5332: if ($now<$starttime) { $active=0; }
5333: }
5334: if ($endtime) {
5335: if ($now>$endtime) { $active=0; }
5336: }
5337: if ($active) {
5338: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
5339: if ($sec eq '') {
5340: $sec = 'none';
5341: } else {
5342: $value .= $sec;
5343: }
5344: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5345: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5346: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5347: }
5348: } else {
5349: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5350: }
5351: }
5352: }
5353: }
5354: }
5355: return %courses;
5356: }
5357:
5358: ###############################################
5359:
5360: sub blockcheck {
5361: my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5362: unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
5363: my ($has_evb,$check_ipaccess);
5364: my $dom = $env{'user.domain'};
5365: if ($env{'request.course.id'}) {
5366: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5367: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5368: my $checkrole = "cm./$cdom/$cnum";
5369: my $sec = $env{'request.course.sec'};
5370: if ($sec ne '') {
5371: $checkrole .= "/$sec";
5372: }
5373: if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
5374: ($env{'request.role'} !~ /^st/)) {
5375: $has_evb = 1;
5376: }
5377: unless ($has_evb) {
5378: if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
5379: ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
5380: if ($udom eq $cdom) {
5381: $check_ipaccess = 1;
5382: }
5383: }
5384: }
5385: } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
5386: ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
5387: my $checkrole;
5388: if ($env{'request.role.domain'} eq '') {
5389: $checkrole = "cm./$env{'user.domain'}/";
5390: } else {
5391: $checkrole = "cm./$env{'request.role.domain'}/";
5392: }
5393: if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
5394: $has_evb = 1;
5395: }
5396: }
5397: unless ($has_evb || $check_ipaccess) {
5398: my @machinedoms = &Apache::lonnet::current_machine_domains();
5399: if (($dom eq 'public') && ($activity eq 'port')) {
5400: $dom = $udom;
5401: }
5402: if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
5403: $check_ipaccess = 1;
5404: } else {
5405: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
5406: my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
5407: my $prim = &Apache::lonnet::domain($dom,'primary');
5408: my $intdom = &Apache::lonnet::internet_dom($prim);
5409: if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
5410: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
5411: $check_ipaccess = 1;
5412: }
5413: }
5414: }
5415: }
5416: if ($check_ipaccess) {
5417: my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
5418: unless (defined($cached)) {
5419: my %domconfig =
5420: &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
5421: $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
5422: }
5423: if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
5424: foreach my $id (keys(%{$ipaccessref})) {
5425: if (ref($ipaccessref->{$id}) eq 'HASH') {
5426: my $range = $ipaccessref->{$id}->{'ip'};
5427: if ($range) {
5428: if (&Apache::lonnet::ip_match($clientip,$range)) {
5429: if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
5430: if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
5431: return ('','','',$id,$dom);
5432: last;
5433: }
5434: }
5435: }
5436: }
5437: }
5438: }
5439: }
5440: }
5441: if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5442: return ();
5443: }
5444: }
5445: if (defined($udom) && defined($uname)) {
5446: # If uname and udom are for a course, check for blocks in the course.
5447: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
5448: my ($startblock,$endblock,$triggerblock) =
5449: &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
5450: return ($startblock,$endblock,$triggerblock);
5451: }
5452: } else {
5453: $udom = $env{'user.domain'};
5454: $uname = $env{'user.name'};
5455: }
5456:
5457: my $startblock = 0;
5458: my $endblock = 0;
5459: my $triggerblock = '';
5460: my %live_courses;
5461: unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5462: %live_courses = &findallcourses(undef,$uname,$udom);
5463: }
5464:
5465: # If uname is for a user, and activity is course-specific, i.e.,
5466: # boards, chat or groups, check for blocking in current course only.
5467:
5468: if (($activity eq 'boards' || $activity eq 'chat' ||
5469: $activity eq 'groups' || $activity eq 'printout' ||
5470: $activity eq 'search' || $activity eq 'reinit' ||
5471: $activity eq 'alert') &&
5472: ($env{'request.course.id'})) {
5473: foreach my $key (keys(%live_courses)) {
5474: if ($key ne $env{'request.course.id'}) {
5475: delete($live_courses{$key});
5476: }
5477: }
5478: }
5479:
5480: my $otheruser = 0;
5481: my %own_courses;
5482: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
5483: # Resource belongs to user other than current user.
5484: $otheruser = 1;
5485: # Gather courses for current user
5486: %own_courses =
5487: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
5488: }
5489:
5490: # Gather active course roles - course coordinator, instructor,
5491: # exam proctor, ta, student, or custom role.
5492:
5493: foreach my $course (keys(%live_courses)) {
5494: my ($cdom,$cnum);
5495: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5496: $cdom = $env{'course.'.$course.'.domain'};
5497: $cnum = $env{'course.'.$course.'.num'};
5498: } else {
5499: ($cdom,$cnum) = split(/_/,$course);
5500: }
5501: my $no_ownblock = 0;
5502: my $no_userblock = 0;
5503: if ($otheruser && $activity ne 'com') {
5504: # Check if current user has 'evb' priv for this
5505: if (defined($own_courses{$course})) {
5506: foreach my $sec (keys(%{$own_courses{$course}})) {
5507: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5508: if ($sec ne 'none') {
5509: $checkrole .= '/'.$sec;
5510: }
5511: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5512: $no_ownblock = 1;
5513: last;
5514: }
5515: }
5516: }
5517: # if they have 'evb' priv and are currently not playing student
5518: next if (($no_ownblock) &&
5519: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5520: }
5521: foreach my $sec (keys(%{$live_courses{$course}})) {
5522: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5523: if ($sec ne 'none') {
5524: $checkrole .= '/'.$sec;
5525: }
5526: if ($otheruser) {
5527: # Resource belongs to user other than current user.
5528: # Assemble privs for that user, and check for 'evb' priv.
5529: my (%allroles,%userroles);
5530: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5531: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5532: my ($trole,$tdom,$tnum,$tsec);
5533: if ($entry =~ /^cr/) {
5534: ($trole,$tdom,$tnum,$tsec) =
5535: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5536: } else {
5537: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5538: }
5539: my ($spec,$area,$trest);
5540: $area = '/'.$tdom.'/'.$tnum;
5541: $trest = $tnum;
5542: if ($tsec ne '') {
5543: $area .= '/'.$tsec;
5544: $trest .= '/'.$tsec;
5545: }
5546: $spec = $trole.'.'.$area;
5547: if ($trole =~ /^cr/) {
5548: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5549: $tdom,$spec,$trest,$area);
5550: } else {
5551: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5552: $tdom,$spec,$trest,$area);
5553: }
5554: }
5555: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5556: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5557: if ($1) {
5558: $no_userblock = 1;
5559: last;
5560: }
5561: }
5562: }
5563: } else {
5564: # Resource belongs to current user
5565: # Check for 'evb' priv via lonnet::allowed().
5566: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5567: $no_ownblock = 1;
5568: last;
5569: }
5570: }
5571: }
5572: # if they have the evb priv and are currently not playing student
5573: next if (($no_ownblock) &&
5574: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5575: next if ($no_userblock);
5576:
5577: # Retrieve blocking times and identity of blocker for course
5578: # of specified user, unless user has 'evb' privilege.
5579:
5580: my ($start,$end,$trigger) =
5581: &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
5582: if (($start != 0) &&
5583: (($startblock == 0) || ($startblock > $start))) {
5584: $startblock = $start;
5585: if ($trigger ne '') {
5586: $triggerblock = $trigger;
5587: }
5588: }
5589: if (($end != 0) &&
5590: (($endblock == 0) || ($endblock < $end))) {
5591: $endblock = $end;
5592: if ($trigger ne '') {
5593: $triggerblock = $trigger;
5594: }
5595: }
5596: }
5597: return ($startblock,$endblock,$triggerblock);
5598: }
5599:
5600: sub get_blocks {
5601: my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
5602: my $startblock = 0;
5603: my $endblock = 0;
5604: my $triggerblock = '';
5605: my $course = $cdom.'_'.$cnum;
5606: $setters->{$course} = {};
5607: $setters->{$course}{'staff'} = [];
5608: $setters->{$course}{'times'} = [];
5609: $setters->{$course}{'triggers'} = [];
5610: my (@blockers,%triggered);
5611: my $now = time;
5612: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5613: if ($activity eq 'docs') {
5614: my ($blocked,$nosymbcache,$noenccheck);
5615: if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
5616: $blocked = 1;
5617: $nosymbcache = 1;
5618: $noenccheck = 1;
5619: }
5620: @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
5621: foreach my $block (@blockers) {
5622: if ($block =~ /^firstaccess____(.+)$/) {
5623: my $item = $1;
5624: my $type = 'map';
5625: my $timersymb = $item;
5626: if ($item eq 'course') {
5627: $type = 'course';
5628: } elsif ($item =~ /___\d+___/) {
5629: $type = 'resource';
5630: } else {
5631: $timersymb = &Apache::lonnet::symbread($item);
5632: }
5633: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5634: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5635: $triggered{$block} = {
5636: start => $start,
5637: end => $end,
5638: type => $type,
5639: };
5640: }
5641: }
5642: } else {
5643: foreach my $block (keys(%commblocks)) {
5644: if ($block =~ m/^(\d+)____(\d+)$/) {
5645: my ($start,$end) = ($1,$2);
5646: if ($start <= time && $end >= time) {
5647: if (ref($commblocks{$block}) eq 'HASH') {
5648: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5649: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5650: unless(grep(/^\Q$block\E$/,@blockers)) {
5651: push(@blockers,$block);
5652: }
5653: }
5654: }
5655: }
5656: }
5657: } elsif ($block =~ /^firstaccess____(.+)$/) {
5658: my $item = $1;
5659: my $timersymb = $item;
5660: my $type = 'map';
5661: if ($item eq 'course') {
5662: $type = 'course';
5663: } elsif ($item =~ /___\d+___/) {
5664: $type = 'resource';
5665: } else {
5666: $timersymb = &Apache::lonnet::symbread($item);
5667: }
5668: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5669: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5670: if ($start && $end) {
5671: if (($start <= time) && ($end >= time)) {
5672: if (ref($commblocks{$block}) eq 'HASH') {
5673: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5674: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5675: unless(grep(/^\Q$block\E$/,@blockers)) {
5676: push(@blockers,$block);
5677: $triggered{$block} = {
5678: start => $start,
5679: end => $end,
5680: type => $type,
5681: };
5682: }
5683: }
5684: }
5685: }
5686: }
5687: }
5688: }
5689: }
5690: }
5691: foreach my $blocker (@blockers) {
5692: my ($staff_name,$staff_dom,$title,$blocks) =
5693: &parse_block_record($commblocks{$blocker});
5694: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5695: my ($start,$end,$triggertype);
5696: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5697: ($start,$end) = ($1,$2);
5698: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5699: $start = $triggered{$blocker}{'start'};
5700: $end = $triggered{$blocker}{'end'};
5701: $triggertype = $triggered{$blocker}{'type'};
5702: }
5703: if ($start) {
5704: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5705: if ($triggertype) {
5706: push(@{$$setters{$course}{'triggers'}},$triggertype);
5707: } else {
5708: push(@{$$setters{$course}{'triggers'}},0);
5709: }
5710: if ( ($startblock == 0) || ($startblock > $start) ) {
5711: $startblock = $start;
5712: if ($triggertype) {
5713: $triggerblock = $blocker;
5714: }
5715: }
5716: if ( ($endblock == 0) || ($endblock < $end) ) {
5717: $endblock = $end;
5718: if ($triggertype) {
5719: $triggerblock = $blocker;
5720: }
5721: }
5722: }
5723: }
5724: return ($startblock,$endblock,$triggerblock);
5725: }
5726:
5727: sub parse_block_record {
5728: my ($record) = @_;
5729: my ($setuname,$setudom,$title,$blocks);
5730: if (ref($record) eq 'HASH') {
5731: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5732: $title = &unescape($record->{'event'});
5733: $blocks = $record->{'blocks'};
5734: } else {
5735: my @data = split(/:/,$record,3);
5736: if (scalar(@data) eq 2) {
5737: $title = $data[1];
5738: ($setuname,$setudom) = split(/@/,$data[0]);
5739: } else {
5740: ($setuname,$setudom,$title) = @data;
5741: }
5742: $blocks = { 'com' => 'on' };
5743: }
5744: return ($setuname,$setudom,$title,$blocks);
5745: }
5746:
5747: sub blocking_status {
5748: my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5749: my %setters;
5750:
5751: # check for active blocking
5752: if ($clientip eq '') {
5753: $clientip = &Apache::lonnet::get_requestor_ip();
5754: }
5755: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
5756: &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
5757: my $blocked = 0;
5758: if (($startblock && $endblock) || ($by_ip)) {
5759: $blocked = 1;
5760: }
5761:
5762: # caller just wants to know whether a block is active
5763: if (!wantarray) { return $blocked; }
5764:
5765: # build a link to a popup window containing the details
5766: my $querystring = "?activity=$activity";
5767: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
5768: if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
5769: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5770: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5771: } elsif ($activity eq 'docs') {
5772: my $showurl = &Apache::lonenc::check_encrypt($url);
5773: $querystring .= '&url='.&HTML::Entities::encode($showurl,'\'&"<>');
5774: if ($symb) {
5775: my $showsymb = &Apache::lonenc::check_encrypt($symb);
5776: $querystring .= '&symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
5777: }
5778: }
5779:
5780: my $output .= <<'END_MYBLOCK';
5781: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5782: var options = "width=" + w + ",height=" + h + ",";
5783: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5784: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5785: var newWin = window.open(url, wdwName, options);
5786: newWin.focus();
5787: }
5788: END_MYBLOCK
5789:
5790: $output = Apache::lonhtmlcommon::scripttag($output);
5791:
5792: my $popupUrl = "/adm/blockingstatus/$querystring";
5793: my $text = &mt('Communication Blocked');
5794: my $class = 'LC_comblock';
5795: if ($activity eq 'docs') {
5796: $text = &mt('Content Access Blocked');
5797: $class = '';
5798: } elsif ($activity eq 'printout') {
5799: $text = &mt('Printing Blocked');
5800: } elsif ($activity eq 'passwd') {
5801: $text = &mt('Password Changing Blocked');
5802: } elsif ($activity eq 'grades') {
5803: $text = &mt('Gradebook Blocked');
5804: } elsif ($activity eq 'search') {
5805: $text = &mt('Search Blocked');
5806: } elsif ($activity eq 'alert') {
5807: $text = &mt('Checking Critical Messages Blocked');
5808: } elsif ($activity eq 'reinit') {
5809: $text = &mt('Checking Course Update Blocked');
5810: } elsif ($activity eq 'about') {
5811: $text = &mt('Access to User Information Pages Blocked');
5812: } elsif ($activity eq 'wishlist') {
5813: $text = &mt('Access to Stored Links Blocked');
5814: } elsif ($activity eq 'annotate') {
5815: $text = &mt('Access to Annotations Blocked');
5816: }
5817: $output .= <<"END_BLOCK";
5818: <div class='$class'>
5819: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5820: title='$text'>
5821: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5822: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5823: title='$text'>$text</a>
5824: </div>
5825:
5826: END_BLOCK
5827:
5828: return ($blocked, $output);
5829: }
5830:
5831: ###############################################
5832:
5833: sub check_ip_acc {
5834: my ($acc,$clientip)=@_;
5835: &Apache::lonxml::debug("acc is $acc");
5836: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5837: return 1;
5838: }
5839: my ($ip,$allowed);
5840: if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
5841: ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
5842: $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
5843: } else {
5844: my $remote_ip = &Apache::lonnet::get_requestor_ip();
5845: $ip = $remote_ip || $env{'request.host'} || $clientip;
5846: }
5847:
5848: my $name;
5849: my %access = (
5850: allowfrom => 1,
5851: denyfrom => 0,
5852: );
5853: my @allows;
5854: my @denies;
5855: foreach my $item (split(',',$acc)) {
5856: $item =~ s/^\s*//;
5857: $item =~ s/\s*$//;
5858: my $pattern;
5859: if ($item =~ /^\!(.+)$/) {
5860: push(@denies,$1);
5861: } else {
5862: push(@allows,$item);
5863: }
5864: }
5865: my $numdenies = scalar(@denies);
5866: my $numallows = scalar(@allows);
5867: my $count = 0;
5868: foreach my $pattern (@denies,@allows) {
5869: $count ++;
5870: my $acctype = 'allowfrom';
5871: if ($count <= $numdenies) {
5872: $acctype = 'denyfrom';
5873: }
5874: if ($pattern =~ /\*$/) {
5875: #35.8.*
5876: $pattern=~s/\*//;
5877: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5878: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5879: #35.8.3.[34-56]
5880: my $low=$2;
5881: my $high=$3;
5882: $pattern=$1;
5883: if ($ip =~ /^\Q$pattern\E/) {
5884: my $last=(split(/\./,$ip))[3];
5885: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5886: }
5887: } elsif ($pattern =~ /^\*/) {
5888: #*.msu.edu
5889: $pattern=~s/\*//;
5890: if (!defined($name)) {
5891: use Socket;
5892: my $netaddr=inet_aton($ip);
5893: ($name)=gethostbyaddr($netaddr,AF_INET);
5894: }
5895: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5896: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5897: #127.0.0.1
5898: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5899: } else {
5900: #some.name.com
5901: if (!defined($name)) {
5902: use Socket;
5903: my $netaddr=inet_aton($ip);
5904: ($name)=gethostbyaddr($netaddr,AF_INET);
5905: }
5906: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5907: }
5908: if ($allowed =~ /^(0|1)$/) { last; }
5909: }
5910: if ($allowed eq '') {
5911: if ($numdenies && !$numallows) {
5912: $allowed = 1;
5913: } else {
5914: $allowed = 0;
5915: }
5916: }
5917: return $allowed;
5918: }
5919:
5920: ###############################################
5921:
5922: =pod
5923:
5924: =head1 Domain Template Functions
5925:
5926: =over 4
5927:
5928: =item * &determinedomain()
5929:
5930: Inputs: $domain (usually will be undef)
5931:
5932: Returns: Determines which domain should be used for designs
5933:
5934: =cut
5935:
5936: ###############################################
5937: sub determinedomain {
5938: my $domain=shift;
5939: if (! $domain) {
5940: # Determine domain if we have not been given one
5941: $domain = &Apache::lonnet::default_login_domain();
5942: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5943: if ($env{'request.role.domain'}) {
5944: $domain=$env{'request.role.domain'};
5945: }
5946: }
5947: return $domain;
5948: }
5949: ###############################################
5950:
5951: sub devalidate_domconfig_cache {
5952: my ($udom)=@_;
5953: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5954: }
5955:
5956: # ---------------------- Get domain configuration for a domain
5957: sub get_domainconf {
5958: my ($udom) = @_;
5959: my $cachetime=1800;
5960: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5961: if (defined($cached)) { return %{$result}; }
5962:
5963: my %domconfig = &Apache::lonnet::get_dom('configuration',
5964: ['login','rolecolors','autoenroll'],$udom);
5965: my (%designhash,%legacy);
5966: if (keys(%domconfig) > 0) {
5967: if (ref($domconfig{'login'}) eq 'HASH') {
5968: if (keys(%{$domconfig{'login'}})) {
5969: foreach my $key (keys(%{$domconfig{'login'}})) {
5970: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5971: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5972: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5973: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5974: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5975: if ($key eq 'loginvia') {
5976: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5977: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5978: $designhash{$udom.'.login.loginvia'} = $server;
5979: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5980:
5981: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5982: } else {
5983: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5984: }
5985: }
5986: } elsif ($key eq 'headtag') {
5987: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5988: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5989: }
5990: }
5991: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5992: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5993: }
5994: }
5995: }
5996: }
5997: } elsif ($key eq 'saml') {
5998: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5999: foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
6000: if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
6001: $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
6002: foreach my $item ('text','img','alt','url','title','notsso') {
6003: $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
6004: }
6005: }
6006: }
6007: }
6008: } else {
6009: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
6010: $designhash{$udom.'.login.'.$key.'_'.$img} =
6011: $domconfig{'login'}{$key}{$img};
6012: }
6013: }
6014: } else {
6015: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
6016: }
6017: }
6018: } else {
6019: $legacy{'login'} = 1;
6020: }
6021: } else {
6022: $legacy{'login'} = 1;
6023: }
6024: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
6025: if (keys(%{$domconfig{'rolecolors'}})) {
6026: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
6027: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
6028: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
6029: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
6030: }
6031: }
6032: }
6033: } else {
6034: $legacy{'rolecolors'} = 1;
6035: }
6036: } else {
6037: $legacy{'rolecolors'} = 1;
6038: }
6039: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6040: if ($domconfig{'autoenroll'}{'co-owners'}) {
6041: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
6042: }
6043: }
6044: if (keys(%legacy) > 0) {
6045: my %legacyhash = &get_legacy_domconf($udom);
6046: foreach my $item (keys(%legacyhash)) {
6047: if ($item =~ /^\Q$udom\E\.login/) {
6048: if ($legacy{'login'}) {
6049: $designhash{$item} = $legacyhash{$item};
6050: }
6051: } else {
6052: if ($legacy{'rolecolors'}) {
6053: $designhash{$item} = $legacyhash{$item};
6054: }
6055: }
6056: }
6057: }
6058: } else {
6059: %designhash = &get_legacy_domconf($udom);
6060: }
6061: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
6062: $cachetime);
6063: return %designhash;
6064: }
6065:
6066: sub get_legacy_domconf {
6067: my ($udom) = @_;
6068: my %legacyhash;
6069: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
6070: my $designfile = $designdir.'/'.$udom.'.tab';
6071: if (-e $designfile) {
6072: if ( open (my $fh,'<',$designfile) ) {
6073: while (my $line = <$fh>) {
6074: next if ($line =~ /^\#/);
6075: chomp($line);
6076: my ($key,$val)=(split(/\=/,$line));
6077: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
6078: }
6079: close($fh);
6080: }
6081: }
6082: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
6083: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
6084: }
6085: return %legacyhash;
6086: }
6087:
6088: =pod
6089:
6090: =item * &domainlogo()
6091:
6092: Inputs: $domain (usually will be undef)
6093:
6094: Returns: A link to a domain logo, if the domain logo exists.
6095: If the domain logo does not exist, a description of the domain.
6096:
6097: =cut
6098:
6099: ###############################################
6100: sub domainlogo {
6101: my $domain = &determinedomain(shift);
6102: my %designhash = &get_domainconf($domain);
6103: # See if there is a logo
6104: if ($designhash{$domain.'.login.domlogo'} ne '') {
6105: my $imgsrc = $designhash{$domain.'.login.domlogo'};
6106: if ($imgsrc =~ m{^/(adm|res)/}) {
6107: if ($imgsrc =~ m{^/res/}) {
6108: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
6109: &Apache::lonnet::repcopy($local_name);
6110: }
6111: $imgsrc = &lonhttpdurl($imgsrc);
6112: }
6113: my $alttext = $domain;
6114: if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
6115: $alttext = $designhash{$domain.'.login.alttext_domlogo'};
6116: }
6117: return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
6118: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
6119: return &Apache::lonnet::domain($domain,'description');
6120: } else {
6121: return '';
6122: }
6123: }
6124: ##############################################
6125:
6126: =pod
6127:
6128: =item * &designparm()
6129:
6130: Inputs: $which parameter; $domain (usually will be undef)
6131:
6132: Returns: value of designparamter $which
6133:
6134: =cut
6135:
6136:
6137: ##############################################
6138: sub designparm {
6139: my ($which,$domain)=@_;
6140: if (exists($env{'environment.color.'.$which})) {
6141: return $env{'environment.color.'.$which};
6142: }
6143: $domain=&determinedomain($domain);
6144: my %domdesign;
6145: unless ($domain eq 'public') {
6146: %domdesign = &get_domainconf($domain);
6147: }
6148: my $output;
6149: if ($domdesign{$domain.'.'.$which} ne '') {
6150: $output = $domdesign{$domain.'.'.$which};
6151: } else {
6152: $output = $defaultdesign{$which};
6153: }
6154: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
6155: ($which =~ /login\.(img|logo|domlogo|login)/)) {
6156: if ($output =~ m{^/(adm|res)/}) {
6157: if ($output =~ m{^/res/}) {
6158: my $local_name = &Apache::lonnet::filelocation('',$output);
6159: &Apache::lonnet::repcopy($local_name);
6160: }
6161: $output = &lonhttpdurl($output);
6162: }
6163: }
6164: return $output;
6165: }
6166:
6167: ##############################################
6168: =pod
6169:
6170: =item * &authorspace()
6171:
6172: Inputs: $url (usually will be undef).
6173:
6174: Returns: Path to Authoring Space containing the resource or
6175: directory being viewed (or for which action is being taken).
6176: If $url is provided, and begins /priv/<domain>/<uname>
6177: the path will be that portion of the $context argument.
6178: Otherwise the path will be for the author space of the current
6179: user when the current role is author, or for that of the
6180: co-author/assistant co-author space when the current role
6181: is co-author or assistant co-author.
6182:
6183: =cut
6184:
6185: sub authorspace {
6186: my ($url) = @_;
6187: if ($url ne '') {
6188: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
6189: return $1;
6190: }
6191: }
6192: my $caname = '';
6193: my $cadom = '';
6194: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
6195: ($cadom,$caname) =
6196: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
6197: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
6198: $caname = $env{'user.name'};
6199: $cadom = $env{'user.domain'};
6200: }
6201: if (($caname ne '') && ($cadom ne '')) {
6202: return "/priv/$cadom/$caname/";
6203: }
6204: return;
6205: }
6206:
6207: ##############################################
6208: =pod
6209:
6210: =item * &head_subbox()
6211:
6212: Inputs: $content (contains HTML code with page functions, etc.)
6213:
6214: Returns: HTML div with $content
6215: To be included in page header
6216:
6217: =cut
6218:
6219: sub head_subbox {
6220: my ($content)=@_;
6221: my $output =
6222: '<div class="LC_head_subbox">'
6223: .$content
6224: .'</div>'
6225: }
6226:
6227: ##############################################
6228: =pod
6229:
6230: =item * &CSTR_pageheader()
6231:
6232: Input: (optional) filename from which breadcrumb trail is built.
6233: In most cases no input as needed, as $env{'request.filename'}
6234: is appropriate for use in building the breadcrumb trail.
6235: frameset flag
6236: If page header is being requested for use in a frameset, then
6237: the second (option) argument -- frameset will be true, and
6238: the target attribute set for links should be target="_parent".
6239:
6240: Returns: HTML div with CSTR path and recent box
6241: To be included on Authoring Space pages
6242:
6243: =cut
6244:
6245: sub CSTR_pageheader {
6246: my ($trailfile,$frameset) = @_;
6247: if ($trailfile eq '') {
6248: $trailfile = $env{'request.filename'};
6249: }
6250:
6251: # this is for resources; directories have customtitle, and crumbs
6252: # and select recent are created in lonpubdir.pm
6253:
6254: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
6255: my ($udom,$uname,$thisdisfn)=
6256: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
6257: my $formaction = "/priv/$udom/$uname/$thisdisfn";
6258: $formaction =~ s{/+}{/}g;
6259:
6260: my $parentpath = '';
6261: my $lastitem = '';
6262: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
6263: $parentpath = $1;
6264: $lastitem = $2;
6265: } else {
6266: $lastitem = $thisdisfn;
6267: }
6268:
6269: my ($crsauthor,$title);
6270: if (($env{'request.course.id'}) &&
6271: ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
6272: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
6273: $crsauthor = 1;
6274: $title = &mt('Course Authoring Space');
6275: } else {
6276: $title = &mt('Authoring Space');
6277: }
6278:
6279: my ($target,$crumbtarget) = (' target="_top"','_top');
6280: if ($frameset) {
6281: $target = ' target="_parent"';
6282: $crumbtarget = '_parent';
6283: } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
6284: $target = '';
6285: $crumbtarget = '';
6286: } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
6287: $target = ' target="'.$env{'request.deeplink.target'}.'"';
6288: $crumbtarget = $env{'request.deeplink.target'};
6289: }
6290:
6291: my $output =
6292: '<div>'
6293: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
6294: .'<b>'.$title.'</b> '
6295: .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
6296: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
6297:
6298: if ($lastitem) {
6299: $output .=
6300: '<span class="LC_filename">'
6301: .$lastitem
6302: .'</span>';
6303: }
6304:
6305: if ($crsauthor) {
6306: $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
6307: } else {
6308: $output .=
6309: '<br />'
6310: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
6311: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
6312: .'</form>'
6313: .&Apache::lonmenu::constspaceform($frameset);
6314: }
6315: $output .= '</div>';
6316:
6317: return $output;
6318: }
6319:
6320: ###############################################
6321: ###############################################
6322:
6323: =pod
6324:
6325: =back
6326:
6327: =head1 HTML Helpers
6328:
6329: =over 4
6330:
6331: =item * &bodytag()
6332:
6333: Returns a uniform header for LON-CAPA web pages.
6334:
6335: Inputs:
6336:
6337: =over 4
6338:
6339: =item * $title, A title to be displayed on the page.
6340:
6341: =item * $function, the current role (can be undef).
6342:
6343: =item * $addentries, extra parameters for the <body> tag.
6344:
6345: =item * $bodyonly, if defined, only return the <body> tag.
6346:
6347: =item * $domain, if defined, force a given domain.
6348:
6349: =item * $forcereg, if page should register as content page (relevant for
6350: text interface only)
6351:
6352: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
6353: navigational links
6354:
6355: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
6356:
6357: =item * $args, optional argument valid values are
6358: no_auto_mt_title -> prevents &mt()ing the title arg
6359: use_absolute -> for external resource or syllabus, this will
6360: contain https://<hostname> if server uses
6361: https (as per hosts.tab), but request is for http
6362: hostname -> hostname, from $r->hostname().
6363:
6364: =item * $advtoolsref, optional argument, ref to an array containing
6365: inlineremote items to be added in "Functions" menu below
6366: breadcrumbs.
6367:
6368: =item * $ltiscope, optional argument, will be one of: resource, map or
6369: course, if LON-CAPA is in LTI Provider context. Value is
6370: the scope of use, i.e., launch was for access to a single, a map
6371: or the entire course.
6372:
6373: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
6374: context, this will contain the URL for the landing item in
6375: the course, after launch from an LTI Consumer
6376:
6377: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
6378: context, this will contain a reference to hash of items
6379: to be included in the page header and/or inline menu.
6380:
6381: =back
6382:
6383: Returns: A uniform header for LON-CAPA web pages.
6384: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
6385: If $bodyonly is undef or zero, an html string containing a <body> tag and
6386: other decorations will be returned.
6387:
6388: =cut
6389:
6390: sub bodytag {
6391: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
6392: $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
6393: $ltimenu,$menucoll,$menuref)=@_;
6394:
6395: my $public;
6396: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
6397: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
6398: $public = 1;
6399: }
6400: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6401: my $httphost = $args->{'use_absolute'};
6402: my $hostname = $args->{'hostname'};
6403:
6404: $function = &get_users_function() if (!$function);
6405: my $img = &designparm($function.'.img',$domain);
6406: my $font = &designparm($function.'.font',$domain);
6407: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
6408:
6409: my %design = ( 'style' => 'margin-top: 0',
6410: 'bgcolor' => $pgbg,
6411: 'text' => $font,
6412: 'alink' => &designparm($function.'.alink',$domain),
6413: 'vlink' => &designparm($function.'.vlink',$domain),
6414: 'link' => &designparm($function.'.link',$domain),);
6415: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
6416:
6417: # role and realm
6418: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
6419: if ($realm) {
6420: $realm = '/'.$realm;
6421: }
6422: if ($role eq 'ca') {
6423: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
6424: $realm = &plainname($rname,$rdom);
6425: }
6426: # realm
6427: my ($cid,$sec);
6428: if ($env{'request.course.id'}) {
6429: $cid = $env{'request.course.id'};
6430: if ($env{'request.course.sec'}) {
6431: $sec = $env{'request.course.sec'};
6432: }
6433: } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
6434: if (&Apache::lonnet::is_course($1,$2)) {
6435: $cid = $1.'_'.$2;
6436: $sec = $3;
6437: }
6438: }
6439: if ($cid) {
6440: if ($env{'request.role'} !~ /^cr/) {
6441: $role = &Apache::lonnet::plaintext($role,&course_type());
6442: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
6443: if ($env{'request.role.desc'}) {
6444: $role = $env{'request.role.desc'};
6445: } else {
6446: $role = &mt('Helpdesk[_1]',' '.$2);
6447: }
6448: } else {
6449: $role = (split(/\//,$role,4))[-1];
6450: }
6451: if ($sec) {
6452: $role .= (' 'x2).'- '.&mt('section:').' '.$sec;
6453: }
6454: $realm = $env{'course.'.$cid.'.description'};
6455: } else {
6456: $role = &Apache::lonnet::plaintext($role);
6457: }
6458:
6459: if (!$realm) { $realm=' '; }
6460:
6461: my $extra_body_attr = &make_attr_string($forcereg,\%design);
6462:
6463: # construct main body tag
6464: my $bodytag = "<body $extra_body_attr>".
6465: &Apache::lontexconvert::init_math_support();
6466:
6467: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6468:
6469: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
6470: return $bodytag;
6471: }
6472:
6473: if ($public) {
6474: undef($role);
6475: }
6476:
6477: my $showcrstitle = 1;
6478: if (($cid) && ($env{'request.lti.login'})) {
6479: if (ref($ltimenu) eq 'HASH') {
6480: unless ($ltimenu->{'role'}) {
6481: undef($role);
6482: }
6483: unless ($ltimenu->{'coursetitle'}) {
6484: $realm=' ';
6485: $showcrstitle = 0;
6486: }
6487: }
6488: } elsif (($cid) && ($menucoll)) {
6489: if (ref($menuref) eq 'HASH') {
6490: unless ($menuref->{'role'}) {
6491: undef($role);
6492: }
6493: unless ($menuref->{'crs'}) {
6494: $realm=' ';
6495: $showcrstitle = 0;
6496: }
6497: }
6498: }
6499:
6500: my $titleinfo = '<h1>'.$title.'</h1>';
6501: #
6502: # Extra info if you are the DC
6503: my $dc_info = '';
6504: if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
6505: (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
6506: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
6507: $dc_info =~ s/\s+$//;
6508: }
6509:
6510: my $crstype;
6511: if ($cid) {
6512: $crstype = $env{'course.'.$cid.'.type'};
6513: } elsif ($args->{'crstype'}) {
6514: $crstype = $args->{'crstype'};
6515: }
6516: if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
6517: undef($role);
6518: } else {
6519: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
6520: }
6521:
6522: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
6523:
6524: # if ($env{'request.state'} eq 'construct') {
6525: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
6526: # }
6527:
6528: $bodytag .= Apache::lonhtmlcommon::scripttag(
6529: Apache::lonmenu::utilityfunctions($httphost), 'start');
6530:
6531: unless ($args->{'no_primary_menu'}) {
6532: my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
6533: $args->{'links_disabled'},
6534: $args->{'links_target'});
6535:
6536: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
6537: if ($dc_info) {
6538: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
6539: }
6540: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
6541: <em>$realm</em> $dc_info</div>|;
6542: return $bodytag;
6543: }
6544:
6545: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
6546: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
6547: }
6548:
6549: $bodytag .= $right;
6550:
6551: if ($dc_info) {
6552: $dc_info = &dc_courseid_toggle($dc_info);
6553: }
6554: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
6555: }
6556:
6557: #if directed to not display the secondary menu, don't.
6558: if ($args->{'no_secondary_menu'}) {
6559: return $bodytag;
6560: }
6561: #don't show menus for public users
6562: if (!$public){
6563: unless ($args->{'no_inline_menu'}) {
6564: $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
6565: $args->{'no_primary_menu'},
6566: $menucoll,$menuref,
6567: $args->{'links_disabled'},
6568: $args->{'links_target'});
6569: }
6570: $bodytag .= Apache::lonmenu::serverform();
6571: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6572: if ($env{'request.state'} eq 'construct') {
6573: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
6574: $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
6575: } elsif ($forcereg) {
6576: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
6577: $args->{'group'},
6578: $args->{'hide_buttons'},
6579: $hostname,$ltiscope,$ltiuri);
6580: } else {
6581: $bodytag .=
6582: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6583: $forcereg,$args->{'group'},
6584: $args->{'bread_crumbs'},
6585: $advtoolsref,'',$hostname);
6586: }
6587: }else{
6588: # this is to seperate menu from content when there's no secondary
6589: # menu. Especially needed for public accessible ressources.
6590: $bodytag .= '<hr style="clear:both" />';
6591: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6592: }
6593:
6594: return $bodytag;
6595: }
6596:
6597: sub dc_courseid_toggle {
6598: my ($dc_info) = @_;
6599: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
6600: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
6601: &mt('(More ...)').'</a></span>'.
6602: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
6603: }
6604:
6605: sub make_attr_string {
6606: my ($register,$attr_ref) = @_;
6607:
6608: if ($attr_ref && !ref($attr_ref)) {
6609: die("addentries Must be a hash ref ".
6610: join(':',caller(1))." ".
6611: join(':',caller(0))." ");
6612: }
6613:
6614: if ($register) {
6615: my ($on_load,$on_unload);
6616: foreach my $key (keys(%{$attr_ref})) {
6617: if (lc($key) eq 'onload') {
6618: $on_load.=$attr_ref->{$key}.';';
6619: delete($attr_ref->{$key});
6620:
6621: } elsif (lc($key) eq 'onunload') {
6622: $on_unload.=$attr_ref->{$key}.';';
6623: delete($attr_ref->{$key});
6624: }
6625: }
6626: $attr_ref->{'onload'} = $on_load;
6627: $attr_ref->{'onunload'}= $on_unload;
6628: }
6629:
6630: my $attr_string;
6631: foreach my $attr (sort(keys(%$attr_ref))) {
6632: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6633: }
6634: return $attr_string;
6635: }
6636:
6637:
6638: ###############################################
6639: ###############################################
6640:
6641: =pod
6642:
6643: =item * &endbodytag()
6644:
6645: Returns a uniform footer for LON-CAPA web pages.
6646:
6647: Inputs: 1 - optional reference to an args hash
6648: If in the hash, key for noredirectlink has a value which evaluates to true,
6649: a 'Continue' link is not displayed if the page contains an
6650: internal redirect in the <head></head> section,
6651: i.e., $env{'internal.head.redirect'} exists
6652:
6653: =cut
6654:
6655: sub endbodytag {
6656: my ($args) = @_;
6657: my $endbodytag;
6658: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6659: $endbodytag='</body>';
6660: }
6661: if ( exists( $env{'internal.head.redirect'} ) ) {
6662: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6663: $endbodytag=
6664: "<br /><a href=\"$env{'internal.head.redirect'}\">".
6665: &mt('Continue').'</a>'.
6666: $endbodytag;
6667: }
6668: }
6669: return $endbodytag;
6670: }
6671:
6672: =pod
6673:
6674: =item * &standard_css()
6675:
6676: Returns a style sheet
6677:
6678: Inputs: (all optional)
6679: domain -> force to color decorate a page for a specific
6680: domain
6681: function -> force usage of a specific rolish color scheme
6682: bgcolor -> override the default page bgcolor
6683:
6684: =cut
6685:
6686: sub standard_css {
6687: my ($function,$domain,$bgcolor) = @_;
6688: $function = &get_users_function() if (!$function);
6689: my $img = &designparm($function.'.img', $domain);
6690: my $tabbg = &designparm($function.'.tabbg', $domain);
6691: my $font = &designparm($function.'.font', $domain);
6692: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6693: #second colour for later usage
6694: my $sidebg = &designparm($function.'.sidebg',$domain);
6695: my $pgbg_or_bgcolor =
6696: $bgcolor ||
6697: &designparm($function.'.pgbg', $domain);
6698: my $pgbg = &designparm($function.'.pgbg', $domain);
6699: my $alink = &designparm($function.'.alink', $domain);
6700: my $vlink = &designparm($function.'.vlink', $domain);
6701: my $link = &designparm($function.'.link', $domain);
6702:
6703: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6704: my $mono = 'monospace';
6705: my $data_table_head = $sidebg;
6706: my $data_table_light = '#FAFAFA';
6707: my $data_table_dark = '#E0E0E0';
6708: my $data_table_darker = '#CCCCCC';
6709: my $data_table_highlight = '#FFFF00';
6710: my $mail_new = '#FFBB77';
6711: my $mail_new_hover = '#DD9955';
6712: my $mail_read = '#BBBB77';
6713: my $mail_read_hover = '#999944';
6714: my $mail_replied = '#AAAA88';
6715: my $mail_replied_hover = '#888855';
6716: my $mail_other = '#99BBBB';
6717: my $mail_other_hover = '#669999';
6718: my $table_header = '#DDDDDD';
6719: my $feedback_link_bg = '#BBBBBB';
6720: my $lg_border_color = '#C8C8C8';
6721: my $button_hover = '#BF2317';
6722:
6723: my $border = ($env{'browser.type'} eq 'explorer' ||
6724: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6725: : '0 3px 0 4px';
6726:
6727:
6728: return <<END;
6729:
6730: /* needed for iframe to allow 100% height in FF */
6731: body, html {
6732: margin: 0;
6733: padding: 0 0.5%;
6734: height: 99%; /* to avoid scrollbars */
6735: }
6736:
6737: body {
6738: font-family: $sans;
6739: line-height:130%;
6740: font-size:0.83em;
6741: color:$font;
6742: }
6743:
6744: a:focus,
6745: a:focus img {
6746: color: red;
6747: }
6748:
6749: form, .inline {
6750: display: inline;
6751: }
6752:
6753: .LC_right {
6754: text-align:right;
6755: }
6756:
6757: .LC_middle {
6758: vertical-align:middle;
6759: }
6760:
6761: .LC_floatleft {
6762: float: left;
6763: }
6764:
6765: .LC_floatright {
6766: float: right;
6767: }
6768:
6769: .LC_400Box {
6770: width:400px;
6771: }
6772:
6773: .LC_iframecontainer {
6774: width: 98%;
6775: margin: 0;
6776: position: fixed;
6777: top: 8.5em;
6778: bottom: 0;
6779: }
6780:
6781: .LC_iframecontainer iframe{
6782: border: none;
6783: width: 100%;
6784: height: 100%;
6785: }
6786:
6787: .LC_filename {
6788: font-family: $mono;
6789: white-space:pre;
6790: font-size: 120%;
6791: }
6792:
6793: .LC_fileicon {
6794: border: none;
6795: height: 1.3em;
6796: vertical-align: text-bottom;
6797: margin-right: 0.3em;
6798: text-decoration:none;
6799: }
6800:
6801: .LC_setting {
6802: text-decoration:underline;
6803: }
6804:
6805: .LC_error {
6806: color: red;
6807: }
6808:
6809: .LC_warning {
6810: color: darkorange;
6811: }
6812:
6813: .LC_diff_removed {
6814: color: red;
6815: }
6816:
6817: .LC_info,
6818: .LC_success,
6819: .LC_diff_added {
6820: color: green;
6821: }
6822:
6823: div.LC_confirm_box {
6824: background-color: #FAFAFA;
6825: border: 1px solid $lg_border_color;
6826: margin-right: 0;
6827: padding: 5px;
6828: }
6829:
6830: div.LC_confirm_box .LC_error img,
6831: div.LC_confirm_box .LC_success img {
6832: vertical-align: middle;
6833: }
6834:
6835: .LC_maxwidth {
6836: max-width: 100%;
6837: height: auto;
6838: }
6839:
6840: .LC_textsize_mobile {
6841: \@media only screen and (max-device-width: 480px) {
6842: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
6843: }
6844: }
6845:
6846: .LC_icon {
6847: border: none;
6848: vertical-align: middle;
6849: }
6850:
6851: .LC_docs_spacer {
6852: width: 25px;
6853: height: 1px;
6854: border: none;
6855: }
6856:
6857: .LC_internal_info {
6858: color: #999999;
6859: }
6860:
6861: .LC_discussion {
6862: background: $data_table_dark;
6863: border: 1px solid black;
6864: margin: 2px;
6865: }
6866:
6867: .LC_disc_action_left {
6868: background: $sidebg;
6869: text-align: left;
6870: padding: 4px;
6871: margin: 2px;
6872: }
6873:
6874: .LC_disc_action_right {
6875: background: $sidebg;
6876: text-align: right;
6877: padding: 4px;
6878: margin: 2px;
6879: }
6880:
6881: .LC_disc_new_item {
6882: background: white;
6883: border: 2px solid red;
6884: margin: 4px;
6885: padding: 4px;
6886: }
6887:
6888: .LC_disc_old_item {
6889: background: white;
6890: margin: 4px;
6891: padding: 4px;
6892: }
6893:
6894: table.LC_pastsubmission {
6895: border: 1px solid black;
6896: margin: 2px;
6897: }
6898:
6899: table#LC_menubuttons {
6900: width: 100%;
6901: background: $pgbg;
6902: border: 2px;
6903: border-collapse: separate;
6904: padding: 0;
6905: }
6906:
6907: table#LC_title_bar a {
6908: color: $fontmenu;
6909: }
6910:
6911: table#LC_title_bar {
6912: clear: both;
6913: display: none;
6914: }
6915:
6916: table#LC_title_bar,
6917: table.LC_breadcrumbs, /* obsolete? */
6918: table#LC_title_bar.LC_with_remote {
6919: width: 100%;
6920: border-color: $pgbg;
6921: border-style: solid;
6922: border-width: $border;
6923: background: $pgbg;
6924: color: $fontmenu;
6925: border-collapse: collapse;
6926: padding: 0;
6927: margin: 0;
6928: }
6929:
6930: ul.LC_breadcrumb_tools_outerlist {
6931: margin: 0;
6932: padding: 0;
6933: position: relative;
6934: list-style: none;
6935: }
6936: ul.LC_breadcrumb_tools_outerlist li {
6937: display: inline;
6938: }
6939:
6940: .LC_breadcrumb_tools_navigation {
6941: padding: 0;
6942: margin: 0;
6943: float: left;
6944: }
6945: .LC_breadcrumb_tools_tools {
6946: padding: 0;
6947: margin: 0;
6948: float: right;
6949: }
6950:
6951: .LC_placement_prog {
6952: padding-right: 20px;
6953: font-weight: bold;
6954: font-size: 90%;
6955: }
6956:
6957: table#LC_title_bar td {
6958: background: $tabbg;
6959: }
6960:
6961: table#LC_menubuttons img {
6962: border: none;
6963: }
6964:
6965: .LC_breadcrumbs_component {
6966: float: right;
6967: margin: 0 1em;
6968: }
6969: .LC_breadcrumbs_component img {
6970: vertical-align: middle;
6971: }
6972:
6973: .LC_breadcrumbs_hoverable {
6974: background: $sidebg;
6975: }
6976:
6977: td.LC_table_cell_checkbox {
6978: text-align: center;
6979: }
6980:
6981: .LC_fontsize_small {
6982: font-size: 70%;
6983: }
6984:
6985: #LC_breadcrumbs {
6986: clear:both;
6987: background: $sidebg;
6988: border-bottom: 1px solid $lg_border_color;
6989: line-height: 2.5em;
6990: overflow: hidden;
6991: margin: 0;
6992: padding: 0;
6993: text-align: left;
6994: }
6995:
6996: .LC_head_subbox, .LC_actionbox {
6997: clear:both;
6998: background: #F8F8F8; /* $sidebg; */
6999: border: 1px solid $sidebg;
7000: margin: 0 0 10px 0;
7001: padding: 3px;
7002: text-align: left;
7003: }
7004:
7005: .LC_fontsize_medium {
7006: font-size: 85%;
7007: }
7008:
7009: .LC_fontsize_large {
7010: font-size: 120%;
7011: }
7012:
7013: .LC_menubuttons_inline_text {
7014: color: $font;
7015: font-size: 90%;
7016: padding-left:3px;
7017: }
7018:
7019: .LC_menubuttons_inline_text img{
7020: vertical-align: middle;
7021: }
7022:
7023: li.LC_menubuttons_inline_text img {
7024: cursor:pointer;
7025: text-decoration: none;
7026: }
7027:
7028: .LC_menubuttons_link {
7029: text-decoration: none;
7030: }
7031:
7032: .LC_menubuttons_category {
7033: color: $font;
7034: background: $pgbg;
7035: font-size: larger;
7036: font-weight: bold;
7037: }
7038:
7039: td.LC_menubuttons_text {
7040: color: $font;
7041: }
7042:
7043: .LC_current_location {
7044: background: $tabbg;
7045: }
7046:
7047: td.LC_zero_height {
7048: line-height: 0;
7049: cellpadding: 0;
7050: }
7051:
7052: table.LC_data_table {
7053: border: 1px solid #000000;
7054: border-collapse: separate;
7055: border-spacing: 1px;
7056: background: $pgbg;
7057: }
7058:
7059: .LC_data_table_dense {
7060: font-size: small;
7061: }
7062:
7063: table.LC_nested_outer {
7064: border: 1px solid #000000;
7065: border-collapse: collapse;
7066: border-spacing: 0;
7067: width: 100%;
7068: }
7069:
7070: table.LC_innerpickbox,
7071: table.LC_nested {
7072: border: none;
7073: border-collapse: collapse;
7074: border-spacing: 0;
7075: width: 100%;
7076: }
7077:
7078: table.LC_data_table tr th,
7079: table.LC_calendar tr th,
7080: table.LC_prior_tries tr th,
7081: table.LC_innerpickbox tr th {
7082: font-weight: bold;
7083: background-color: $data_table_head;
7084: color:$fontmenu;
7085: font-size:90%;
7086: }
7087:
7088: table.LC_innerpickbox tr th,
7089: table.LC_innerpickbox tr td {
7090: vertical-align: top;
7091: }
7092:
7093: table.LC_data_table tr.LC_info_row > td {
7094: background-color: #CCCCCC;
7095: font-weight: bold;
7096: text-align: left;
7097: }
7098:
7099: table.LC_data_table tr.LC_odd_row > td {
7100: background-color: $data_table_light;
7101: padding: 2px;
7102: vertical-align: top;
7103: }
7104:
7105: table.LC_pick_box tr > td.LC_odd_row {
7106: background-color: $data_table_light;
7107: vertical-align: top;
7108: }
7109:
7110: table.LC_data_table tr.LC_even_row > td {
7111: background-color: $data_table_dark;
7112: padding: 2px;
7113: vertical-align: top;
7114: }
7115:
7116: table.LC_pick_box tr > td.LC_even_row {
7117: background-color: $data_table_dark;
7118: vertical-align: top;
7119: }
7120:
7121: table.LC_data_table tr.LC_data_table_highlight td {
7122: background-color: $data_table_darker;
7123: }
7124:
7125: table.LC_data_table tr td.LC_leftcol_header {
7126: background-color: $data_table_head;
7127: font-weight: bold;
7128: }
7129:
7130: table.LC_data_table tr.LC_empty_row td,
7131: table.LC_nested tr.LC_empty_row td {
7132: font-weight: bold;
7133: font-style: italic;
7134: text-align: center;
7135: padding: 8px;
7136: }
7137:
7138: table.LC_data_table tr.LC_empty_row td,
7139: table.LC_data_table tr.LC_footer_row td {
7140: background-color: $sidebg;
7141: }
7142:
7143: table.LC_nested tr.LC_empty_row td {
7144: background-color: #FFFFFF;
7145: }
7146:
7147: table.LC_caption {
7148: }
7149:
7150: table.LC_nested tr.LC_empty_row td {
7151: padding: 4ex
7152: }
7153:
7154: table.LC_nested_outer tr th {
7155: font-weight: bold;
7156: color:$fontmenu;
7157: background-color: $data_table_head;
7158: font-size: small;
7159: border-bottom: 1px solid #000000;
7160: }
7161:
7162: table.LC_nested_outer tr td.LC_subheader {
7163: background-color: $data_table_head;
7164: font-weight: bold;
7165: font-size: small;
7166: border-bottom: 1px solid #000000;
7167: text-align: right;
7168: }
7169:
7170: table.LC_nested tr.LC_info_row td {
7171: background-color: #CCCCCC;
7172: font-weight: bold;
7173: font-size: small;
7174: text-align: center;
7175: }
7176:
7177: table.LC_nested tr.LC_info_row td.LC_left_item,
7178: table.LC_nested_outer tr th.LC_left_item {
7179: text-align: left;
7180: }
7181:
7182: table.LC_nested td {
7183: background-color: #FFFFFF;
7184: font-size: small;
7185: }
7186:
7187: table.LC_nested_outer tr th.LC_right_item,
7188: table.LC_nested tr.LC_info_row td.LC_right_item,
7189: table.LC_nested tr.LC_odd_row td.LC_right_item,
7190: table.LC_nested tr td.LC_right_item {
7191: text-align: right;
7192: }
7193:
7194: table.LC_nested tr.LC_odd_row td {
7195: background-color: #EEEEEE;
7196: }
7197:
7198: table.LC_createuser {
7199: }
7200:
7201: table.LC_createuser tr.LC_section_row td {
7202: font-size: small;
7203: }
7204:
7205: table.LC_createuser tr.LC_info_row td {
7206: background-color: #CCCCCC;
7207: font-weight: bold;
7208: text-align: center;
7209: }
7210:
7211: table.LC_calendar {
7212: border: 1px solid #000000;
7213: border-collapse: collapse;
7214: width: 98%;
7215: }
7216:
7217: table.LC_calendar_pickdate {
7218: font-size: xx-small;
7219: }
7220:
7221: table.LC_calendar tr td {
7222: border: 1px solid #000000;
7223: vertical-align: top;
7224: width: 14%;
7225: }
7226:
7227: table.LC_calendar tr td.LC_calendar_day_empty {
7228: background-color: $data_table_dark;
7229: }
7230:
7231: table.LC_calendar tr td.LC_calendar_day_current {
7232: background-color: $data_table_highlight;
7233: }
7234:
7235: table.LC_data_table tr td.LC_mail_new {
7236: background-color: $mail_new;
7237: }
7238:
7239: table.LC_data_table tr.LC_mail_new:hover {
7240: background-color: $mail_new_hover;
7241: }
7242:
7243: table.LC_data_table tr td.LC_mail_read {
7244: background-color: $mail_read;
7245: }
7246:
7247: /*
7248: table.LC_data_table tr.LC_mail_read:hover {
7249: background-color: $mail_read_hover;
7250: }
7251: */
7252:
7253: table.LC_data_table tr td.LC_mail_replied {
7254: background-color: $mail_replied;
7255: }
7256:
7257: /*
7258: table.LC_data_table tr.LC_mail_replied:hover {
7259: background-color: $mail_replied_hover;
7260: }
7261: */
7262:
7263: table.LC_data_table tr td.LC_mail_other {
7264: background-color: $mail_other;
7265: }
7266:
7267: /*
7268: table.LC_data_table tr.LC_mail_other:hover {
7269: background-color: $mail_other_hover;
7270: }
7271: */
7272:
7273: table.LC_data_table tr > td.LC_browser_file,
7274: table.LC_data_table tr > td.LC_browser_file_published {
7275: background: #AAEE77;
7276: }
7277:
7278: table.LC_data_table tr > td.LC_browser_file_locked,
7279: table.LC_data_table tr > td.LC_browser_file_unpublished {
7280: background: #FFAA99;
7281: }
7282:
7283: table.LC_data_table tr > td.LC_browser_file_obsolete {
7284: background: #888888;
7285: }
7286:
7287: table.LC_data_table tr > td.LC_browser_file_modified,
7288: table.LC_data_table tr > td.LC_browser_file_metamodified {
7289: background: #F8F866;
7290: }
7291:
7292: table.LC_data_table tr.LC_browser_folder > td {
7293: background: #E0E8FF;
7294: }
7295:
7296: table.LC_data_table tr > td.LC_roles_is {
7297: /* background: #77FF77; */
7298: }
7299:
7300: table.LC_data_table tr > td.LC_roles_future {
7301: border-right: 8px solid #FFFF77;
7302: }
7303:
7304: table.LC_data_table tr > td.LC_roles_will {
7305: border-right: 8px solid #FFAA77;
7306: }
7307:
7308: table.LC_data_table tr > td.LC_roles_expired {
7309: border-right: 8px solid #FF7777;
7310: }
7311:
7312: table.LC_data_table tr > td.LC_roles_will_not {
7313: border-right: 8px solid #AAFF77;
7314: }
7315:
7316: table.LC_data_table tr > td.LC_roles_selected {
7317: border-right: 8px solid #11CC55;
7318: }
7319:
7320: span.LC_current_location {
7321: font-size:larger;
7322: background: $pgbg;
7323: }
7324:
7325: span.LC_current_nav_location {
7326: font-weight:bold;
7327: background: $sidebg;
7328: }
7329:
7330: span.LC_parm_menu_item {
7331: font-size: larger;
7332: }
7333:
7334: span.LC_parm_scope_all {
7335: color: red;
7336: }
7337:
7338: span.LC_parm_scope_folder {
7339: color: green;
7340: }
7341:
7342: span.LC_parm_scope_resource {
7343: color: orange;
7344: }
7345:
7346: span.LC_parm_part {
7347: color: blue;
7348: }
7349:
7350: span.LC_parm_folder,
7351: span.LC_parm_symb {
7352: font-size: x-small;
7353: font-family: $mono;
7354: color: #AAAAAA;
7355: }
7356:
7357: ul.LC_parm_parmlist li {
7358: display: inline-block;
7359: padding: 0.3em 0.8em;
7360: vertical-align: top;
7361: width: 150px;
7362: border-top:1px solid $lg_border_color;
7363: }
7364:
7365: td.LC_parm_overview_level_menu,
7366: td.LC_parm_overview_map_menu,
7367: td.LC_parm_overview_parm_selectors,
7368: td.LC_parm_overview_restrictions {
7369: border: 1px solid black;
7370: border-collapse: collapse;
7371: }
7372:
7373: span.LC_parm_recursive,
7374: td.LC_parm_recursive {
7375: font-weight: bold;
7376: font-size: smaller;
7377: }
7378:
7379: table.LC_parm_overview_restrictions td {
7380: border-width: 1px 4px 1px 4px;
7381: border-style: solid;
7382: border-color: $pgbg;
7383: text-align: center;
7384: }
7385:
7386: table.LC_parm_overview_restrictions th {
7387: background: $tabbg;
7388: border-width: 1px 4px 1px 4px;
7389: border-style: solid;
7390: border-color: $pgbg;
7391: }
7392:
7393: table#LC_helpmenu {
7394: border: none;
7395: height: 55px;
7396: border-spacing: 0;
7397: }
7398:
7399: table#LC_helpmenu fieldset legend {
7400: font-size: larger;
7401: }
7402:
7403: table#LC_helpmenu_links {
7404: width: 100%;
7405: border: 1px solid black;
7406: background: $pgbg;
7407: padding: 0;
7408: border-spacing: 1px;
7409: }
7410:
7411: table#LC_helpmenu_links tr td {
7412: padding: 1px;
7413: background: $tabbg;
7414: text-align: center;
7415: font-weight: bold;
7416: }
7417:
7418: table#LC_helpmenu_links a:link,
7419: table#LC_helpmenu_links a:visited,
7420: table#LC_helpmenu_links a:active {
7421: text-decoration: none;
7422: color: $font;
7423: }
7424:
7425: table#LC_helpmenu_links a:hover {
7426: text-decoration: underline;
7427: color: $vlink;
7428: }
7429:
7430: .LC_chrt_popup_exists {
7431: border: 1px solid #339933;
7432: margin: -1px;
7433: }
7434:
7435: .LC_chrt_popup_up {
7436: border: 1px solid yellow;
7437: margin: -1px;
7438: }
7439:
7440: .LC_chrt_popup {
7441: border: 1px solid #8888FF;
7442: background: #CCCCFF;
7443: }
7444:
7445: table.LC_pick_box {
7446: border-collapse: separate;
7447: background: white;
7448: border: 1px solid black;
7449: border-spacing: 1px;
7450: }
7451:
7452: table.LC_pick_box td.LC_pick_box_title {
7453: background: $sidebg;
7454: font-weight: bold;
7455: text-align: left;
7456: vertical-align: top;
7457: width: 184px;
7458: padding: 8px;
7459: }
7460:
7461: table.LC_pick_box td.LC_pick_box_value {
7462: text-align: left;
7463: padding: 8px;
7464: }
7465:
7466: table.LC_pick_box td.LC_pick_box_select {
7467: text-align: left;
7468: padding: 8px;
7469: }
7470:
7471: table.LC_pick_box td.LC_pick_box_separator {
7472: padding: 0;
7473: height: 1px;
7474: background: black;
7475: }
7476:
7477: table.LC_pick_box td.LC_pick_box_submit {
7478: text-align: right;
7479: }
7480:
7481: table.LC_pick_box td.LC_evenrow_value {
7482: text-align: left;
7483: padding: 8px;
7484: background-color: $data_table_light;
7485: }
7486:
7487: table.LC_pick_box td.LC_oddrow_value {
7488: text-align: left;
7489: padding: 8px;
7490: background-color: $data_table_light;
7491: }
7492:
7493: span.LC_helpform_receipt_cat {
7494: font-weight: bold;
7495: }
7496:
7497: table.LC_group_priv_box {
7498: background: white;
7499: border: 1px solid black;
7500: border-spacing: 1px;
7501: }
7502:
7503: table.LC_group_priv_box td.LC_pick_box_title {
7504: background: $tabbg;
7505: font-weight: bold;
7506: text-align: right;
7507: width: 184px;
7508: }
7509:
7510: table.LC_group_priv_box td.LC_groups_fixed {
7511: background: $data_table_light;
7512: text-align: center;
7513: }
7514:
7515: table.LC_group_priv_box td.LC_groups_optional {
7516: background: $data_table_dark;
7517: text-align: center;
7518: }
7519:
7520: table.LC_group_priv_box td.LC_groups_functionality {
7521: background: $data_table_darker;
7522: text-align: center;
7523: font-weight: bold;
7524: }
7525:
7526: table.LC_group_priv td {
7527: text-align: left;
7528: padding: 0;
7529: }
7530:
7531: .LC_navbuttons {
7532: margin: 2ex 0ex 2ex 0ex;
7533: }
7534:
7535: .LC_topic_bar {
7536: font-weight: bold;
7537: background: $tabbg;
7538: margin: 1em 0em 1em 2em;
7539: padding: 3px;
7540: font-size: 1.2em;
7541: }
7542:
7543: .LC_topic_bar span {
7544: left: 0.5em;
7545: position: absolute;
7546: vertical-align: middle;
7547: font-size: 1.2em;
7548: }
7549:
7550: table.LC_course_group_status {
7551: margin: 20px;
7552: }
7553:
7554: table.LC_status_selector td {
7555: vertical-align: top;
7556: text-align: center;
7557: padding: 4px;
7558: }
7559:
7560: div.LC_feedback_link {
7561: clear: both;
7562: background: $sidebg;
7563: width: 100%;
7564: padding-bottom: 10px;
7565: border: 1px $tabbg solid;
7566: height: 22px;
7567: line-height: 22px;
7568: padding-top: 5px;
7569: }
7570:
7571: div.LC_feedback_link img {
7572: height: 22px;
7573: vertical-align:middle;
7574: }
7575:
7576: div.LC_feedback_link a {
7577: text-decoration: none;
7578: }
7579:
7580: div.LC_comblock {
7581: display:inline;
7582: color:$font;
7583: font-size:90%;
7584: }
7585:
7586: div.LC_feedback_link div.LC_comblock {
7587: padding-left:5px;
7588: }
7589:
7590: div.LC_feedback_link div.LC_comblock a {
7591: color:$font;
7592: }
7593:
7594: span.LC_feedback_link {
7595: /* background: $feedback_link_bg; */
7596: font-size: larger;
7597: }
7598:
7599: span.LC_message_link {
7600: /* background: $feedback_link_bg; */
7601: font-size: larger;
7602: position: absolute;
7603: right: 1em;
7604: }
7605:
7606: table.LC_prior_tries {
7607: border: 1px solid #000000;
7608: border-collapse: separate;
7609: border-spacing: 1px;
7610: }
7611:
7612: table.LC_prior_tries td {
7613: padding: 2px;
7614: }
7615:
7616: .LC_answer_correct {
7617: background: lightgreen;
7618: color: darkgreen;
7619: padding: 6px;
7620: }
7621:
7622: .LC_answer_charged_try {
7623: background: #FFAAAA;
7624: color: darkred;
7625: padding: 6px;
7626: }
7627:
7628: .LC_answer_not_charged_try,
7629: .LC_answer_no_grade,
7630: .LC_answer_late {
7631: background: lightyellow;
7632: color: black;
7633: padding: 6px;
7634: }
7635:
7636: .LC_answer_previous {
7637: background: lightblue;
7638: color: darkblue;
7639: padding: 6px;
7640: }
7641:
7642: .LC_answer_no_message {
7643: background: #FFFFFF;
7644: color: black;
7645: padding: 6px;
7646: }
7647:
7648: .LC_answer_unknown,
7649: .LC_answer_warning {
7650: background: orange;
7651: color: black;
7652: padding: 6px;
7653: }
7654:
7655: span.LC_prior_numerical,
7656: span.LC_prior_string,
7657: span.LC_prior_custom,
7658: span.LC_prior_reaction,
7659: span.LC_prior_math {
7660: font-family: $mono;
7661: white-space: pre;
7662: }
7663:
7664: span.LC_prior_string {
7665: font-family: $mono;
7666: white-space: pre;
7667: }
7668:
7669: table.LC_prior_option {
7670: width: 100%;
7671: border-collapse: collapse;
7672: }
7673:
7674: table.LC_prior_rank,
7675: table.LC_prior_match {
7676: border-collapse: collapse;
7677: }
7678:
7679: table.LC_prior_option tr td,
7680: table.LC_prior_rank tr td,
7681: table.LC_prior_match tr td {
7682: border: 1px solid #000000;
7683: }
7684:
7685: .LC_nobreak {
7686: white-space: nowrap;
7687: }
7688:
7689: span.LC_cusr_emph {
7690: font-style: italic;
7691: }
7692:
7693: span.LC_cusr_subheading {
7694: font-weight: normal;
7695: font-size: 85%;
7696: }
7697:
7698: div.LC_docs_entry_move {
7699: border: 1px solid #BBBBBB;
7700: background: #DDDDDD;
7701: width: 22px;
7702: padding: 1px;
7703: margin: 0;
7704: }
7705:
7706: table.LC_data_table tr > td.LC_docs_entry_commands,
7707: table.LC_data_table tr > td.LC_docs_entry_parameter {
7708: font-size: x-small;
7709: }
7710:
7711: .LC_docs_entry_parameter {
7712: white-space: nowrap;
7713: }
7714:
7715: .LC_docs_copy {
7716: color: #000099;
7717: }
7718:
7719: .LC_docs_cut {
7720: color: #550044;
7721: }
7722:
7723: .LC_docs_rename {
7724: color: #009900;
7725: }
7726:
7727: .LC_docs_remove {
7728: color: #990000;
7729: }
7730:
7731: .LC_docs_alias {
7732: color: #440055;
7733: }
7734:
7735: .LC_domprefs_email,
7736: .LC_docs_alias_name,
7737: .LC_docs_reinit_warn,
7738: .LC_docs_ext_edit {
7739: font-size: x-small;
7740: }
7741:
7742: table.LC_docs_adddocs td,
7743: table.LC_docs_adddocs th {
7744: border: 1px solid #BBBBBB;
7745: padding: 4px;
7746: background: #DDDDDD;
7747: }
7748:
7749: table.LC_sty_begin {
7750: background: #BBFFBB;
7751: }
7752:
7753: table.LC_sty_end {
7754: background: #FFBBBB;
7755: }
7756:
7757: table.LC_double_column {
7758: border-width: 0;
7759: border-collapse: collapse;
7760: width: 100%;
7761: padding: 2px;
7762: }
7763:
7764: table.LC_double_column tr td.LC_left_col {
7765: top: 2px;
7766: left: 2px;
7767: width: 47%;
7768: vertical-align: top;
7769: }
7770:
7771: table.LC_double_column tr td.LC_right_col {
7772: top: 2px;
7773: right: 2px;
7774: width: 47%;
7775: vertical-align: top;
7776: }
7777:
7778: div.LC_left_float {
7779: float: left;
7780: padding-right: 5%;
7781: padding-bottom: 4px;
7782: }
7783:
7784: div.LC_clear_float_header {
7785: padding-bottom: 2px;
7786: }
7787:
7788: div.LC_clear_float_footer {
7789: padding-top: 10px;
7790: clear: both;
7791: }
7792:
7793: div.LC_grade_show_user {
7794: /* border-left: 5px solid $sidebg; */
7795: border-top: 5px solid #000000;
7796: margin: 50px 0 0 0;
7797: padding: 15px 0 5px 10px;
7798: }
7799:
7800: div.LC_grade_show_user_odd_row {
7801: /* border-left: 5px solid #000000; */
7802: }
7803:
7804: div.LC_grade_show_user div.LC_Box {
7805: margin-right: 50px;
7806: }
7807:
7808: div.LC_grade_submissions,
7809: div.LC_grade_message_center,
7810: div.LC_grade_info_links {
7811: margin: 5px;
7812: width: 99%;
7813: background: #FFFFFF;
7814: }
7815:
7816: div.LC_grade_submissions_header,
7817: div.LC_grade_message_center_header {
7818: font-weight: bold;
7819: font-size: large;
7820: }
7821:
7822: div.LC_grade_submissions_body,
7823: div.LC_grade_message_center_body {
7824: border: 1px solid black;
7825: width: 99%;
7826: background: #FFFFFF;
7827: }
7828:
7829: table.LC_scantron_action {
7830: width: 100%;
7831: }
7832:
7833: table.LC_scantron_action tr th {
7834: font-weight:bold;
7835: font-style:normal;
7836: }
7837:
7838: .LC_edit_problem_header,
7839: div.LC_edit_problem_footer {
7840: font-weight: normal;
7841: font-size: medium;
7842: margin: 2px;
7843: background-color: $sidebg;
7844: }
7845:
7846: div.LC_edit_problem_header,
7847: div.LC_edit_problem_header div,
7848: div.LC_edit_problem_footer,
7849: div.LC_edit_problem_footer div,
7850: div.LC_edit_problem_editxml_header,
7851: div.LC_edit_problem_editxml_header div {
7852: z-index: 100;
7853: }
7854:
7855: div.LC_edit_problem_header_title {
7856: font-weight: bold;
7857: font-size: larger;
7858: background: $tabbg;
7859: padding: 3px;
7860: margin: 0 0 5px 0;
7861: }
7862:
7863: table.LC_edit_problem_header_title {
7864: width: 100%;
7865: background: $tabbg;
7866: }
7867:
7868: div.LC_edit_actionbar {
7869: background-color: $sidebg;
7870: margin: 0;
7871: padding: 0;
7872: line-height: 200%;
7873: }
7874:
7875: div.LC_edit_actionbar div{
7876: padding: 0;
7877: margin: 0;
7878: display: inline-block;
7879: }
7880:
7881: .LC_edit_opt {
7882: padding-left: 1em;
7883: white-space: nowrap;
7884: }
7885:
7886: .LC_edit_problem_latexhelper{
7887: text-align: right;
7888: }
7889:
7890: #LC_edit_problem_colorful div{
7891: margin-left: 40px;
7892: }
7893:
7894: #LC_edit_problem_codemirror div{
7895: margin-left: 0px;
7896: }
7897:
7898: img.stift {
7899: border-width: 0;
7900: vertical-align: middle;
7901: }
7902:
7903: table td.LC_mainmenu_col_fieldset {
7904: vertical-align: top;
7905: }
7906:
7907: div.LC_createcourse {
7908: margin: 10px 10px 10px 10px;
7909: }
7910:
7911: .LC_dccid {
7912: float: right;
7913: margin: 0.2em 0 0 0;
7914: padding: 0;
7915: font-size: 90%;
7916: display:none;
7917: }
7918:
7919: ol.LC_primary_menu a:hover,
7920: ol#LC_MenuBreadcrumbs a:hover,
7921: ol#LC_PathBreadcrumbs a:hover,
7922: ul#LC_secondary_menu a:hover,
7923: .LC_FormSectionClearButton input:hover
7924: ul.LC_TabContent li:hover a {
7925: color:$button_hover;
7926: text-decoration:none;
7927: }
7928:
7929: h1 {
7930: padding: 0;
7931: line-height:130%;
7932: }
7933:
7934: h2,
7935: h3,
7936: h4,
7937: h5,
7938: h6 {
7939: margin: 5px 0 5px 0;
7940: padding: 0;
7941: line-height:130%;
7942: }
7943:
7944: .LC_hcell {
7945: padding:3px 15px 3px 15px;
7946: margin: 0;
7947: background-color:$tabbg;
7948: color:$fontmenu;
7949: border-bottom:solid 1px $lg_border_color;
7950: }
7951:
7952: .LC_Box > .LC_hcell {
7953: margin: 0 -10px 10px -10px;
7954: }
7955:
7956: .LC_noBorder {
7957: border: 0;
7958: }
7959:
7960: .LC_FormSectionClearButton input {
7961: background-color:transparent;
7962: border: none;
7963: cursor:pointer;
7964: text-decoration:underline;
7965: }
7966:
7967: .LC_help_open_topic {
7968: color: #FFFFFF;
7969: background-color: #EEEEFF;
7970: margin: 1px;
7971: padding: 4px;
7972: border: 1px solid #000033;
7973: white-space: nowrap;
7974: /* vertical-align: middle; */
7975: }
7976:
7977: dl,
7978: ul,
7979: div,
7980: fieldset {
7981: margin: 10px 10px 10px 0;
7982: /* overflow: hidden; */
7983: }
7984:
7985: article.geogebraweb div {
7986: margin: 0;
7987: }
7988:
7989: fieldset > legend {
7990: font-weight: bold;
7991: padding: 0 5px 0 5px;
7992: }
7993:
7994: #LC_nav_bar {
7995: float: left;
7996: background-color: $pgbg_or_bgcolor;
7997: margin: 0 0 2px 0;
7998: }
7999:
8000: #LC_realm {
8001: margin: 0.2em 0 0 0;
8002: padding: 0;
8003: font-weight: bold;
8004: text-align: center;
8005: background-color: $pgbg_or_bgcolor;
8006: }
8007:
8008: #LC_nav_bar em {
8009: font-weight: bold;
8010: font-style: normal;
8011: }
8012:
8013: ol.LC_primary_menu {
8014: margin: 0;
8015: padding: 0;
8016: }
8017:
8018: ol#LC_PathBreadcrumbs {
8019: margin: 0;
8020: }
8021:
8022: ol.LC_primary_menu li {
8023: color: RGB(80, 80, 80);
8024: vertical-align: middle;
8025: text-align: left;
8026: list-style: none;
8027: position: relative;
8028: float: left;
8029: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
8030: line-height: 1.5em;
8031: }
8032:
8033: ol.LC_primary_menu li a,
8034: ol.LC_primary_menu li p {
8035: display: block;
8036: margin: 0;
8037: padding: 0 5px 0 10px;
8038: text-decoration: none;
8039: }
8040:
8041: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
8042: display: inline-block;
8043: width: 95%;
8044: text-align: left;
8045: }
8046:
8047: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
8048: display: inline-block;
8049: width: 5%;
8050: float: right;
8051: text-align: right;
8052: font-size: 70%;
8053: }
8054:
8055: ol.LC_primary_menu ul {
8056: display: none;
8057: width: 15em;
8058: background-color: $data_table_light;
8059: position: absolute;
8060: top: 100%;
8061: }
8062:
8063: ol.LC_primary_menu ul ul {
8064: left: 100%;
8065: top: 0;
8066: }
8067:
8068: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
8069: display: block;
8070: position: absolute;
8071: margin: 0;
8072: padding: 0;
8073: z-index: 2;
8074: }
8075:
8076: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
8077: /* First Submenu -> size should be smaller than the menu title of the whole menu */
8078: font-size: 90%;
8079: vertical-align: top;
8080: float: none;
8081: border-left: 1px solid black;
8082: border-right: 1px solid black;
8083: /* A dark bottom border to visualize different menu options;
8084: overwritten in the create_submenu routine for the last border-bottom of the menu */
8085: border-bottom: 1px solid $data_table_dark;
8086: }
8087:
8088: ol.LC_primary_menu li li p:hover {
8089: color:$button_hover;
8090: text-decoration:none;
8091: background-color:$data_table_dark;
8092: }
8093:
8094: ol.LC_primary_menu li li a:hover {
8095: color:$button_hover;
8096: background-color:$data_table_dark;
8097: }
8098:
8099: /* Font-size equal to the size of the predecessors*/
8100: ol.LC_primary_menu li:hover li li {
8101: font-size: 100%;
8102: }
8103:
8104: ol.LC_primary_menu li img {
8105: vertical-align: bottom;
8106: height: 1.1em;
8107: margin: 0.2em 0 0 0;
8108: }
8109:
8110: ol.LC_primary_menu a {
8111: color: RGB(80, 80, 80);
8112: text-decoration: none;
8113: }
8114:
8115: ol.LC_primary_menu a.LC_new_message {
8116: font-weight:bold;
8117: color: darkred;
8118: }
8119:
8120: ol.LC_docs_parameters {
8121: margin-left: 0;
8122: padding: 0;
8123: list-style: none;
8124: }
8125:
8126: ol.LC_docs_parameters li {
8127: margin: 0;
8128: padding-right: 20px;
8129: display: inline;
8130: }
8131:
8132: ol.LC_docs_parameters li:before {
8133: content: "\\002022 \\0020";
8134: }
8135:
8136: li.LC_docs_parameters_title {
8137: font-weight: bold;
8138: }
8139:
8140: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
8141: content: "";
8142: }
8143:
8144: ul#LC_secondary_menu {
8145: clear: right;
8146: color: $fontmenu;
8147: background: $tabbg;
8148: list-style: none;
8149: padding: 0;
8150: margin: 0;
8151: width: 100%;
8152: text-align: left;
8153: float: left;
8154: }
8155:
8156: ul#LC_secondary_menu li {
8157: font-weight: bold;
8158: line-height: 1.8em;
8159: border-right: 1px solid black;
8160: float: left;
8161: }
8162:
8163: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
8164: background-color: $data_table_light;
8165: }
8166:
8167: ul#LC_secondary_menu li a {
8168: padding: 0 0.8em;
8169: }
8170:
8171: ul#LC_secondary_menu li ul {
8172: display: none;
8173: }
8174:
8175: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
8176: display: block;
8177: position: absolute;
8178: margin: 0;
8179: padding: 0;
8180: list-style:none;
8181: float: none;
8182: background-color: $data_table_light;
8183: z-index: 2;
8184: margin-left: -1px;
8185: }
8186:
8187: ul#LC_secondary_menu li ul li {
8188: font-size: 90%;
8189: vertical-align: top;
8190: border-left: 1px solid black;
8191: border-right: 1px solid black;
8192: background-color: $data_table_light;
8193: list-style:none;
8194: float: none;
8195: }
8196:
8197: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
8198: background-color: $data_table_dark;
8199: }
8200:
8201: ul.LC_TabContent {
8202: display:block;
8203: background: $sidebg;
8204: border-bottom: solid 1px $lg_border_color;
8205: list-style:none;
8206: margin: -1px -10px 0 -10px;
8207: padding: 0;
8208: }
8209:
8210: ul.LC_TabContent li,
8211: ul.LC_TabContentBigger li {
8212: float:left;
8213: }
8214:
8215: ul#LC_secondary_menu li a {
8216: color: $fontmenu;
8217: text-decoration: none;
8218: }
8219:
8220: ul.LC_TabContent {
8221: min-height:20px;
8222: }
8223:
8224: ul.LC_TabContent li {
8225: vertical-align:middle;
8226: padding: 0 16px 0 10px;
8227: background-color:$tabbg;
8228: border-bottom:solid 1px $lg_border_color;
8229: border-left: solid 1px $font;
8230: }
8231:
8232: ul.LC_TabContent .right {
8233: float:right;
8234: }
8235:
8236: ul.LC_TabContent li a,
8237: ul.LC_TabContent li {
8238: color:rgb(47,47,47);
8239: text-decoration:none;
8240: font-size:95%;
8241: font-weight:bold;
8242: min-height:20px;
8243: }
8244:
8245: ul.LC_TabContent li a:hover,
8246: ul.LC_TabContent li a:focus {
8247: color: $button_hover;
8248: background:none;
8249: outline:none;
8250: }
8251:
8252: ul.LC_TabContent li:hover {
8253: color: $button_hover;
8254: cursor:pointer;
8255: }
8256:
8257: ul.LC_TabContent li.active {
8258: color: $font;
8259: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
8260: border-bottom:solid 1px #FFFFFF;
8261: cursor: default;
8262: }
8263:
8264: ul.LC_TabContent li.active a {
8265: color:$font;
8266: background:#FFFFFF;
8267: outline: none;
8268: }
8269:
8270: ul.LC_TabContent li.goback {
8271: float: left;
8272: border-left: none;
8273: }
8274:
8275: #maincoursedoc {
8276: clear:both;
8277: }
8278:
8279: ul.LC_TabContentBigger {
8280: display:block;
8281: list-style:none;
8282: padding: 0;
8283: }
8284:
8285: ul.LC_TabContentBigger li {
8286: vertical-align:bottom;
8287: height: 30px;
8288: font-size:110%;
8289: font-weight:bold;
8290: color: #737373;
8291: }
8292:
8293: ul.LC_TabContentBigger li.active {
8294: position: relative;
8295: top: 1px;
8296: }
8297:
8298: ul.LC_TabContentBigger li a {
8299: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
8300: height: 30px;
8301: line-height: 30px;
8302: text-align: center;
8303: display: block;
8304: text-decoration: none;
8305: outline: none;
8306: }
8307:
8308: ul.LC_TabContentBigger li.active a {
8309: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
8310: color:$font;
8311: }
8312:
8313: ul.LC_TabContentBigger li b {
8314: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
8315: display: block;
8316: float: left;
8317: padding: 0 30px;
8318: border-bottom: 1px solid $lg_border_color;
8319: }
8320:
8321: ul.LC_TabContentBigger li:hover b {
8322: color:$button_hover;
8323: }
8324:
8325: ul.LC_TabContentBigger li.active b {
8326: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
8327: color:$font;
8328: border: 0;
8329: }
8330:
8331:
8332: ul.LC_CourseBreadcrumbs {
8333: background: $sidebg;
8334: height: 2em;
8335: padding-left: 10px;
8336: margin: 0;
8337: list-style-position: inside;
8338: }
8339:
8340: ol#LC_MenuBreadcrumbs,
8341: ol#LC_PathBreadcrumbs {
8342: padding-left: 10px;
8343: margin: 0;
8344: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
8345: }
8346:
8347: ol#LC_MenuBreadcrumbs li,
8348: ol#LC_PathBreadcrumbs li,
8349: ul.LC_CourseBreadcrumbs li {
8350: display: inline;
8351: white-space: normal;
8352: }
8353:
8354: ol#LC_MenuBreadcrumbs li a,
8355: ul.LC_CourseBreadcrumbs li a {
8356: text-decoration: none;
8357: font-size:90%;
8358: }
8359:
8360: ol#LC_MenuBreadcrumbs h1 {
8361: display: inline;
8362: font-size: 90%;
8363: line-height: 2.5em;
8364: margin: 0;
8365: padding: 0;
8366: }
8367:
8368: ol#LC_PathBreadcrumbs li a {
8369: text-decoration:none;
8370: font-size:100%;
8371: font-weight:bold;
8372: }
8373:
8374: .LC_Box {
8375: border: solid 1px $lg_border_color;
8376: padding: 0 10px 10px 10px;
8377: }
8378:
8379: .LC_DocsBox {
8380: border: solid 1px $lg_border_color;
8381: padding: 0 0 10px 10px;
8382: }
8383:
8384: .LC_AboutMe_Image {
8385: float:left;
8386: margin-right:10px;
8387: }
8388:
8389: .LC_Clear_AboutMe_Image {
8390: clear:left;
8391: }
8392:
8393: dl.LC_ListStyleClean dt {
8394: padding-right: 5px;
8395: display: table-header-group;
8396: }
8397:
8398: dl.LC_ListStyleClean dd {
8399: display: table-row;
8400: }
8401:
8402: .LC_ListStyleClean,
8403: .LC_ListStyleSimple,
8404: .LC_ListStyleNormal,
8405: .LC_ListStyleSpecial {
8406: /* display:block; */
8407: list-style-position: inside;
8408: list-style-type: none;
8409: overflow: hidden;
8410: padding: 0;
8411: }
8412:
8413: .LC_ListStyleSimple li,
8414: .LC_ListStyleSimple dd,
8415: .LC_ListStyleNormal li,
8416: .LC_ListStyleNormal dd,
8417: .LC_ListStyleSpecial li,
8418: .LC_ListStyleSpecial dd {
8419: margin: 0;
8420: padding: 5px 5px 5px 10px;
8421: clear: both;
8422: }
8423:
8424: .LC_ListStyleClean li,
8425: .LC_ListStyleClean dd {
8426: padding-top: 0;
8427: padding-bottom: 0;
8428: }
8429:
8430: .LC_ListStyleSimple dd,
8431: .LC_ListStyleSimple li {
8432: border-bottom: solid 1px $lg_border_color;
8433: }
8434:
8435: .LC_ListStyleSpecial li,
8436: .LC_ListStyleSpecial dd {
8437: list-style-type: none;
8438: background-color: RGB(220, 220, 220);
8439: margin-bottom: 4px;
8440: }
8441:
8442: table.LC_SimpleTable {
8443: margin:5px;
8444: border:solid 1px $lg_border_color;
8445: }
8446:
8447: table.LC_SimpleTable tr {
8448: padding: 0;
8449: border:solid 1px $lg_border_color;
8450: }
8451:
8452: table.LC_SimpleTable thead {
8453: background:rgb(220,220,220);
8454: }
8455:
8456: div.LC_columnSection {
8457: display: block;
8458: clear: both;
8459: overflow: hidden;
8460: margin: 0;
8461: }
8462:
8463: div.LC_columnSection>* {
8464: float: left;
8465: margin: 10px 20px 10px 0;
8466: overflow:hidden;
8467: }
8468:
8469: table em {
8470: font-weight: bold;
8471: font-style: normal;
8472: }
8473:
8474: table.LC_tableBrowseRes,
8475: table.LC_tableOfContent {
8476: border:none;
8477: border-spacing: 1px;
8478: padding: 3px;
8479: background-color: #FFFFFF;
8480: font-size: 90%;
8481: }
8482:
8483: table.LC_tableOfContent {
8484: border-collapse: collapse;
8485: }
8486:
8487: table.LC_tableBrowseRes a,
8488: table.LC_tableOfContent a {
8489: background-color: transparent;
8490: text-decoration: none;
8491: }
8492:
8493: table.LC_tableOfContent img {
8494: border: none;
8495: height: 1.3em;
8496: vertical-align: text-bottom;
8497: margin-right: 0.3em;
8498: }
8499:
8500: a#LC_content_toolbar_firsthomework {
8501: background-image:url(/res/adm/pages/open-first-problem.gif);
8502: }
8503:
8504: a#LC_content_toolbar_everything {
8505: background-image:url(/res/adm/pages/show-all.gif);
8506: }
8507:
8508: a#LC_content_toolbar_uncompleted {
8509: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
8510: }
8511:
8512: #LC_content_toolbar_clearbubbles {
8513: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
8514: }
8515:
8516: a#LC_content_toolbar_changefolder {
8517: background : url(/res/adm/pages/close-all-folders.gif) top center ;
8518: }
8519:
8520: a#LC_content_toolbar_changefolder_toggled {
8521: background-image:url(/res/adm/pages/open-all-folders.gif);
8522: }
8523:
8524: a#LC_content_toolbar_edittoplevel {
8525: background-image:url(/res/adm/pages/edittoplevel.gif);
8526: }
8527:
8528: ul#LC_toolbar li a:hover {
8529: background-position: bottom center;
8530: }
8531:
8532: ul#LC_toolbar {
8533: padding: 0;
8534: margin: 2px;
8535: list-style:none;
8536: position:relative;
8537: background-color:white;
8538: overflow: auto;
8539: }
8540:
8541: ul#LC_toolbar li {
8542: border:1px solid white;
8543: padding: 0;
8544: margin: 0;
8545: float: left;
8546: display:inline;
8547: vertical-align:middle;
8548: white-space: nowrap;
8549: }
8550:
8551:
8552: a.LC_toolbarItem {
8553: display:block;
8554: padding: 0;
8555: margin: 0;
8556: height: 32px;
8557: width: 32px;
8558: color:white;
8559: border: none;
8560: background-repeat:no-repeat;
8561: background-color:transparent;
8562: }
8563:
8564: ul.LC_funclist {
8565: margin: 0;
8566: padding: 0.5em 1em 0.5em 0;
8567: }
8568:
8569: ul.LC_funclist > li:first-child {
8570: font-weight:bold;
8571: margin-left:0.8em;
8572: }
8573:
8574: ul.LC_funclist + ul.LC_funclist {
8575: /*
8576: left border as a seperator if we have more than
8577: one list
8578: */
8579: border-left: 1px solid $sidebg;
8580: /*
8581: this hides the left border behind the border of the
8582: outer box if element is wrapped to the next 'line'
8583: */
8584: margin-left: -1px;
8585: }
8586:
8587: ul.LC_funclist li {
8588: display: inline;
8589: white-space: nowrap;
8590: margin: 0 0 0 25px;
8591: line-height: 150%;
8592: }
8593:
8594: .LC_hidden {
8595: display: none;
8596: }
8597:
8598: .LCmodal-overlay {
8599: position:fixed;
8600: top:0;
8601: right:0;
8602: bottom:0;
8603: left:0;
8604: height:100%;
8605: width:100%;
8606: margin:0;
8607: padding:0;
8608: background:#999;
8609: opacity:.75;
8610: filter: alpha(opacity=75);
8611: -moz-opacity: 0.75;
8612: z-index:101;
8613: }
8614:
8615: * html .LCmodal-overlay {
8616: position: absolute;
8617: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
8618: }
8619:
8620: .LCmodal-window {
8621: position:fixed;
8622: top:50%;
8623: left:50%;
8624: margin:0;
8625: padding:0;
8626: z-index:102;
8627: }
8628:
8629: * html .LCmodal-window {
8630: position:absolute;
8631: }
8632:
8633: .LCclose-window {
8634: position:absolute;
8635: width:32px;
8636: height:32px;
8637: right:8px;
8638: top:8px;
8639: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
8640: text-indent:-99999px;
8641: overflow:hidden;
8642: cursor:pointer;
8643: }
8644:
8645: .LCisDisabled {
8646: cursor: not-allowed;
8647: opacity: 0.5;
8648: }
8649:
8650: a[aria-disabled="true"] {
8651: color: currentColor;
8652: display: inline-block; /* For IE11/ MS Edge bug */
8653: pointer-events: none;
8654: text-decoration: none;
8655: }
8656:
8657: pre.LC_wordwrap {
8658: white-space: pre-wrap;
8659: white-space: -moz-pre-wrap;
8660: white-space: -pre-wrap;
8661: white-space: -o-pre-wrap;
8662: word-wrap: break-word;
8663: }
8664:
8665: /*
8666: styles used for response display
8667: */
8668: div.LC_radiofoil, div.LC_rankfoil {
8669: margin: .5em 0em .5em 0em;
8670: }
8671: table.LC_itemgroup {
8672: margin-top: 1em;
8673: }
8674:
8675: /*
8676: styles used by TTH when "Default set of options to pass to tth/m
8677: when converting TeX" in course settings has been set
8678:
8679: option passed: -t
8680:
8681: */
8682:
8683: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8684: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8685: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8686: td div.norm {line-height:normal;}
8687:
8688: /*
8689: option passed -y3
8690: */
8691:
8692: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8693: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8694: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8695:
8696: /*
8697: sections with roles, for content only
8698: */
8699: section[class^="role-"] {
8700: padding-left: 10px;
8701: padding-right: 5px;
8702: margin-top: 8px;
8703: margin-bottom: 8px;
8704: border: 1px solid #2A4;
8705: border-radius: 5px;
8706: box-shadow: 0px 1px 1px #BBB;
8707: }
8708: section[class^="role-"]>h1 {
8709: position: relative;
8710: margin: 0px;
8711: padding-top: 10px;
8712: padding-left: 40px;
8713: }
8714: section[class^="role-"]>h1:before {
8715: position: absolute;
8716: left: -5px;
8717: top: 5px;
8718: }
8719: section.role-activity>h1:before {
8720: content:url('/adm/daxe/images/section_icons/activity.png');
8721: }
8722: section.role-advice>h1:before {
8723: content:url('/adm/daxe/images/section_icons/advice.png');
8724: }
8725: section.role-bibliography>h1:before {
8726: content:url('/adm/daxe/images/section_icons/bibliography.png');
8727: }
8728: section.role-citation>h1:before {
8729: content:url('/adm/daxe/images/section_icons/citation.png');
8730: }
8731: section.role-conclusion>h1:before {
8732: content:url('/adm/daxe/images/section_icons/conclusion.png');
8733: }
8734: section.role-definition>h1:before {
8735: content:url('/adm/daxe/images/section_icons/definition.png');
8736: }
8737: section.role-demonstration>h1:before {
8738: content:url('/adm/daxe/images/section_icons/demonstration.png');
8739: }
8740: section.role-example>h1:before {
8741: content:url('/adm/daxe/images/section_icons/example.png');
8742: }
8743: section.role-explanation>h1:before {
8744: content:url('/adm/daxe/images/section_icons/explanation.png');
8745: }
8746: section.role-introduction>h1:before {
8747: content:url('/adm/daxe/images/section_icons/introduction.png');
8748: }
8749: section.role-method>h1:before {
8750: content:url('/adm/daxe/images/section_icons/method.png');
8751: }
8752: section.role-more_information>h1:before {
8753: content:url('/adm/daxe/images/section_icons/more_information.png');
8754: }
8755: section.role-objectives>h1:before {
8756: content:url('/adm/daxe/images/section_icons/objectives.png');
8757: }
8758: section.role-prerequisites>h1:before {
8759: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8760: }
8761: section.role-remark>h1:before {
8762: content:url('/adm/daxe/images/section_icons/remark.png');
8763: }
8764: section.role-reminder>h1:before {
8765: content:url('/adm/daxe/images/section_icons/reminder.png');
8766: }
8767: section.role-summary>h1:before {
8768: content:url('/adm/daxe/images/section_icons/summary.png');
8769: }
8770: section.role-syntax>h1:before {
8771: content:url('/adm/daxe/images/section_icons/syntax.png');
8772: }
8773: section.role-warning>h1:before {
8774: content:url('/adm/daxe/images/section_icons/warning.png');
8775: }
8776:
8777: #LC_minitab_header {
8778: float:left;
8779: width:100%;
8780: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
8781: font-size:93%;
8782: line-height:normal;
8783: margin: 0.5em 0 0.5em 0;
8784: }
8785: #LC_minitab_header ul {
8786: margin:0;
8787: padding:10px 10px 0;
8788: list-style:none;
8789: }
8790: #LC_minitab_header li {
8791: float:left;
8792: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
8793: margin:0;
8794: padding:0 0 0 9px;
8795: }
8796: #LC_minitab_header a {
8797: display:block;
8798: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
8799: padding:5px 15px 4px 6px;
8800: }
8801: #LC_minitab_header #LC_current_minitab {
8802: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
8803: }
8804: #LC_minitab_header #LC_current_minitab a {
8805: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
8806: padding-bottom:5px;
8807: }
8808:
8809:
8810: END
8811: }
8812:
8813: =pod
8814:
8815: =item * &headtag()
8816:
8817: Returns a uniform footer for LON-CAPA web pages.
8818:
8819: Inputs: $title - optional title for the head
8820: $head_extra - optional extra HTML to put inside the <head>
8821: $args - optional arguments
8822: force_register - if is true call registerurl so the remote is
8823: informed
8824: redirect -> array ref of
8825: 1- seconds before redirect occurs
8826: 2- url to redirect to
8827: 3- whether the side effect should occur
8828: (side effect of setting
8829: $env{'internal.head.redirect'} to the url
8830: redirected too)
8831: domain -> force to color decorate a page for a specific
8832: domain
8833: function -> force usage of a specific rolish color scheme
8834: bgcolor -> override the default page bgcolor
8835: no_auto_mt_title
8836: -> prevent &mt()ing the title arg
8837:
8838: =cut
8839:
8840: sub headtag {
8841: my ($title,$head_extra,$args) = @_;
8842:
8843: my $function = $args->{'function'} || &get_users_function();
8844: my $domain = $args->{'domain'} || &determinedomain();
8845: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
8846: my $httphost = $args->{'use_absolute'};
8847: my $url = join(':',$env{'user.name'},$env{'user.domain'},
8848: $Apache::lonnet::perlvar{'lonVersion'},
8849: #time(),
8850: $env{'environment.color.timestamp'},
8851: $function,$domain,$bgcolor);
8852:
8853: $url = '/adm/css/'.&escape($url).'.css';
8854:
8855: my $result =
8856: '<head>'.
8857: &font_settings($args);
8858:
8859: my $inhibitprint;
8860: if ($args->{'print_suppress'}) {
8861: $inhibitprint = &print_suppression();
8862: }
8863:
8864: if (!$args->{'frameset'}) {
8865: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
8866: }
8867: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
8868: $result .= Apache::lonxml::display_title();
8869: }
8870: if (!$args->{'no_nav_bar'}
8871: && !$args->{'only_body'}
8872: && !$args->{'frameset'}) {
8873: $result .= &help_menu_js($httphost);
8874: $result.=&modal_window();
8875: $result.=&togglebox_script();
8876: $result.=&wishlist_window();
8877: $result.=&LCprogressbarUpdate_script();
8878: } else {
8879: if ($args->{'add_modal'}) {
8880: $result.=&modal_window();
8881: }
8882: if ($args->{'add_wishlist'}) {
8883: $result.=&wishlist_window();
8884: }
8885: if ($args->{'add_togglebox'}) {
8886: $result.=&togglebox_script();
8887: }
8888: if ($args->{'add_progressbar'}) {
8889: $result.=&LCprogressbarUpdate_script();
8890: }
8891: }
8892: if (ref($args->{'redirect'})) {
8893: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
8894: $url = &Apache::lonenc::check_encrypt($url);
8895: if (!$inhibit_continue) {
8896: $env{'internal.head.redirect'} = $url;
8897: }
8898: $result.=<<ADDMETA
8899: <meta http-equiv="pragma" content="no-cache" />
8900: <meta http-equiv="Refresh" content="$time; url=$url" />
8901: ADDMETA
8902: } else {
8903: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
8904: my $requrl = $env{'request.uri'};
8905: if ($requrl eq '') {
8906: $requrl = $ENV{'REQUEST_URI'};
8907: $requrl =~ s/\?.+$//;
8908: }
8909: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
8910: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
8911: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
8912: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
8913: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
8914: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
8915: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
8916: my ($offload,$offloadoth);
8917: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
8918: if ($domdefs{'offloadnow'}{$lonhost}) {
8919: $offload = 1;
8920: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
8921: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
8922: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
8923: $offloadoth = 1;
8924: $dom_in_use = $env{'user.domain'};
8925: }
8926: }
8927: }
8928: }
8929: unless ($offload) {
8930: if (ref($domdefs{'offloadoth'}) eq 'HASH') {
8931: if ($domdefs{'offloadoth'}{$lonhost}) {
8932: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
8933: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
8934: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
8935: $offload = 1;
8936: $offloadoth = 1;
8937: $dom_in_use = $env{'user.domain'};
8938: }
8939: }
8940: }
8941: }
8942: }
8943: if ($offload) {
8944: my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
8945: if (($newserver eq '') && ($offloadoth)) {
8946: my @domains = &Apache::lonnet::current_machine_domains();
8947: if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
8948: ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
8949: }
8950: }
8951: if (($newserver) && ($newserver ne $lonhost)) {
8952: my $numsec = 5;
8953: my $timeout = $numsec * 1000;
8954: my ($newurl,$locknum,%locks,$msg);
8955: if ($env{'request.role.adv'}) {
8956: ($locknum,%locks) = &Apache::lonnet::get_locks();
8957: }
8958: my $disable_submit = 0;
8959: if ($requrl =~ /$LONCAPA::assess_re/) {
8960: $disable_submit = 1;
8961: }
8962: if ($locknum) {
8963: my @lockinfo = sort(values(%locks));
8964: $msg = &mt('Once the following tasks are complete:')." \n".
8965: join(", ",sort(values(%locks)))."\n";
8966: if (&show_course()) {
8967: $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
8968: } else {
8969: $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
8970: }
8971: } else {
8972: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
8973: $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
8974: }
8975: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
8976: $newurl = '/adm/switchserver?otherserver='.$newserver;
8977: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
8978: $newurl .= '&role='.$env{'request.role'};
8979: }
8980: if ($env{'request.symb'}) {
8981: my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
8982: if ($shownsymb =~ m{^/enc/}) {
8983: my $reqdmajor = 2;
8984: my $reqdminor = 11;
8985: my $reqdsubminor = 3;
8986: my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
8987: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
8988: my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
8989: if (($major eq '' && $minor eq '') ||
8990: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
8991: (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
8992: ($reqdsubminor > $subminor))))) {
8993: undef($shownsymb);
8994: }
8995: }
8996: if ($shownsymb) {
8997: &js_escape(\$shownsymb);
8998: $newurl .= '&symb='.$shownsymb;
8999: }
9000: } else {
9001: my $shownurl = &Apache::lonenc::check_encrypt($requrl);
9002: &js_escape(\$shownurl);
9003: $newurl .= '&origurl='.$shownurl;
9004: }
9005: }
9006: &js_escape(\$msg);
9007: $result.=<<OFFLOAD
9008: <meta http-equiv="pragma" content="no-cache" />
9009: <script type="text/javascript">
9010: // <![CDATA[
9011: function LC_Offload_Now() {
9012: var dest = "$newurl";
9013: if (dest != '') {
9014: window.location.href="$newurl";
9015: }
9016: }
9017: \$(document).ready(function () {
9018: window.alert('$msg');
9019: if ($disable_submit) {
9020: \$(".LC_hwk_submit").prop("disabled", true);
9021: \$( ".LC_textline" ).prop( "readonly", "readonly");
9022: }
9023: setTimeout('LC_Offload_Now()', $timeout);
9024: });
9025: // ]]>
9026: </script>
9027: OFFLOAD
9028: }
9029: }
9030: }
9031: }
9032: }
9033: }
9034: if (!defined($title)) {
9035: $title = 'The LearningOnline Network with CAPA';
9036: }
9037: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
9038: $result .= '<title> LON-CAPA '.$title.'</title>'
9039: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
9040: if (!$args->{'frameset'}) {
9041: $result .= ' /';
9042: }
9043: $result .= '>'
9044: .$inhibitprint
9045: .$head_extra;
9046: my $clientmobile;
9047: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
9048: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
9049: } else {
9050: $clientmobile = $env{'browser.mobile'};
9051: }
9052: if ($clientmobile) {
9053: $result .= '
9054: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
9055: <meta name="apple-mobile-web-app-capable" content="yes" />';
9056: }
9057: $result .= '<meta name="google" content="notranslate" />'."\n";
9058: return $result.'</head>';
9059: }
9060:
9061: =pod
9062:
9063: =item * &font_settings()
9064:
9065: Returns neccessary <meta> to set the proper encoding
9066:
9067: Inputs: optional reference to HASH -- $args passed to &headtag()
9068:
9069: =cut
9070:
9071: sub font_settings {
9072: my ($args) = @_;
9073: my $headerstring='';
9074: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
9075: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
9076: $headerstring.=
9077: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
9078: if (!$args->{'frameset'}) {
9079: $headerstring.= ' /';
9080: }
9081: $headerstring .= '>'."\n";
9082: }
9083: return $headerstring;
9084: }
9085:
9086: =pod
9087:
9088: =item * &print_suppression()
9089:
9090: In course context returns css which causes the body to be blank when media="print",
9091: if printout generation is unavailable for the current resource.
9092:
9093: This could be because:
9094:
9095: (a) printstartdate is in the future
9096:
9097: (b) printenddate is in the past
9098:
9099: (c) there is an active exam block with "printout"
9100: functionality blocked
9101:
9102: Users with pav, pfo or evb privileges are exempt.
9103:
9104: Inputs: none
9105:
9106: =cut
9107:
9108:
9109: sub print_suppression {
9110: my $noprint;
9111: if ($env{'request.course.id'}) {
9112: my $scope = $env{'request.course.id'};
9113: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9114: (&Apache::lonnet::allowed('pfo',$scope))) {
9115: return;
9116: }
9117: if ($env{'request.course.sec'} ne '') {
9118: $scope .= "/$env{'request.course.sec'}";
9119: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9120: (&Apache::lonnet::allowed('pfo',$scope))) {
9121: return;
9122: }
9123: }
9124: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9125: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9126: my $clientip = &Apache::lonnet::get_requestor_ip();
9127: my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
9128: if ($blocked) {
9129: my $checkrole = "cm./$cdom/$cnum";
9130: if ($env{'request.course.sec'} ne '') {
9131: $checkrole .= "/$env{'request.course.sec'}";
9132: }
9133: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
9134: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
9135: $noprint = 1;
9136: }
9137: }
9138: unless ($noprint) {
9139: my $symb = &Apache::lonnet::symbread();
9140: if ($symb ne '') {
9141: my $navmap = Apache::lonnavmaps::navmap->new();
9142: if (ref($navmap)) {
9143: my $res = $navmap->getBySymb($symb);
9144: if (ref($res)) {
9145: if (!$res->resprintable()) {
9146: $noprint = 1;
9147: }
9148: }
9149: }
9150: }
9151: }
9152: if ($noprint) {
9153: return <<"ENDSTYLE";
9154: <style type="text/css" media="print">
9155: body { display:none }
9156: </style>
9157: ENDSTYLE
9158: }
9159: }
9160: return;
9161: }
9162:
9163: =pod
9164:
9165: =item * &xml_begin()
9166:
9167: Returns the needed doctype and <html>
9168:
9169: Inputs: none
9170:
9171: =cut
9172:
9173: sub xml_begin {
9174: my ($is_frameset) = @_;
9175: my $output='';
9176:
9177: if ($env{'browser.mathml'}) {
9178: $output='<?xml version="1.0"?>'
9179: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
9180: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
9181:
9182: # .'<!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">] >'
9183: .'<!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">'
9184: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
9185: .'xmlns="http://www.w3.org/1999/xhtml">';
9186: } elsif ($is_frameset) {
9187: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
9188: '<html>'."\n";
9189: } else {
9190: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
9191: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
9192: }
9193: return $output;
9194: }
9195:
9196: =pod
9197:
9198: =item * &start_page()
9199:
9200: Returns a complete <html> .. <body> section for LON-CAPA web pages.
9201:
9202: Inputs:
9203:
9204: =over 4
9205:
9206: $title - optional title for the page
9207:
9208: $head_extra - optional extra HTML to incude inside the <head>
9209:
9210: $args - additional optional args supported are:
9211:
9212: =over 8
9213:
9214: only_body -> is true will set &bodytag() onlybodytag
9215: arg on
9216: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
9217: add_entries -> additional attributes to add to the <body>
9218: domain -> force to color decorate a page for a
9219: specific domain
9220: function -> force usage of a specific rolish color
9221: scheme
9222: redirect -> see &headtag()
9223: bgcolor -> override the default page bg color
9224: js_ready -> return a string ready for being used in
9225: a javascript writeln
9226: html_encode -> return a string ready for being used in
9227: a html attribute
9228: force_register -> if is true will turn on the &bodytag()
9229: $forcereg arg
9230: frameset -> if true will start with a <frameset>
9231: rather than <body>
9232: skip_phases -> hash ref of
9233: head -> skip the <html><head> generation
9234: body -> skip all <body> generation
9235: no_auto_mt_title -> prevent &mt()ing the title arg
9236: bread_crumbs -> Array containing breadcrumbs
9237: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
9238: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
9239: to lonhtmlcommon::breadcrumbs
9240: group -> includes the current group, if page is for a
9241: specific group
9242: use_absolute -> for request for external resource or syllabus, this
9243: will contain https://<hostname> if server uses
9244: https (as per hosts.tab), but request is for http
9245: hostname -> hostname, originally from $r->hostname(), (optional).
9246: links_disabled -> Links in primary and secondary menus are disabled
9247: (Can enable them once page has loaded - see lonroles.pm
9248: for an example).
9249: links_target -> Target for links, e.g., _parent (optional).
9250:
9251: =back
9252:
9253: =back
9254:
9255: =cut
9256:
9257: sub start_page {
9258: my ($title,$head_extra,$args) = @_;
9259: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
9260:
9261: $env{'internal.start_page'}++;
9262: my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
9263:
9264: if (! exists($args->{'skip_phases'}{'head'}) ) {
9265: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
9266: }
9267:
9268: if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
9269: if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
9270: unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
9271: $args->{'no_primary_menu'} = 1;
9272: }
9273: unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
9274: $args->{'no_inline_menu'} = 1;
9275: }
9276: if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
9277: map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
9278: }
9279: } else {
9280: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9281: my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
9282: if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
9283: unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
9284: $args->{'no_primary_menu'} = 1;
9285: }
9286: unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
9287: $args->{'no_inline_menu'} = 1;
9288: }
9289: if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
9290: map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
9291: }
9292: }
9293: }
9294: ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
9295: $env{'course.'.$env{'request.course.id'}.'.domain'},
9296: $env{'course.'.$env{'request.course.id'}.'.num'});
9297: } elsif ($env{'request.course.id'}) {
9298: my $expiretime=600;
9299: if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
9300: &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
9301: }
9302: my ($deeplinkmenu,$menuref);
9303: ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
9304: if ($menucoll) {
9305: if (ref($menuref) eq 'HASH') {
9306: %menu = %{$menuref};
9307: }
9308: if ($menu{'top'} eq 'n') {
9309: $args->{'no_primary_menu'} = 1;
9310: }
9311: if ($menu{'inline'} eq 'n') {
9312: unless (&Apache::lonnet::allowed('opa')) {
9313: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9314: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9315: my $crstype = &course_type();
9316: my $now = time;
9317: my $ccrole;
9318: if ($crstype eq 'Community') {
9319: $ccrole = 'co';
9320: } else {
9321: $ccrole = 'cc';
9322: }
9323: if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
9324: my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
9325: if ((($start) && ($start<0)) ||
9326: (($end) && ($end<$now)) ||
9327: (($start) && ($now<$start))) {
9328: $args->{'no_inline_menu'} = 1;
9329: }
9330: } else {
9331: $args->{'no_inline_menu'} = 1;
9332: }
9333: }
9334: }
9335: }
9336: }
9337:
9338: if (! exists($args->{'skip_phases'}{'body'}) ) {
9339: if ($args->{'frameset'}) {
9340: my $attr_string = &make_attr_string($args->{'force_register'},
9341: $args->{'add_entries'});
9342: $result .= "\n<frameset $attr_string>\n";
9343: } else {
9344: $result .=
9345: &bodytag($title,
9346: $args->{'function'}, $args->{'add_entries'},
9347: $args->{'only_body'}, $args->{'domain'},
9348: $args->{'force_register'}, $args->{'no_nav_bar'},
9349: $args->{'bgcolor'}, $args,
9350: \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
9351: }
9352: }
9353:
9354: if ($args->{'js_ready'}) {
9355: $result = &js_ready($result);
9356: }
9357: if ($args->{'html_encode'}) {
9358: $result = &html_encode($result);
9359: }
9360:
9361: # Preparation for new and consistent functionlist at top of screen
9362: # if ($args->{'functionlist'}) {
9363: # $result .= &build_functionlist();
9364: #}
9365:
9366: # Don't add anything more if only_body wanted or in const space
9367: return $result if $args->{'only_body'}
9368: || $env{'request.state'} eq 'construct';
9369:
9370: #Breadcrumbs
9371: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
9372: &Apache::lonhtmlcommon::clear_breadcrumbs();
9373: #if any br links exists, add them to the breadcrumbs
9374: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
9375: foreach my $crumb (@{$args->{'bread_crumbs'}}){
9376: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
9377: }
9378: }
9379: # if @advtools array contains items add then to the breadcrumbs
9380: if (@advtools > 0) {
9381: &Apache::lonmenu::advtools_crumbs(@advtools);
9382: }
9383: my $menulink;
9384: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
9385: if ((exists($args->{'bread_crumbs_nomenu'})) ||
9386: ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
9387: ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
9388: ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
9389: (!$env{'request.role.adv'}))) {
9390: $menulink = 0;
9391: } else {
9392: undef($menulink);
9393: }
9394: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
9395: if(exists($args->{'bread_crumbs_component'})){
9396: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
9397: } else {
9398: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
9399: }
9400: }
9401: return $result;
9402: }
9403:
9404: sub end_page {
9405: my ($args) = @_;
9406: $env{'internal.end_page'}++;
9407: my $result;
9408: if ($args->{'discussion'}) {
9409: my ($target,$parser);
9410: if (ref($args->{'discussion'})) {
9411: ($target,$parser) =($args->{'discussion'}{'target'},
9412: $args->{'discussion'}{'parser'});
9413: }
9414: $result .= &Apache::lonxml::xmlend($target,$parser);
9415: }
9416: if ($args->{'frameset'}) {
9417: $result .= '</frameset>';
9418: } else {
9419: $result .= &endbodytag($args);
9420: }
9421: unless ($args->{'notbody'}) {
9422: $result .= "\n</html>";
9423: }
9424:
9425: if ($args->{'js_ready'}) {
9426: $result = &js_ready($result);
9427: }
9428:
9429: if ($args->{'html_encode'}) {
9430: $result = &html_encode($result);
9431: }
9432:
9433: return $result;
9434: }
9435:
9436: sub menucoll_in_effect {
9437: my ($menucoll,$deeplinkmenu,%menu);
9438: if ($env{'request.course.id'}) {
9439: $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
9440: if ($env{'request.deeplink.login'}) {
9441: my ($deeplink_symb,$deeplink,$check_login_symb);
9442: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9443: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9444: if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
9445: if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
9446: my $navmap = Apache::lonnavmaps::navmap->new();
9447: if (ref($navmap)) {
9448: $deeplink = $navmap->get_mapparam(undef,
9449: &Apache::lonnet::declutter($env{'request.noversionuri'}),
9450: '0.deeplink');
9451: } else {
9452: $check_login_symb = 1;
9453: }
9454: } else {
9455: my $symb = &Apache::lonnet::symbread();
9456: if ($symb) {
9457: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
9458: } else {
9459: $check_login_symb = 1;
9460: }
9461: }
9462: } else {
9463: $check_login_symb = 1;
9464: }
9465: if ($check_login_symb) {
9466: $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
9467: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9468: my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
9469: my $navmap = Apache::lonnavmaps::navmap->new();
9470: if (ref($navmap)) {
9471: $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
9472: }
9473: } else {
9474: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
9475: }
9476: }
9477: if ($deeplink ne '') {
9478: my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
9479: if ($display =~ /^\d+$/) {
9480: $deeplinkmenu = 1;
9481: $menucoll = $display;
9482: }
9483: }
9484: }
9485: if ($menucoll) {
9486: %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
9487: }
9488: }
9489: return ($menucoll,$deeplinkmenu,\%menu);
9490: }
9491:
9492: sub deeplink_login_symb {
9493: my ($cnum,$cdom) = @_;
9494: my $login_symb;
9495: if ($env{'request.deeplink.login'}) {
9496: $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
9497: }
9498: return $login_symb;
9499: }
9500:
9501: sub symb_from_tinyurl {
9502: my ($url,$cnum,$cdom) = @_;
9503: if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
9504: my $key = $1;
9505: my ($tinyurl,$login);
9506: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
9507: if (defined($cached)) {
9508: $tinyurl = $result;
9509: } else {
9510: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
9511: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
9512: if ($currtiny{$key} ne '') {
9513: $tinyurl = $currtiny{$key};
9514: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
9515: }
9516: }
9517: if ($tinyurl ne '') {
9518: my ($cnumreq,$symb) = split(/\&/,$tinyurl);
9519: if (wantarray) {
9520: return ($cnumreq,$symb);
9521: } elsif ($cnumreq eq $cnum) {
9522: return $symb;
9523: }
9524: }
9525: }
9526: if (wantarray) {
9527: return ();
9528: } else {
9529: return;
9530: }
9531: }
9532:
9533: sub wishlist_window {
9534: return(<<'ENDWISHLIST');
9535: <script type="text/javascript">
9536: // <![CDATA[
9537: // <!-- BEGIN LON-CAPA Internal
9538: function set_wishlistlink(title, path) {
9539: if (!title) {
9540: title = document.title;
9541: title = title.replace(/^LON-CAPA /,'');
9542: }
9543: title = encodeURIComponent(title);
9544: title = title.replace("'","\\\'");
9545: if (!path) {
9546: path = location.pathname;
9547: }
9548: path = encodeURIComponent(path);
9549: path = path.replace("'","\\\'");
9550: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
9551: 'wishlistNewLink','width=560,height=350,scrollbars=0');
9552: }
9553: // END LON-CAPA Internal -->
9554: // ]]>
9555: </script>
9556: ENDWISHLIST
9557: }
9558:
9559: sub modal_window {
9560: return(<<'ENDMODAL');
9561: <script type="text/javascript">
9562: // <![CDATA[
9563: // <!-- BEGIN LON-CAPA Internal
9564: var modalWindow = {
9565: parent:"body",
9566: windowId:null,
9567: content:null,
9568: width:null,
9569: height:null,
9570: close:function()
9571: {
9572: $(".LCmodal-window").remove();
9573: $(".LCmodal-overlay").remove();
9574: },
9575: open:function()
9576: {
9577: var modal = "";
9578: modal += "<div class=\"LCmodal-overlay\"></div>";
9579: 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;\">";
9580: modal += this.content;
9581: modal += "</div>";
9582:
9583: $(this.parent).append(modal);
9584:
9585: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
9586: $(".LCclose-window").click(function(){modalWindow.close();});
9587: $(".LCmodal-overlay").click(function(){modalWindow.close();});
9588: }
9589: };
9590: var openMyModal = function(source,width,height,scrolling,transparency,style)
9591: {
9592: source = source.replace(/'/g,"'");
9593: modalWindow.windowId = "myModal";
9594: modalWindow.width = width;
9595: modalWindow.height = height;
9596: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
9597: modalWindow.open();
9598: };
9599: // END LON-CAPA Internal -->
9600: // ]]>
9601: </script>
9602: ENDMODAL
9603: }
9604:
9605: sub modal_link {
9606: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
9607: unless ($width) { $width=480; }
9608: unless ($height) { $height=400; }
9609: unless ($scrolling) { $scrolling='yes'; }
9610: unless ($transparency) { $transparency='true'; }
9611:
9612: my $target_attr;
9613: if (defined($target)) {
9614: $target_attr = 'target="'.$target.'"';
9615: }
9616: return <<"ENDLINK";
9617: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
9618: ENDLINK
9619: }
9620:
9621: sub modal_adhoc_script {
9622: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9623: my $mathjax;
9624: if ($possmathjax) {
9625: $mathjax = <<'ENDJAX';
9626: if (typeof MathJax == 'object') {
9627: MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
9628: }
9629: ENDJAX
9630: }
9631: return (<<ENDADHOC);
9632: <script type="text/javascript">
9633: // <![CDATA[
9634: var $funcname = function()
9635: {
9636: modalWindow.windowId = "myModal";
9637: modalWindow.width = $width;
9638: modalWindow.height = $height;
9639: modalWindow.content = '$content';
9640: modalWindow.open();
9641: $mathjax
9642: };
9643: // ]]>
9644: </script>
9645: ENDADHOC
9646: }
9647:
9648: sub modal_adhoc_inner {
9649: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9650: my $innerwidth=$width-20;
9651: $content=&js_ready(
9652: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
9653: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
9654: $content.
9655: &end_scrollbox().
9656: &end_page()
9657: );
9658: return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
9659: }
9660:
9661: sub modal_adhoc_window {
9662: my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
9663: return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
9664: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
9665: }
9666:
9667: sub modal_adhoc_launch {
9668: my ($funcname,$width,$height,$content)=@_;
9669: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
9670: <script type="text/javascript">
9671: // <![CDATA[
9672: $funcname();
9673: // ]]>
9674: </script>
9675: ENDLAUNCH
9676: }
9677:
9678: sub modal_adhoc_close {
9679: return (<<ENDCLOSE);
9680: <script type="text/javascript">
9681: // <![CDATA[
9682: modalWindow.close();
9683: // ]]>
9684: </script>
9685: ENDCLOSE
9686: }
9687:
9688: sub togglebox_script {
9689: return(<<ENDTOGGLE);
9690: <script type="text/javascript">
9691: // <![CDATA[
9692: function LCtoggleDisplay(id,hidetext,showtext) {
9693: link = document.getElementById(id + "link").childNodes[0];
9694: with (document.getElementById(id).style) {
9695: if (display == "none" ) {
9696: display = "inline";
9697: link.nodeValue = hidetext;
9698: } else {
9699: display = "none";
9700: link.nodeValue = showtext;
9701: }
9702: }
9703: }
9704: // ]]>
9705: </script>
9706: ENDTOGGLE
9707: }
9708:
9709: sub start_togglebox {
9710: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
9711: unless ($heading) { $heading=''; } else { $heading.=' '; }
9712: unless ($showtext) { $showtext=&mt('show'); }
9713: unless ($hidetext) { $hidetext=&mt('hide'); }
9714: unless ($headerbg) { $headerbg='#FFFFFF'; }
9715: return &start_data_table().
9716: &start_data_table_header_row().
9717: '<td bgcolor="'.$headerbg.'">'.$heading.
9718: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
9719: $showtext.'\')">'.$showtext.'</a>]</td>'.
9720: &end_data_table_header_row().
9721: '<tr id="'.$id.'" style="display:none""><td>';
9722: }
9723:
9724: sub end_togglebox {
9725: return '</td></tr>'.&end_data_table();
9726: }
9727:
9728: sub LCprogressbar_script {
9729: my ($id,$number_to_do)=@_;
9730: if ($number_to_do) {
9731: return(<<ENDPROGRESS);
9732: <script type="text/javascript">
9733: // <![CDATA[
9734: \$('#progressbar$id').progressbar({
9735: value: 0,
9736: change: function(event, ui) {
9737: var newVal = \$(this).progressbar('option', 'value');
9738: \$('.pblabel', this).text(LCprogressTxt);
9739: }
9740: });
9741: // ]]>
9742: </script>
9743: ENDPROGRESS
9744: } else {
9745: return(<<ENDPROGRESS);
9746: <script type="text/javascript">
9747: // <![CDATA[
9748: \$('#progressbar$id').progressbar({
9749: value: false,
9750: create: function(event, ui) {
9751: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
9752: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
9753: }
9754: });
9755: // ]]>
9756: </script>
9757: ENDPROGRESS
9758: }
9759: }
9760:
9761: sub LCprogressbarUpdate_script {
9762: return(<<ENDPROGRESSUPDATE);
9763: <style type="text/css">
9764: .ui-progressbar { position:relative; }
9765: .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%; }
9766: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
9767: </style>
9768: <script type="text/javascript">
9769: // <![CDATA[
9770: var LCprogressTxt='---';
9771:
9772: function LCupdateProgress(percent,progresstext,id,maxnum) {
9773: LCprogressTxt=progresstext;
9774: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
9775: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
9776: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
9777: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
9778: } else {
9779: \$('#progressbar'+id).progressbar('value',percent);
9780: }
9781: }
9782: // ]]>
9783: </script>
9784: ENDPROGRESSUPDATE
9785: }
9786:
9787: my $LClastpercent;
9788: my $LCidcnt;
9789: my $LCcurrentid;
9790:
9791: sub LCprogressbar {
9792: my ($r,$number_to_do,$preamble)=@_;
9793: $LClastpercent=0;
9794: $LCidcnt++;
9795: $LCcurrentid=$$.'_'.$LCidcnt;
9796: my ($starting,$content);
9797: if ($number_to_do) {
9798: $starting=&mt('Starting');
9799: $content=(<<ENDPROGBAR);
9800: $preamble
9801: <div id="progressbar$LCcurrentid">
9802: <span class="pblabel">$starting</span>
9803: </div>
9804: ENDPROGBAR
9805: } else {
9806: $starting=&mt('Loading...');
9807: $LClastpercent='false';
9808: $content=(<<ENDPROGBAR);
9809: $preamble
9810: <div id="progressbar$LCcurrentid">
9811: <div class="progress-label">$starting</div>
9812: </div>
9813: ENDPROGBAR
9814: }
9815: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
9816: }
9817:
9818: sub LCprogressbarUpdate {
9819: my ($r,$val,$text,$number_to_do)=@_;
9820: if ($number_to_do) {
9821: unless ($val) {
9822: if ($LClastpercent) {
9823: $val=$LClastpercent;
9824: } else {
9825: $val=0;
9826: }
9827: }
9828: if ($val<0) { $val=0; }
9829: if ($val>100) { $val=0; }
9830: $LClastpercent=$val;
9831: unless ($text) { $text=$val.'%'; }
9832: } else {
9833: $val = 'false';
9834: }
9835: $text=&js_ready($text);
9836: &r_print($r,<<ENDUPDATE);
9837: <script type="text/javascript">
9838: // <![CDATA[
9839: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
9840: // ]]>
9841: </script>
9842: ENDUPDATE
9843: }
9844:
9845: sub LCprogressbarClose {
9846: my ($r)=@_;
9847: $LClastpercent=0;
9848: &r_print($r,<<ENDCLOSE);
9849: <script type="text/javascript">
9850: // <![CDATA[
9851: \$("#progressbar$LCcurrentid").hide('slow');
9852: // ]]>
9853: </script>
9854: ENDCLOSE
9855: }
9856:
9857: sub r_print {
9858: my ($r,$to_print)=@_;
9859: if ($r) {
9860: $r->print($to_print);
9861: $r->rflush();
9862: } else {
9863: print($to_print);
9864: }
9865: }
9866:
9867: sub html_encode {
9868: my ($result) = @_;
9869:
9870: $result = &HTML::Entities::encode($result,'<>&"');
9871:
9872: return $result;
9873: }
9874:
9875: sub js_ready {
9876: my ($result) = @_;
9877:
9878: $result =~ s/[\n\r]/ /xmsg;
9879: $result =~ s/\\/\\\\/xmsg;
9880: $result =~ s/'/\\'/xmsg;
9881: $result =~ s{</}{<\\/}xmsg;
9882:
9883: return $result;
9884: }
9885:
9886: sub validate_page {
9887: if ( exists($env{'internal.start_page'})
9888: && $env{'internal.start_page'} > 1) {
9889: &Apache::lonnet::logthis('start_page called multiple times '.
9890: $env{'internal.start_page'}.' '.
9891: $ENV{'request.filename'});
9892: }
9893: if ( exists($env{'internal.end_page'})
9894: && $env{'internal.end_page'} > 1) {
9895: &Apache::lonnet::logthis('end_page called multiple times '.
9896: $env{'internal.end_page'}.' '.
9897: $env{'request.filename'});
9898: }
9899: if ( exists($env{'internal.start_page'})
9900: && ! exists($env{'internal.end_page'})) {
9901: &Apache::lonnet::logthis('start_page called without end_page '.
9902: $env{'request.filename'});
9903: }
9904: if ( ! exists($env{'internal.start_page'})
9905: && exists($env{'internal.end_page'})) {
9906: &Apache::lonnet::logthis('end_page called without start_page'.
9907: $env{'request.filename'});
9908: }
9909: }
9910:
9911:
9912: sub start_scrollbox {
9913: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
9914: unless ($outerwidth) { $outerwidth='520px'; }
9915: unless ($width) { $width='500px'; }
9916: unless ($height) { $height='200px'; }
9917: my ($table_id,$div_id,$tdcol);
9918: if ($id ne '') {
9919: $table_id = ' id="table_'.$id.'"';
9920: $div_id = ' id="div_'.$id.'"';
9921: }
9922: if ($bgcolor ne '') {
9923: $tdcol = "background-color: $bgcolor;";
9924: }
9925: my $nicescroll_js;
9926: if ($env{'browser.mobile'}) {
9927: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
9928: }
9929: return <<"END";
9930: $nicescroll_js
9931:
9932: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
9933: <div style="overflow:auto; width:$width; height:$height;"$div_id>
9934: END
9935: }
9936:
9937: sub end_scrollbox {
9938: return '</div></td></tr></table>';
9939: }
9940:
9941: sub nicescroll_javascript {
9942: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
9943: my %options;
9944: if (ref($cursor) eq 'HASH') {
9945: %options = %{$cursor};
9946: }
9947: unless ($options{'railalign'} =~ /^left|right$/) {
9948: $options{'railalign'} = 'left';
9949: }
9950: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
9951: my $function = &get_users_function();
9952: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
9953: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
9954: $options{'cursorcolor'} = '#00F';
9955: }
9956: }
9957: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
9958: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
9959: $options{'cursoropacity'}='1.0';
9960: }
9961: } else {
9962: $options{'cursoropacity'}='1.0';
9963: }
9964: if ($options{'cursorfixedheight'} eq 'none') {
9965: delete($options{'cursorfixedheight'});
9966: } else {
9967: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
9968: }
9969: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
9970: delete($options{'railoffset'});
9971: }
9972: my @niceoptions;
9973: while (my($key,$value) = each(%options)) {
9974: if ($value =~ /^\{.+\}$/) {
9975: push(@niceoptions,$key.':'.$value);
9976: } else {
9977: push(@niceoptions,$key.':"'.$value.'"');
9978: }
9979: }
9980: my $nicescroll_js = '
9981: $(document).ready(
9982: function() {
9983: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
9984: }
9985: );
9986: ';
9987: if ($framecheck) {
9988: $nicescroll_js .= '
9989: function expand_div(caller) {
9990: if (top === self) {
9991: document.getElementById("'.$id.'").style.width = "auto";
9992: document.getElementById("'.$id.'").style.height = "auto";
9993: } else {
9994: try {
9995: if (parent.frames) {
9996: if (parent.frames.length > 1) {
9997: var framesrc = parent.frames[1].location.href;
9998: var currsrc = framesrc.replace(/\#.*$/,"");
9999: if ((caller == "search") || (currsrc == "'.$location.'")) {
10000: document.getElementById("'.$id.'").style.width = "auto";
10001: document.getElementById("'.$id.'").style.height = "auto";
10002: }
10003: }
10004: }
10005: } catch (e) {
10006: return;
10007: }
10008: }
10009: return;
10010: }
10011: ';
10012: }
10013: if ($needjsready) {
10014: $nicescroll_js = '
10015: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10016: } else {
10017: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10018: }
10019: return $nicescroll_js;
10020: }
10021:
10022: sub simple_error_page {
10023: my ($r,$title,$msg,$args) = @_;
10024: my %displayargs;
10025: if (ref($args) eq 'HASH') {
10026: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10027: if ($args->{'only_body'}) {
10028: $displayargs{'only_body'} = 1;
10029: }
10030: if ($args->{'no_nav_bar'}) {
10031: $displayargs{'no_nav_bar'} = 1;
10032: }
10033: } else {
10034: $msg = &mt($msg);
10035: }
10036:
10037: my $page =
10038: &Apache::loncommon::start_page($title,'',\%displayargs).
10039: '<p class="LC_error">'.$msg.'</p>'.
10040: &Apache::loncommon::end_page();
10041: if (ref($r)) {
10042: $r->print($page);
10043: return;
10044: }
10045: return $page;
10046: }
10047:
10048: {
10049: my @row_count;
10050:
10051: sub start_data_table_count {
10052: unshift(@row_count, 0);
10053: return;
10054: }
10055:
10056: sub end_data_table_count {
10057: shift(@row_count);
10058: return;
10059: }
10060:
10061: sub start_data_table {
10062: my ($add_class,$id) = @_;
10063: my $css_class = (join(' ','LC_data_table',$add_class));
10064: my $table_id;
10065: if (defined($id)) {
10066: $table_id = ' id="'.$id.'"';
10067: }
10068: &start_data_table_count();
10069: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10070: }
10071:
10072: sub end_data_table {
10073: &end_data_table_count();
10074: return '</table>'."\n";;
10075: }
10076:
10077: sub start_data_table_row {
10078: my ($add_class, $id) = @_;
10079: $row_count[0]++;
10080: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10081: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10082: $id = (' id="'.$id.'"') unless ($id eq '');
10083: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10084: }
10085:
10086: sub continue_data_table_row {
10087: my ($add_class, $id) = @_;
10088: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10089: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10090: $id = (' id="'.$id.'"') unless ($id eq '');
10091: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10092: }
10093:
10094: sub end_data_table_row {
10095: return '</tr>'."\n";;
10096: }
10097:
10098: sub start_data_table_empty_row {
10099: # $row_count[0]++;
10100: return '<tr class="LC_empty_row" >'."\n";;
10101: }
10102:
10103: sub end_data_table_empty_row {
10104: return '</tr>'."\n";;
10105: }
10106:
10107: sub start_data_table_header_row {
10108: return '<tr class="LC_header_row">'."\n";;
10109: }
10110:
10111: sub end_data_table_header_row {
10112: return '</tr>'."\n";;
10113: }
10114:
10115: sub data_table_caption {
10116: my $caption = shift;
10117: return "<caption class=\"LC_caption\">$caption</caption>";
10118: }
10119: }
10120:
10121: =pod
10122:
10123: =item * &inhibit_menu_check($arg)
10124:
10125: Checks for a inhibitmenu state and generates output to preserve it
10126:
10127: Inputs: $arg - can be any of
10128: - undef - in which case the return value is a string
10129: to add into arguments list of a uri
10130: - 'input' - in which case the return value is a HTML
10131: <form> <input> field of type hidden to
10132: preserve the value
10133: - a url - in which case the return value is the url with
10134: the neccesary cgi args added to preserve the
10135: inhibitmenu state
10136: - a ref to a url - no return value, but the string is
10137: updated to include the neccessary cgi
10138: args to preserve the inhibitmenu state
10139:
10140: =cut
10141:
10142: sub inhibit_menu_check {
10143: my ($arg) = @_;
10144: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10145: if ($arg eq 'input') {
10146: if ($env{'form.inhibitmenu'}) {
10147: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10148: } else {
10149: return
10150: }
10151: }
10152: if ($env{'form.inhibitmenu'}) {
10153: if (ref($arg)) {
10154: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10155: } elsif ($arg eq '') {
10156: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10157: } else {
10158: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10159: }
10160: }
10161: if (!ref($arg)) {
10162: return $arg;
10163: }
10164: }
10165:
10166: ###############################################
10167:
10168: =pod
10169:
10170: =back
10171:
10172: =head1 User Information Routines
10173:
10174: =over 4
10175:
10176: =item * &get_users_function()
10177:
10178: Used by &bodytag to determine the current users primary role.
10179: Returns either 'student','coordinator','admin', or 'author'.
10180:
10181: =cut
10182:
10183: ###############################################
10184: sub get_users_function {
10185: my $function = 'norole';
10186: if ($env{'request.role'}=~/^(st)/) {
10187: $function='student';
10188: }
10189: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10190: $function='coordinator';
10191: }
10192: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10193: $function='admin';
10194: }
10195: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10196: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10197: $function='author';
10198: }
10199: return $function;
10200: }
10201:
10202: ###############################################
10203:
10204: =pod
10205:
10206: =item * &show_course()
10207:
10208: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10209: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10210:
10211: Inputs:
10212: None
10213:
10214: Outputs:
10215: Scalar: 1 if 'Course' to be used, 0 otherwise.
10216:
10217: =cut
10218:
10219: ###############################################
10220: sub show_course {
10221: my $course = !$env{'user.adv'};
10222: if (!$env{'user.adv'}) {
10223: foreach my $env (keys(%env)) {
10224: next if ($env !~ m/^user\.priv\./);
10225: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10226: $course = 0;
10227: last;
10228: }
10229: }
10230: }
10231: return $course;
10232: }
10233:
10234: ###############################################
10235:
10236: =pod
10237:
10238: =item * &check_user_status()
10239:
10240: Determines current status of supplied role for a
10241: specific user. Roles can be active, previous or future.
10242:
10243: Inputs:
10244: user's domain, user's username, course's domain,
10245: course's number, optional section ID.
10246:
10247: Outputs:
10248: role status: active, previous or future.
10249:
10250: =cut
10251:
10252: sub check_user_status {
10253: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10254: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10255: my @uroles = keys(%userinfo);
10256: my $srchstr;
10257: my $active_chk = 'none';
10258: my $now = time;
10259: if (@uroles > 0) {
10260: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10261: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10262: } else {
10263: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10264: }
10265: if (grep/^\Q$srchstr\E$/,@uroles) {
10266: my $role_end = 0;
10267: my $role_start = 0;
10268: $active_chk = 'active';
10269: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10270: $role_end = $1;
10271: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10272: $role_start = $1;
10273: }
10274: }
10275: if ($role_start > 0) {
10276: if ($now < $role_start) {
10277: $active_chk = 'future';
10278: }
10279: }
10280: if ($role_end > 0) {
10281: if ($now > $role_end) {
10282: $active_chk = 'previous';
10283: }
10284: }
10285: }
10286: }
10287: return $active_chk;
10288: }
10289:
10290: ###############################################
10291:
10292: =pod
10293:
10294: =item * &get_sections()
10295:
10296: Determines all the sections for a course including
10297: sections with students and sections containing other roles.
10298: Incoming parameters:
10299:
10300: 1. domain
10301: 2. course number
10302: 3. reference to array containing roles for which sections should
10303: be gathered (optional).
10304: 4. reference to array containing status types for which sections
10305: should be gathered (optional).
10306:
10307: If the third argument is undefined, sections are gathered for any role.
10308: If the fourth argument is undefined, sections are gathered for any status.
10309: Permissible values are 'active' or 'future' or 'previous'.
10310:
10311: Returns section hash (keys are section IDs, values are
10312: number of users in each section), subject to the
10313: optional roles filter, optional status filter
10314:
10315: =cut
10316:
10317: ###############################################
10318: sub get_sections {
10319: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10320: if (!defined($cdom) || !defined($cnum)) {
10321: my $cid = $env{'request.course.id'};
10322:
10323: return if (!defined($cid));
10324:
10325: $cdom = $env{'course.'.$cid.'.domain'};
10326: $cnum = $env{'course.'.$cid.'.num'};
10327: }
10328:
10329: my %sectioncount;
10330: my $now = time;
10331:
10332: my $check_students = 1;
10333: my $only_students = 0;
10334: if (ref($possible_roles) eq 'ARRAY') {
10335: if (grep(/^st$/,@{$possible_roles})) {
10336: if (@{$possible_roles} == 1) {
10337: $only_students = 1;
10338: }
10339: } else {
10340: $check_students = 0;
10341: }
10342: }
10343:
10344: if ($check_students) {
10345: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10346: my $sec_index = &Apache::loncoursedata::CL_SECTION();
10347: my $status_index = &Apache::loncoursedata::CL_STATUS();
10348: my $start_index = &Apache::loncoursedata::CL_START();
10349: my $end_index = &Apache::loncoursedata::CL_END();
10350: my $status;
10351: while (my ($student,$data) = each(%$classlist)) {
10352: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10353: $data->[$status_index],
10354: $data->[$start_index],
10355: $data->[$end_index]);
10356: if ($stu_status eq 'Active') {
10357: $status = 'active';
10358: } elsif ($end < $now) {
10359: $status = 'previous';
10360: } elsif ($start > $now) {
10361: $status = 'future';
10362: }
10363: if ($section ne '-1' && $section !~ /^\s*$/) {
10364: if ((!defined($possible_status)) || (($status ne '') &&
10365: (grep/^\Q$status\E$/,@{$possible_status}))) {
10366: $sectioncount{$section}++;
10367: }
10368: }
10369: }
10370: }
10371: if ($only_students) {
10372: return %sectioncount;
10373: }
10374: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10375: foreach my $user (sort(keys(%courseroles))) {
10376: if ($user !~ /^(\w{2})/) { next; }
10377: my ($role) = ($user =~ /^(\w{2})/);
10378: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10379: my ($section,$status);
10380: if ($role eq 'cr' &&
10381: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10382: $section=$1;
10383: }
10384: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10385: if (!defined($section) || $section eq '-1') { next; }
10386: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10387: if ($end == -1 && $start == -1) {
10388: next; #deleted role
10389: }
10390: if (!defined($possible_status)) {
10391: $sectioncount{$section}++;
10392: } else {
10393: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10394: $status = 'active';
10395: } elsif ($end < $now) {
10396: $status = 'future';
10397: } elsif ($start > $now) {
10398: $status = 'previous';
10399: }
10400: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10401: $sectioncount{$section}++;
10402: }
10403: }
10404: }
10405: return %sectioncount;
10406: }
10407:
10408: ###############################################
10409:
10410: =pod
10411:
10412: =item * &get_course_users()
10413:
10414: Retrieves usernames:domains for users in the specified course
10415: with specific role(s), and access status.
10416:
10417: Incoming parameters:
10418: 1. course domain
10419: 2. course number
10420: 3. access status: users must have - either active,
10421: previous, future, or all.
10422: 4. reference to array of permissible roles
10423: 5. reference to array of section restrictions (optional)
10424: 6. reference to results object (hash of hashes).
10425: 7. reference to optional userdata hash
10426: 8. reference to optional statushash
10427: 9. flag if privileged users (except those set to unhide in
10428: course settings) should be excluded
10429: Keys of top level results hash are roles.
10430: Keys of inner hashes are username:domain, with
10431: values set to access type.
10432: Optional userdata hash returns an array with arguments in the
10433: same order as loncoursedata::get_classlist() for student data.
10434:
10435: Optional statushash returns
10436:
10437: Entries for end, start, section and status are blank because
10438: of the possibility of multiple values for non-student roles.
10439:
10440: =cut
10441:
10442: ###############################################
10443:
10444: sub get_course_users {
10445: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10446: my %idx = ();
10447: my %seclists;
10448:
10449: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10450: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
10451: $idx{end} = &Apache::loncoursedata::CL_END();
10452: $idx{start} = &Apache::loncoursedata::CL_START();
10453: $idx{id} = &Apache::loncoursedata::CL_ID();
10454: $idx{section} = &Apache::loncoursedata::CL_SECTION();
10455: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10456: $idx{status} = &Apache::loncoursedata::CL_STATUS();
10457:
10458: if (grep(/^st$/,@{$roles})) {
10459: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10460: my $now = time;
10461: foreach my $student (keys(%{$classlist})) {
10462: my $match = 0;
10463: my $secmatch = 0;
10464: my $section = $$classlist{$student}[$idx{section}];
10465: my $status = $$classlist{$student}[$idx{status}];
10466: if ($section eq '') {
10467: $section = 'none';
10468: }
10469: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10470: if (grep(/^all$/,@{$sections})) {
10471: $secmatch = 1;
10472: } elsif ($$classlist{$student}[$idx{section}] eq '') {
10473: if (grep(/^none$/,@{$sections})) {
10474: $secmatch = 1;
10475: }
10476: } else {
10477: if (grep(/^\Q$section\E$/,@{$sections})) {
10478: $secmatch = 1;
10479: }
10480: }
10481: if (!$secmatch) {
10482: next;
10483: }
10484: }
10485: if (defined($$types{'active'})) {
10486: if ($$classlist{$student}[$idx{status}] eq 'Active') {
10487: push(@{$$users{st}{$student}},'active');
10488: $match = 1;
10489: }
10490: }
10491: if (defined($$types{'previous'})) {
10492: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10493: push(@{$$users{st}{$student}},'previous');
10494: $match = 1;
10495: }
10496: }
10497: if (defined($$types{'future'})) {
10498: if ($$classlist{$student}[$idx{status}] eq 'Future') {
10499: push(@{$$users{st}{$student}},'future');
10500: $match = 1;
10501: }
10502: }
10503: if ($match) {
10504: push(@{$seclists{$student}},$section);
10505: if (ref($userdata) eq 'HASH') {
10506: $$userdata{$student} = $$classlist{$student};
10507: }
10508: if (ref($statushash) eq 'HASH') {
10509: $statushash->{$student}{'st'}{$section} = $status;
10510: }
10511: }
10512: }
10513: }
10514: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10515: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10516: my $now = time;
10517: my %displaystatus = ( previous => 'Expired',
10518: active => 'Active',
10519: future => 'Future',
10520: );
10521: my (%nothide,@possdoms);
10522: if ($hidepriv) {
10523: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10524: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10525: if ($user !~ /:/) {
10526: $nothide{join(':',split(/[\@]/,$user))}=1;
10527: } else {
10528: $nothide{$user} = 1;
10529: }
10530: }
10531: my @possdoms = ($cdom);
10532: if ($coursehash{'checkforpriv'}) {
10533: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10534: }
10535: }
10536: foreach my $person (sort(keys(%coursepersonnel))) {
10537: my $match = 0;
10538: my $secmatch = 0;
10539: my $status;
10540: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10541: $user =~ s/:$//;
10542: my ($end,$start) = split(/:/,$coursepersonnel{$person});
10543: if ($end == -1 || $start == -1) {
10544: next;
10545: }
10546: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10547: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10548: my ($uname,$udom) = split(/:/,$user);
10549: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10550: if (grep(/^all$/,@{$sections})) {
10551: $secmatch = 1;
10552: } elsif ($usec eq '') {
10553: if (grep(/^none$/,@{$sections})) {
10554: $secmatch = 1;
10555: }
10556: } else {
10557: if (grep(/^\Q$usec\E$/,@{$sections})) {
10558: $secmatch = 1;
10559: }
10560: }
10561: if (!$secmatch) {
10562: next;
10563: }
10564: }
10565: if ($usec eq '') {
10566: $usec = 'none';
10567: }
10568: if ($uname ne '' && $udom ne '') {
10569: if ($hidepriv) {
10570: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10571: (!$nothide{$uname.':'.$udom})) {
10572: next;
10573: }
10574: }
10575: if ($end > 0 && $end < $now) {
10576: $status = 'previous';
10577: } elsif ($start > $now) {
10578: $status = 'future';
10579: } else {
10580: $status = 'active';
10581: }
10582: foreach my $type (keys(%{$types})) {
10583: if ($status eq $type) {
10584: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10585: push(@{$$users{$role}{$user}},$type);
10586: }
10587: $match = 1;
10588: }
10589: }
10590: if (($match) && (ref($userdata) eq 'HASH')) {
10591: if (!exists($$userdata{$uname.':'.$udom})) {
10592: &get_user_info($udom,$uname,\%idx,$userdata);
10593: }
10594: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10595: push(@{$seclists{$uname.':'.$udom}},$usec);
10596: }
10597: if (ref($statushash) eq 'HASH') {
10598: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10599: }
10600: }
10601: }
10602: }
10603: }
10604: if (grep(/^ow$/,@{$roles})) {
10605: if ((defined($cdom)) && (defined($cnum))) {
10606: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10607: if ( defined($csettings{'internal.courseowner'}) ) {
10608: my $owner = $csettings{'internal.courseowner'};
10609: next if ($owner eq '');
10610: my ($ownername,$ownerdom);
10611: if ($owner =~ /^([^:]+):([^:]+)$/) {
10612: $ownername = $1;
10613: $ownerdom = $2;
10614: } else {
10615: $ownername = $owner;
10616: $ownerdom = $cdom;
10617: $owner = $ownername.':'.$ownerdom;
10618: }
10619: @{$$users{'ow'}{$owner}} = 'any';
10620: if (defined($userdata) &&
10621: !exists($$userdata{$owner})) {
10622: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
10623: if (!grep(/^none$/,@{$seclists{$owner}})) {
10624: push(@{$seclists{$owner}},'none');
10625: }
10626: if (ref($statushash) eq 'HASH') {
10627: $statushash->{$owner}{'ow'}{'none'} = 'Any';
10628: }
10629: }
10630: }
10631: }
10632: }
10633: foreach my $user (keys(%seclists)) {
10634: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10635: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10636: }
10637: }
10638: return;
10639: }
10640:
10641: sub get_user_info {
10642: my ($udom,$uname,$idx,$userdata) = @_;
10643: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
10644: &plainname($uname,$udom,'lastname');
10645: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10646: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10647: my %idhash = &Apache::lonnet::idrget($udom,($uname));
10648: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
10649: return;
10650: }
10651:
10652: ###############################################
10653:
10654: =pod
10655:
10656: =item * &get_user_quota()
10657:
10658: Retrieves quota assigned for storage of user files.
10659: Default is to report quota for portfolio files.
10660:
10661: Incoming parameters:
10662: 1. user's username
10663: 2. user's domain
10664: 3. quota name - portfolio, author, or course
10665: (if no quota name provided, defaults to portfolio).
10666: 4. crstype - official, unofficial, textbook, placement or community,
10667: if quota name is course
10668:
10669: Returns:
10670: 1. Disk quota (in MB) assigned to student.
10671: 2. (Optional) Type of setting: custom or default
10672: (individually assigned or default for user's
10673: institutional status).
10674: 3. (Optional) - User's institutional status (e.g., faculty, staff
10675: or student - types as defined in localenroll::inst_usertypes
10676: for user's domain, which determines default quota for user.
10677: 4. (Optional) - Default quota which would apply to the user.
10678:
10679: If a value has been stored in the user's environment,
10680: it will return that, otherwise it returns the maximal default
10681: defined for the user's institutional status(es) in the domain.
10682:
10683: =cut
10684:
10685: ###############################################
10686:
10687:
10688: sub get_user_quota {
10689: my ($uname,$udom,$quotaname,$crstype) = @_;
10690: my ($quota,$quotatype,$settingstatus,$defquota);
10691: if (!defined($udom)) {
10692: $udom = $env{'user.domain'};
10693: }
10694: if (!defined($uname)) {
10695: $uname = $env{'user.name'};
10696: }
10697: if (($udom eq '' || $uname eq '') ||
10698: ($udom eq 'public') && ($uname eq 'public')) {
10699: $quota = 0;
10700: $quotatype = 'default';
10701: $defquota = 0;
10702: } else {
10703: my $inststatus;
10704: if ($quotaname eq 'course') {
10705: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10706: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10707: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10708: } else {
10709: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10710: $quota = $cenv{'internal.uploadquota'};
10711: }
10712: } else {
10713: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10714: if ($quotaname eq 'author') {
10715: $quota = $env{'environment.authorquota'};
10716: } else {
10717: $quota = $env{'environment.portfolioquota'};
10718: }
10719: $inststatus = $env{'environment.inststatus'};
10720: } else {
10721: my %userenv =
10722: &Apache::lonnet::get('environment',['portfolioquota',
10723: 'authorquota','inststatus'],$udom,$uname);
10724: my ($tmp) = keys(%userenv);
10725: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10726: if ($quotaname eq 'author') {
10727: $quota = $userenv{'authorquota'};
10728: } else {
10729: $quota = $userenv{'portfolioquota'};
10730: }
10731: $inststatus = $userenv{'inststatus'};
10732: } else {
10733: undef(%userenv);
10734: }
10735: }
10736: }
10737: if ($quota eq '' || wantarray) {
10738: if ($quotaname eq 'course') {
10739: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10740: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10741: ($crstype eq 'community') || ($crstype eq 'textbook') ||
10742: ($crstype eq 'placement')) {
10743: $defquota = $domdefs{$crstype.'quota'};
10744: }
10745: if ($defquota eq '') {
10746: $defquota = 500;
10747: }
10748: } else {
10749: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10750: }
10751: if ($quota eq '') {
10752: $quota = $defquota;
10753: $quotatype = 'default';
10754: } else {
10755: $quotatype = 'custom';
10756: }
10757: }
10758: }
10759: if (wantarray) {
10760: return ($quota,$quotatype,$settingstatus,$defquota);
10761: } else {
10762: return $quota;
10763: }
10764: }
10765:
10766: ###############################################
10767:
10768: =pod
10769:
10770: =item * &default_quota()
10771:
10772: Retrieves default quota assigned for storage of user portfolio files,
10773: given an (optional) user's institutional status.
10774:
10775: Incoming parameters:
10776:
10777: 1. domain
10778: 2. (Optional) institutional status(es). This is a : separated list of
10779: status types (e.g., faculty, staff, student etc.)
10780: which apply to the user for whom the default is being retrieved.
10781: If the institutional status string in undefined, the domain
10782: default quota will be returned.
10783: 3. quota name - portfolio, author, or course
10784: (if no quota name provided, defaults to portfolio).
10785:
10786: Returns:
10787:
10788: 1. Default disk quota (in MB) for user portfolios in the domain.
10789: 2. (Optional) institutional type which determined the value of the
10790: default quota.
10791:
10792: If a value has been stored in the domain's configuration db,
10793: it will return that, otherwise it returns 20 (for backwards
10794: compatibility with domains which have not set up a configuration
10795: db file; the original statically defined portfolio quota was 20 MB).
10796:
10797: If the user's status includes multiple types (e.g., staff and student),
10798: the largest default quota which applies to the user determines the
10799: default quota returned.
10800:
10801: =cut
10802:
10803: ###############################################
10804:
10805:
10806: sub default_quota {
10807: my ($udom,$inststatus,$quotaname) = @_;
10808: my ($defquota,$settingstatus);
10809: my %quotahash = &Apache::lonnet::get_dom('configuration',
10810: ['quotas'],$udom);
10811: my $key = 'defaultquota';
10812: if ($quotaname eq 'author') {
10813: $key = 'authorquota';
10814: }
10815: if (ref($quotahash{'quotas'}) eq 'HASH') {
10816: if ($inststatus ne '') {
10817: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10818: foreach my $item (@statuses) {
10819: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10820: if ($quotahash{'quotas'}{$key}{$item} ne '') {
10821: if ($defquota eq '') {
10822: $defquota = $quotahash{'quotas'}{$key}{$item};
10823: $settingstatus = $item;
10824: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10825: $defquota = $quotahash{'quotas'}{$key}{$item};
10826: $settingstatus = $item;
10827: }
10828: }
10829: } elsif ($key eq 'defaultquota') {
10830: if ($quotahash{'quotas'}{$item} ne '') {
10831: if ($defquota eq '') {
10832: $defquota = $quotahash{'quotas'}{$item};
10833: $settingstatus = $item;
10834: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10835: $defquota = $quotahash{'quotas'}{$item};
10836: $settingstatus = $item;
10837: }
10838: }
10839: }
10840: }
10841: }
10842: if ($defquota eq '') {
10843: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10844: $defquota = $quotahash{'quotas'}{$key}{'default'};
10845: } elsif ($key eq 'defaultquota') {
10846: $defquota = $quotahash{'quotas'}{'default'};
10847: }
10848: $settingstatus = 'default';
10849: if ($defquota eq '') {
10850: if ($quotaname eq 'author') {
10851: $defquota = 500;
10852: }
10853: }
10854: }
10855: } else {
10856: $settingstatus = 'default';
10857: if ($quotaname eq 'author') {
10858: $defquota = 500;
10859: } else {
10860: $defquota = 20;
10861: }
10862: }
10863: if (wantarray) {
10864: return ($defquota,$settingstatus);
10865: } else {
10866: return $defquota;
10867: }
10868: }
10869:
10870: ###############################################
10871:
10872: =pod
10873:
10874: =item * &excess_filesize_warning()
10875:
10876: Returns warning message if upload of file to authoring space, or copying
10877: of existing file within authoring space will cause quota for the authoring
10878: space to be exceeded.
10879:
10880: Same, if upload of a file directly to a course/community via Course Editor
10881: will cause quota for uploaded content for the course to be exceeded.
10882:
10883: Inputs: 7
10884: 1. username or coursenum
10885: 2. domain
10886: 3. context ('author' or 'course')
10887: 4. filename of file for which action is being requested
10888: 5. filesize (kB) of file
10889: 6. action being taken: copy or upload.
10890: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10891:
10892: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10893: otherwise return null.
10894:
10895: =back
10896:
10897: =cut
10898:
10899: sub excess_filesize_warning {
10900: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10901: my $current_disk_usage = 0;
10902: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10903: if ($context eq 'author') {
10904: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10905: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10906: } else {
10907: foreach my $subdir ('docs','supplemental') {
10908: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10909: }
10910: }
10911: $disk_quota = int($disk_quota * 1000);
10912: if (($current_disk_usage + $filesize) > $disk_quota) {
10913: return '<p class="LC_warning">'.
10914: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10915: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10916: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10917: $disk_quota,$current_disk_usage).
10918: '</p>';
10919: }
10920: return;
10921: }
10922:
10923: ###############################################
10924:
10925:
10926:
10927:
10928: sub get_secgrprole_info {
10929: my ($cdom,$cnum,$needroles,$type) = @_;
10930: my %sections_count = &get_sections($cdom,$cnum);
10931: my @sections = (sort {$a <=> $b} keys(%sections_count));
10932: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10933: my @groups = sort(keys(%curr_groups));
10934: my $allroles = [];
10935: my $rolehash;
10936: my $accesshash = {
10937: active => 'Currently has access',
10938: future => 'Will have future access',
10939: previous => 'Previously had access',
10940: };
10941: if ($needroles) {
10942: $rolehash = {'all' => 'all'};
10943: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10944: if (&Apache::lonnet::error(%user_roles)) {
10945: undef(%user_roles);
10946: }
10947: foreach my $item (keys(%user_roles)) {
10948: my ($role)=split(/\:/,$item,2);
10949: if ($role eq 'cr') { next; }
10950: if ($role =~ /^cr/) {
10951: $$rolehash{$role} = (split('/',$role))[3];
10952: } else {
10953: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10954: }
10955: }
10956: foreach my $key (sort(keys(%{$rolehash}))) {
10957: push(@{$allroles},$key);
10958: }
10959: push (@{$allroles},'st');
10960: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10961: }
10962: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10963: }
10964:
10965: sub user_picker {
10966: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10967: my $currdom = $dom;
10968: my @alldoms = &Apache::lonnet::all_domains();
10969: if (@alldoms == 1) {
10970: my %domsrch = &Apache::lonnet::get_dom('configuration',
10971: ['directorysrch'],$alldoms[0]);
10972: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10973: my $showdom = $domdesc;
10974: if ($showdom eq '') {
10975: $showdom = $dom;
10976: }
10977: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10978: if ((!$domsrch{'directorysrch'}{'available'}) &&
10979: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10980: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10981: }
10982: }
10983: }
10984: my %curr_selected = (
10985: srchin => 'dom',
10986: srchby => 'lastname',
10987: );
10988: my $srchterm;
10989: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10990: if ($srch->{'srchby'} ne '') {
10991: $curr_selected{'srchby'} = $srch->{'srchby'};
10992: }
10993: if ($srch->{'srchin'} ne '') {
10994: $curr_selected{'srchin'} = $srch->{'srchin'};
10995: }
10996: if ($srch->{'srchtype'} ne '') {
10997: $curr_selected{'srchtype'} = $srch->{'srchtype'};
10998: }
10999: if ($srch->{'srchdomain'} ne '') {
11000: $currdom = $srch->{'srchdomain'};
11001: }
11002: $srchterm = $srch->{'srchterm'};
11003: }
11004: my %html_lt=&Apache::lonlocal::texthash(
11005: 'usr' => 'Search criteria',
11006: 'doma' => 'Domain/institution to search',
11007: 'uname' => 'username',
11008: 'lastname' => 'last name',
11009: 'lastfirst' => 'last name, first name',
11010: 'crs' => 'in this course',
11011: 'dom' => 'in selected LON-CAPA domain',
11012: 'alc' => 'all LON-CAPA',
11013: 'instd' => 'in institutional directory for selected domain',
11014: 'exact' => 'is',
11015: 'contains' => 'contains',
11016: 'begins' => 'begins with',
11017: );
11018: my %js_lt=&Apache::lonlocal::texthash(
11019: 'youm' => "You must include some text to search for.",
11020: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11021: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11022: 'yomc' => "You must choose a domain when using an institutional directory search.",
11023: 'ymcd' => "You must choose a domain when using a domain search.",
11024: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
11025: 'whse' => "When searching by last,first you must include at least one character in the first name.",
11026: 'thfo' => "The following need to be corrected before the search can be run:",
11027: );
11028: &html_escape(\%html_lt);
11029: &js_escape(\%js_lt);
11030: my $domform;
11031: my $allow_blank = 1;
11032: if ($fixeddom) {
11033: $allow_blank = 0;
11034: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11035: } else {
11036: my $defdom = $env{'request.role.domain'};
11037: my ($trusted,$untrusted);
11038: if (($context eq 'requestcrs') || ($context eq 'course')) {
11039: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11040: } elsif ($context eq 'author') {
11041: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11042: } elsif ($context eq 'domain') {
11043: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11044: }
11045: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11046: }
11047: my $srchinsel = ' <select name="srchin">';
11048:
11049: my @srchins = ('crs','dom','alc','instd');
11050:
11051: foreach my $option (@srchins) {
11052: # FIXME 'alc' option unavailable until
11053: # loncreateuser::print_user_query_page()
11054: # has been completed.
11055: next if ($option eq 'alc');
11056: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
11057: next if ($option eq 'crs' && !$env{'request.course.id'});
11058: next if (($option eq 'instd') && ($noinstd));
11059: if ($curr_selected{'srchin'} eq $option) {
11060: $srchinsel .= '
11061: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11062: } else {
11063: $srchinsel .= '
11064: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11065: }
11066: }
11067: $srchinsel .= "\n </select>\n";
11068:
11069: my $srchbysel = ' <select name="srchby">';
11070: foreach my $option ('lastname','lastfirst','uname') {
11071: if ($curr_selected{'srchby'} eq $option) {
11072: $srchbysel .= '
11073: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11074: } else {
11075: $srchbysel .= '
11076: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11077: }
11078: }
11079: $srchbysel .= "\n </select>\n";
11080:
11081: my $srchtypesel = ' <select name="srchtype">';
11082: foreach my $option ('begins','contains','exact') {
11083: if ($curr_selected{'srchtype'} eq $option) {
11084: $srchtypesel .= '
11085: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11086: } else {
11087: $srchtypesel .= '
11088: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11089: }
11090: }
11091: $srchtypesel .= "\n </select>\n";
11092:
11093: my ($newuserscript,$new_user_create);
11094: my $context_dom = $env{'request.role.domain'};
11095: if ($context eq 'requestcrs') {
11096: if ($env{'form.coursedom'} ne '') {
11097: $context_dom = $env{'form.coursedom'};
11098: }
11099: }
11100: if ($forcenewuser) {
11101: if (ref($srch) eq 'HASH') {
11102: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11103: if ($cancreate) {
11104: $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>';
11105: } else {
11106: my $helplink = 'javascript:helpMenu('."'display'".')';
11107: my %usertypetext = (
11108: official => 'institutional',
11109: unofficial => 'non-institutional',
11110: );
11111: $new_user_create = '<p class="LC_warning">'
11112: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11113: .' '
11114: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11115: ,'<a href="'.$helplink.'">','</a>')
11116: .'</p><br />';
11117: }
11118: }
11119: }
11120:
11121: $newuserscript = <<"ENDSCRIPT";
11122:
11123: function setSearch(createnew,callingForm) {
11124: if (createnew == 1) {
11125: for (var i=0; i<callingForm.srchby.length; i++) {
11126: if (callingForm.srchby.options[i].value == 'uname') {
11127: callingForm.srchby.selectedIndex = i;
11128: }
11129: }
11130: for (var i=0; i<callingForm.srchin.length; i++) {
11131: if ( callingForm.srchin.options[i].value == 'dom') {
11132: callingForm.srchin.selectedIndex = i;
11133: }
11134: }
11135: for (var i=0; i<callingForm.srchtype.length; i++) {
11136: if (callingForm.srchtype.options[i].value == 'exact') {
11137: callingForm.srchtype.selectedIndex = i;
11138: }
11139: }
11140: for (var i=0; i<callingForm.srchdomain.length; i++) {
11141: if (callingForm.srchdomain.options[i].value == '$context_dom') {
11142: callingForm.srchdomain.selectedIndex = i;
11143: }
11144: }
11145: }
11146: }
11147: ENDSCRIPT
11148:
11149: }
11150:
11151: my $output = <<"END_BLOCK";
11152: <script type="text/javascript">
11153: // <![CDATA[
11154: function validateEntry(callingForm) {
11155:
11156: var checkok = 1;
11157: var srchin;
11158: for (var i=0; i<callingForm.srchin.length; i++) {
11159: if ( callingForm.srchin[i].checked ) {
11160: srchin = callingForm.srchin[i].value;
11161: }
11162: }
11163:
11164: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11165: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11166: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11167: var srchterm = callingForm.srchterm.value;
11168: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11169: var msg = "";
11170:
11171: if (srchterm == "") {
11172: checkok = 0;
11173: msg += "$js_lt{'youm'}\\n";
11174: }
11175:
11176: if (srchtype== 'begins') {
11177: if (srchterm.length < 2) {
11178: checkok = 0;
11179: msg += "$js_lt{'thte'}\\n";
11180: }
11181: }
11182:
11183: if (srchtype== 'contains') {
11184: if (srchterm.length < 3) {
11185: checkok = 0;
11186: msg += "$js_lt{'thet'}\\n";
11187: }
11188: }
11189: if (srchin == 'instd') {
11190: if (srchdomain == '') {
11191: checkok = 0;
11192: msg += "$js_lt{'yomc'}\\n";
11193: }
11194: }
11195: if (srchin == 'dom') {
11196: if (srchdomain == '') {
11197: checkok = 0;
11198: msg += "$js_lt{'ymcd'}\\n";
11199: }
11200: }
11201: if (srchby == 'lastfirst') {
11202: if (srchterm.indexOf(",") == -1) {
11203: checkok = 0;
11204: msg += "$js_lt{'whus'}\\n";
11205: }
11206: if (srchterm.indexOf(",") == srchterm.length -1) {
11207: checkok = 0;
11208: msg += "$js_lt{'whse'}\\n";
11209: }
11210: }
11211: if (checkok == 0) {
11212: alert("$js_lt{'thfo'}\\n"+msg);
11213: return;
11214: }
11215: if (checkok == 1) {
11216: callingForm.submit();
11217: }
11218: }
11219:
11220: $newuserscript
11221:
11222: // ]]>
11223: </script>
11224:
11225: $new_user_create
11226:
11227: END_BLOCK
11228:
11229: $output .= &Apache::lonhtmlcommon::start_pick_box().
11230: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11231: $domform.
11232: &Apache::lonhtmlcommon::row_closure().
11233: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11234: $srchbysel.
11235: $srchtypesel.
11236: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11237: $srchinsel.
11238: &Apache::lonhtmlcommon::row_closure(1).
11239: &Apache::lonhtmlcommon::end_pick_box().
11240: '<br />';
11241: return ($output,1);
11242: }
11243:
11244: sub user_rule_check {
11245: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11246: my ($response,%inst_response);
11247: if (ref($usershash) eq 'HASH') {
11248: if (keys(%{$usershash}) > 1) {
11249: my (%by_username,%by_id,%userdoms);
11250: my $checkid;
11251: if (ref($checks) eq 'HASH') {
11252: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11253: $checkid = 1;
11254: }
11255: }
11256: foreach my $user (keys(%{$usershash})) {
11257: my ($uname,$udom) = split(/:/,$user);
11258: if ($checkid) {
11259: if (ref($usershash->{$user}) eq 'HASH') {
11260: if ($usershash->{$user}->{'id'} ne '') {
11261: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
11262: $userdoms{$udom} = 1;
11263: if (ref($inst_results) eq 'HASH') {
11264: $inst_results->{$uname.':'.$udom} = {};
11265: }
11266: }
11267: }
11268: } else {
11269: $by_username{$udom}{$uname} = 1;
11270: $userdoms{$udom} = 1;
11271: if (ref($inst_results) eq 'HASH') {
11272: $inst_results->{$uname.':'.$udom} = {};
11273: }
11274: }
11275: }
11276: foreach my $udom (keys(%userdoms)) {
11277: if (!$got_rules->{$udom}) {
11278: my %domconfig = &Apache::lonnet::get_dom('configuration',
11279: ['usercreation'],$udom);
11280: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11281: foreach my $item ('username','id') {
11282: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11283: $$curr_rules{$udom}{$item} =
11284: $domconfig{'usercreation'}{$item.'_rule'};
11285: }
11286: }
11287: }
11288: $got_rules->{$udom} = 1;
11289: }
11290: }
11291: if ($checkid) {
11292: foreach my $udom (keys(%by_id)) {
11293: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11294: if ($outcome eq 'ok') {
11295: foreach my $id (keys(%{$by_id{$udom}})) {
11296: my $uname = $by_id{$udom}{$id};
11297: $inst_response{$uname.':'.$udom} = $outcome;
11298: }
11299: if (ref($results) eq 'HASH') {
11300: foreach my $uname (keys(%{$results})) {
11301: if (exists($inst_response{$uname.':'.$udom})) {
11302: $inst_response{$uname.':'.$udom} = $outcome;
11303: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11304: }
11305: }
11306: }
11307: }
11308: }
11309: } else {
11310: foreach my $udom (keys(%by_username)) {
11311: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11312: if ($outcome eq 'ok') {
11313: foreach my $uname (keys(%{$by_username{$udom}})) {
11314: $inst_response{$uname.':'.$udom} = $outcome;
11315: }
11316: if (ref($results) eq 'HASH') {
11317: foreach my $uname (keys(%{$results})) {
11318: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11319: }
11320: }
11321: }
11322: }
11323: }
11324: } elsif (keys(%{$usershash}) == 1) {
11325: my $user = (keys(%{$usershash}))[0];
11326: my ($uname,$udom) = split(/:/,$user);
11327: if (($udom ne '') && ($uname ne '')) {
11328: if (ref($usershash->{$user}) eq 'HASH') {
11329: if (ref($checks) eq 'HASH') {
11330: if (defined($checks->{'username'})) {
11331: ($inst_response{$user},%{$inst_results->{$user}}) =
11332: &Apache::lonnet::get_instuser($udom,$uname);
11333: } elsif (defined($checks->{'id'})) {
11334: if ($usershash->{$user}->{'id'} ne '') {
11335: ($inst_response{$user},%{$inst_results->{$user}}) =
11336: &Apache::lonnet::get_instuser($udom,undef,
11337: $usershash->{$user}->{'id'});
11338: } else {
11339: ($inst_response{$user},%{$inst_results->{$user}}) =
11340: &Apache::lonnet::get_instuser($udom,$uname);
11341: }
11342: }
11343: } else {
11344: ($inst_response{$user},%{$inst_results->{$user}}) =
11345: &Apache::lonnet::get_instuser($udom,$uname);
11346: return;
11347: }
11348: if (!$got_rules->{$udom}) {
11349: my %domconfig = &Apache::lonnet::get_dom('configuration',
11350: ['usercreation'],$udom);
11351: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11352: foreach my $item ('username','id') {
11353: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11354: $$curr_rules{$udom}{$item} =
11355: $domconfig{'usercreation'}{$item.'_rule'};
11356: }
11357: }
11358: }
11359: $got_rules->{$udom} = 1;
11360: }
11361: }
11362: } else {
11363: return;
11364: }
11365: } else {
11366: return;
11367: }
11368: foreach my $user (keys(%{$usershash})) {
11369: my ($uname,$udom) = split(/:/,$user);
11370: next if (($udom eq '') || ($uname eq ''));
11371: my $id;
11372: if (ref($inst_results) eq 'HASH') {
11373: if (ref($inst_results->{$user}) eq 'HASH') {
11374: $id = $inst_results->{$user}->{'id'};
11375: }
11376: }
11377: if ($id eq '') {
11378: if (ref($usershash->{$user})) {
11379: $id = $usershash->{$user}->{'id'};
11380: }
11381: }
11382: foreach my $item (keys(%{$checks})) {
11383: if (ref($$curr_rules{$udom}) eq 'HASH') {
11384: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11385: if (@{$$curr_rules{$udom}{$item}} > 0) {
11386: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11387: $$curr_rules{$udom}{$item});
11388: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11389: if ($rule_check{$rule}) {
11390: $$rulematch{$user}{$item} = $rule;
11391: if ($inst_response{$user} eq 'ok') {
11392: if (ref($inst_results) eq 'HASH') {
11393: if (ref($inst_results->{$user}) eq 'HASH') {
11394: if (keys(%{$inst_results->{$user}}) == 0) {
11395: $$alerts{$item}{$udom}{$uname} = 1;
11396: } elsif ($item eq 'id') {
11397: if ($inst_results->{$user}->{'id'} eq '') {
11398: $$alerts{$item}{$udom}{$uname} = 1;
11399: }
11400: }
11401: }
11402: }
11403: }
11404: last;
11405: }
11406: }
11407: }
11408: }
11409: }
11410: }
11411: }
11412: }
11413: return;
11414: }
11415:
11416: sub user_rule_formats {
11417: my ($domain,$domdesc,$curr_rules,$check) = @_;
11418: my %text = (
11419: 'username' => 'Usernames',
11420: 'id' => 'IDs',
11421: );
11422: my $output;
11423: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11424: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11425: if (@{$ruleorder} > 0) {
11426: $output = '<br />'.
11427: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11428: '<span class="LC_cusr_emph">','</span>',$domdesc).
11429: ' <ul>';
11430: foreach my $rule (@{$ruleorder}) {
11431: if (ref($curr_rules) eq 'ARRAY') {
11432: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11433: if (ref($rules->{$rule}) eq 'HASH') {
11434: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11435: $rules->{$rule}{'desc'}.'</li>';
11436: }
11437: }
11438: }
11439: }
11440: $output .= '</ul>';
11441: }
11442: }
11443: return $output;
11444: }
11445:
11446: sub instrule_disallow_msg {
11447: my ($checkitem,$domdesc,$count,$mode) = @_;
11448: my $response;
11449: my %text = (
11450: item => 'username',
11451: items => 'usernames',
11452: match => 'matches',
11453: do => 'does',
11454: action => 'a username',
11455: one => 'one',
11456: );
11457: if ($count > 1) {
11458: $text{'item'} = 'usernames';
11459: $text{'match'} ='match';
11460: $text{'do'} = 'do';
11461: $text{'action'} = 'usernames',
11462: $text{'one'} = 'ones';
11463: }
11464: if ($checkitem eq 'id') {
11465: $text{'items'} = 'IDs';
11466: $text{'item'} = 'ID';
11467: $text{'action'} = 'an ID';
11468: if ($count > 1) {
11469: $text{'item'} = 'IDs';
11470: $text{'action'} = 'IDs';
11471: }
11472: }
11473: $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 />';
11474: if ($mode eq 'upload') {
11475: if ($checkitem eq 'username') {
11476: $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'}.");
11477: } elsif ($checkitem eq 'id') {
11478: $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.");
11479: }
11480: } elsif ($mode eq 'selfcreate') {
11481: if ($checkitem eq 'id') {
11482: $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.");
11483: }
11484: } else {
11485: if ($checkitem eq 'username') {
11486: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11487: } elsif ($checkitem eq 'id') {
11488: $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.");
11489: }
11490: }
11491: return $response;
11492: }
11493:
11494: sub personal_data_fieldtitles {
11495: my %fieldtitles = &Apache::lonlocal::texthash (
11496: id => 'Student/Employee ID',
11497: permanentemail => 'E-mail address',
11498: lastname => 'Last Name',
11499: firstname => 'First Name',
11500: middlename => 'Middle Name',
11501: generation => 'Generation',
11502: gen => 'Generation',
11503: inststatus => 'Affiliation',
11504: );
11505: return %fieldtitles;
11506: }
11507:
11508: sub sorted_inst_types {
11509: my ($dom) = @_;
11510: my ($usertypes,$order);
11511: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11512: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11513: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11514: $order = $domdefaults{'inststatus'}{'inststatusorder'};
11515: } else {
11516: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11517: }
11518: my $othertitle = &mt('All users');
11519: if ($env{'request.course.id'}) {
11520: $othertitle = &mt('Any users');
11521: }
11522: my @types;
11523: if (ref($order) eq 'ARRAY') {
11524: @types = @{$order};
11525: }
11526: if (@types == 0) {
11527: if (ref($usertypes) eq 'HASH') {
11528: @types = sort(keys(%{$usertypes}));
11529: }
11530: }
11531: if (keys(%{$usertypes}) > 0) {
11532: $othertitle = &mt('Other users');
11533: }
11534: return ($othertitle,$usertypes,\@types);
11535: }
11536:
11537: sub get_institutional_codes {
11538: my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11539: # Get complete list of course sections to update
11540: my @currsections = ();
11541: my @currxlists = ();
11542: my (%unclutteredsec,%unclutteredlcsec);
11543: my $coursecode = $$settings{'internal.coursecode'};
11544: my $crskey = $crs.':'.$coursecode;
11545: @{$unclutteredsec{$crskey}} = ();
11546: @{$unclutteredlcsec{$crskey}} = ();
11547:
11548: if ($$settings{'internal.sectionnums'} ne '') {
11549: @currsections = split(/,/,$$settings{'internal.sectionnums'});
11550: }
11551:
11552: if ($$settings{'internal.crosslistings'} ne '') {
11553: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11554: }
11555:
11556: if (@currxlists > 0) {
11557: foreach my $xl (@currxlists) {
11558: if ($xl =~ /^([^:]+):(\w*)$/) {
11559: unless (grep/^$1$/,@{$allcourses}) {
11560: push(@{$allcourses},$1);
11561: $$LC_code{$1} = $2;
11562: }
11563: }
11564: }
11565: }
11566:
11567: if (@currsections > 0) {
11568: foreach my $sec (@currsections) {
11569: if ($sec =~ m/^(\w+):(\w*)$/ ) {
11570: my $instsec = $1;
11571: my $lc_sec = $2;
11572: unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11573: push(@{$unclutteredsec{$crskey}},$instsec);
11574: push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11575: }
11576: }
11577: }
11578: }
11579:
11580: if (@{$unclutteredsec{$crskey}} > 0) {
11581: my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11582: if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11583: for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11584: my $sec = $coursecode.$formattedsec{$crskey}[$i];
11585: unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11586: push(@{$allcourses},$sec);
11587: $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11588: }
11589: }
11590: }
11591: }
11592: return;
11593: }
11594:
11595: sub get_standard_codeitems {
11596: return ('Year','Semester','Department','Number','Section');
11597: }
11598:
11599: =pod
11600:
11601: =head1 Slot Helpers
11602:
11603: =over 4
11604:
11605: =item * sorted_slots()
11606:
11607: Sorts an array of slot names in order of an optional sort key,
11608: default sort is by slot start time (earliest first).
11609:
11610: Inputs:
11611:
11612: =over 4
11613:
11614: slotsarr - Reference to array of unsorted slot names.
11615:
11616: slots - Reference to hash of hash, where outer hash keys are slot names.
11617:
11618: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
11619:
11620: =back
11621:
11622: Returns:
11623:
11624: =over 4
11625:
11626: sorted - An array of slot names sorted by a specified sort key
11627: (default sort key is start time of the slot).
11628:
11629: =back
11630:
11631: =cut
11632:
11633:
11634: sub sorted_slots {
11635: my ($slotsarr,$slots,$sortkey) = @_;
11636: if ($sortkey eq '') {
11637: $sortkey = 'starttime';
11638: }
11639: my @sorted;
11640: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11641: @sorted =
11642: sort {
11643: if (ref($slots->{$a}) && ref($slots->{$b})) {
11644: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11645: }
11646: if (ref($slots->{$a})) { return -1;}
11647: if (ref($slots->{$b})) { return 1;}
11648: return 0;
11649: } @{$slotsarr};
11650: }
11651: return @sorted;
11652: }
11653:
11654: =pod
11655:
11656: =item * get_future_slots()
11657:
11658: Inputs:
11659:
11660: =over 4
11661:
11662: cnum - course number
11663:
11664: cdom - course domain
11665:
11666: now - current UNIX time
11667:
11668: symb - optional symb
11669:
11670: =back
11671:
11672: Returns:
11673:
11674: =over 4
11675:
11676: sorted_reservable - ref to array of student_schedulable slots currently
11677: reservable, ordered by end date of reservation period.
11678:
11679: reservable_now - ref to hash of student_schedulable slots currently
11680: reservable.
11681:
11682: Keys in inner hash are:
11683: (a) symb: either blank or symb to which slot use is restricted.
11684: (b) endreserve: end date of reservation period.
11685: (c) uniqueperiod: start,end dates when slot is to be uniquely
11686: selected.
11687:
11688: sorted_future - ref to array of student_schedulable slots reservable in
11689: the future, ordered by start date of reservation period.
11690:
11691: future_reservable - ref to hash of student_schedulable slots reservable
11692: in the future.
11693:
11694: Keys in inner hash are:
11695: (a) symb: either blank or symb to which slot use is restricted.
11696: (b) startreserve: start date of reservation period.
11697: (c) uniqueperiod: start,end dates when slot is to be uniquely
11698: selected.
11699:
11700: =back
11701:
11702: =cut
11703:
11704: sub get_future_slots {
11705: my ($cnum,$cdom,$now,$symb) = @_;
11706: my $map;
11707: if ($symb) {
11708: ($map) = &Apache::lonnet::decode_symb($symb);
11709: }
11710: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11711: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11712: foreach my $slot (keys(%slots)) {
11713: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11714: if ($symb) {
11715: if ($slots{$slot}->{'symb'} ne '') {
11716: my $canuse;
11717: my %oksymbs;
11718: my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
11719: map { $oksymbs{$_} = 1; } @slotsymbs;
11720: if ($oksymbs{$symb}) {
11721: $canuse = 1;
11722: } else {
11723: foreach my $item (@slotsymbs) {
11724: if ($item =~ /\.(page|sequence)$/) {
11725: (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
11726: if (($map ne '') && ($map eq $sloturl)) {
11727: $canuse = 1;
11728: last;
11729: }
11730: }
11731: }
11732: }
11733: next unless ($canuse);
11734: }
11735: }
11736: if (($slots{$slot}->{'starttime'} > $now) &&
11737: ($slots{$slot}->{'endtime'} > $now)) {
11738: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11739: my $userallowed = 0;
11740: if ($slots{$slot}->{'allowedsections'}) {
11741: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11742: if (!defined($env{'request.role.sec'})
11743: && grep(/^No section assigned$/,@allowed_sec)) {
11744: $userallowed=1;
11745: } else {
11746: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11747: $userallowed=1;
11748: }
11749: }
11750: unless ($userallowed) {
11751: if (defined($env{'request.course.groups'})) {
11752: my @groups = split(/:/,$env{'request.course.groups'});
11753: foreach my $group (@groups) {
11754: if (grep(/^\Q$group\E$/,@allowed_sec)) {
11755: $userallowed=1;
11756: last;
11757: }
11758: }
11759: }
11760: }
11761: }
11762: if ($slots{$slot}->{'allowedusers'}) {
11763: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11764: my $user = $env{'user.name'}.':'.$env{'user.domain'};
11765: if (grep(/^\Q$user\E$/,@allowed_users)) {
11766: $userallowed = 1;
11767: }
11768: }
11769: next unless($userallowed);
11770: }
11771: my $startreserve = $slots{$slot}->{'startreserve'};
11772: my $endreserve = $slots{$slot}->{'endreserve'};
11773: my $symb = $slots{$slot}->{'symb'};
11774: my $uniqueperiod;
11775: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11776: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11777: }
11778: if (($startreserve < $now) &&
11779: (!$endreserve || $endreserve > $now)) {
11780: my $lastres = $endreserve;
11781: if (!$lastres) {
11782: $lastres = $slots{$slot}->{'starttime'};
11783: }
11784: $reservable_now{$slot} = {
11785: symb => $symb,
11786: endreserve => $lastres,
11787: uniqueperiod => $uniqueperiod,
11788: };
11789: } elsif (($startreserve > $now) &&
11790: (!$endreserve || $endreserve > $startreserve)) {
11791: $future_reservable{$slot} = {
11792: symb => $symb,
11793: startreserve => $startreserve,
11794: uniqueperiod => $uniqueperiod,
11795: };
11796: }
11797: }
11798: }
11799: my @unsorted_reservable = keys(%reservable_now);
11800: if (@unsorted_reservable > 0) {
11801: @sorted_reservable =
11802: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11803: }
11804: my @unsorted_future = keys(%future_reservable);
11805: if (@unsorted_future > 0) {
11806: @sorted_future =
11807: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11808: }
11809: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11810: }
11811:
11812: =pod
11813:
11814: =back
11815:
11816: =head1 HTTP Helpers
11817:
11818: =over 4
11819:
11820: =item * &get_unprocessed_cgi($query,$possible_names)
11821:
11822: Modify the %env hash to contain unprocessed CGI form parameters held in
11823: $query. The parameters listed in $possible_names (an array reference),
11824: will be set in $env{'form.name'} if they do not already exist.
11825:
11826: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
11827: $possible_names is an ref to an array of form element names. As an example:
11828: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11829: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11830:
11831: =cut
11832:
11833: sub get_unprocessed_cgi {
11834: my ($query,$possible_names)= @_;
11835: # $Apache::lonxml::debug=1;
11836: foreach my $pair (split(/&/,$query)) {
11837: my ($name, $value) = split(/=/,$pair);
11838: $name = &unescape($name);
11839: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11840: $value =~ tr/+/ /;
11841: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11842: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11843: }
11844: }
11845: }
11846:
11847: =pod
11848:
11849: =item * &cacheheader()
11850:
11851: returns cache-controlling header code
11852:
11853: =cut
11854:
11855: sub cacheheader {
11856: unless ($env{'request.method'} eq 'GET') { return ''; }
11857: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11858: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11859: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11860: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11861: return $output;
11862: }
11863:
11864: =pod
11865:
11866: =item * &no_cache($r)
11867:
11868: specifies header code to not have cache
11869:
11870: =cut
11871:
11872: sub no_cache {
11873: my ($r) = @_;
11874: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11875: $env{'request.method'} ne 'GET') { return ''; }
11876: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11877: $r->no_cache(1);
11878: $r->header_out("Expires" => $date);
11879: $r->header_out("Pragma" => "no-cache");
11880: }
11881:
11882: sub content_type {
11883: my ($r,$type,$charset) = @_;
11884: if ($r) {
11885: # Note that printout.pl calls this with undef for $r.
11886: &no_cache($r);
11887: }
11888: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11889: unless ($charset) {
11890: $charset=&Apache::lonlocal::current_encoding;
11891: }
11892: if ($charset) { $type.='; charset='.$charset; }
11893: if ($r) {
11894: $r->content_type($type);
11895: } else {
11896: print("Content-type: $type\n\n");
11897: }
11898: }
11899:
11900: =pod
11901:
11902: =item * &add_to_env($name,$value)
11903:
11904: adds $name to the %env hash with value
11905: $value, if $name already exists, the entry is converted to an array
11906: reference and $value is added to the array.
11907:
11908: =cut
11909:
11910: sub add_to_env {
11911: my ($name,$value)=@_;
11912: if (defined($env{$name})) {
11913: if (ref($env{$name})) {
11914: #already have multiple values
11915: push(@{ $env{$name} },$value);
11916: } else {
11917: #first time seeing multiple values, convert hash entry to an arrayref
11918: my $first=$env{$name};
11919: undef($env{$name});
11920: push(@{ $env{$name} },$first,$value);
11921: }
11922: } else {
11923: $env{$name}=$value;
11924: }
11925: }
11926:
11927: =pod
11928:
11929: =item * &get_env_multiple($name)
11930:
11931: gets $name from the %env hash, it seemlessly handles the cases where multiple
11932: values may be defined and end up as an array ref.
11933:
11934: returns an array of values
11935:
11936: =cut
11937:
11938: sub get_env_multiple {
11939: my ($name) = @_;
11940: my @values;
11941: if (defined($env{$name})) {
11942: # exists is it an array
11943: if (ref($env{$name})) {
11944: @values=@{ $env{$name} };
11945: } else {
11946: $values[0]=$env{$name};
11947: }
11948: }
11949: return(@values);
11950: }
11951:
11952: # Looks at given dependencies, and returns something depending on the context.
11953: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11954: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11955: # For all other contexts, returns ($output, $counter, $numpathchg).
11956: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11957: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11958: # $numpathchg: integer with the number of cleaned up dependency paths.
11959: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11960: # \%mapping: hash reference clean path -> original path for all dependencies.
11961: # @param {string} actionurl - The path to the handler, indicative of the context.
11962: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11963: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11964: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11965: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11966: # @return {Array} - array depending on the context (not a reference)
11967: sub ask_for_embedded_content {
11968: # NOTE: documentation was added afterwards, it could be wrong
11969: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11970: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11971: %currsubfile,%unused,$rem);
11972: my $counter = 0;
11973: my $numnew = 0;
11974: my $numremref = 0;
11975: my $numinvalid = 0;
11976: my $numpathchg = 0;
11977: my $numexisting = 0;
11978: my $numunused = 0;
11979: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11980: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11981: my $heading = &mt('Upload embedded files');
11982: my $buttontext = &mt('Upload');
11983:
11984: # fills these variables based on the context:
11985: # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11986: # $path, $fileloc, $title, $rem, $filename
11987: if ($env{'request.course.id'}) {
11988: if ($actionurl eq '/adm/dependencies') {
11989: $navmap = Apache::lonnavmaps::navmap->new();
11990: }
11991: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11992: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11993: }
11994: if (($actionurl eq '/adm/portfolio') ||
11995: ($actionurl eq '/adm/coursegrp_portfolio')) {
11996: my $current_path='/';
11997: if ($env{'form.currentpath'}) {
11998: $current_path = $env{'form.currentpath'};
11999: }
12000: if ($actionurl eq '/adm/coursegrp_portfolio') {
12001: $udom = $cdom;
12002: $uname = $cnum;
12003: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12004: } else {
12005: $udom = $env{'user.domain'};
12006: $uname = $env{'user.name'};
12007: $url = '/userfiles/portfolio';
12008: }
12009: $toplevel = $url.'/';
12010: $url .= $current_path;
12011: $getpropath = 1;
12012: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12013: ($actionurl eq '/adm/imsimport')) {
12014: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12015: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12016: $toplevel = $url;
12017: if ($rest ne '') {
12018: $url .= $rest;
12019: }
12020: } elsif ($actionurl eq '/adm/coursedocs') {
12021: if (ref($args) eq 'HASH') {
12022: $url = $args->{'docs_url'};
12023: $toplevel = $url;
12024: if ($args->{'context'} eq 'paste') {
12025: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12026: ($path) =
12027: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12028: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12029: $fileloc =~ s{^/}{};
12030: }
12031: }
12032: } elsif ($actionurl eq '/adm/dependencies') {
12033: if ($env{'request.course.id'} ne '') {
12034: if (ref($args) eq 'HASH') {
12035: $url = $args->{'docs_url'};
12036: $title = $args->{'docs_title'};
12037: $toplevel = $url;
12038: unless ($toplevel =~ m{^/}) {
12039: $toplevel = "/$url";
12040: }
12041: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12042: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12043: $path = $1;
12044: } else {
12045: ($path) =
12046: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12047: }
12048: if ($toplevel=~/^\/*(uploaded|editupload)/) {
12049: $fileloc = $toplevel;
12050: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12051: my ($udom,$uname,$fname) =
12052: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12053: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12054: } else {
12055: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12056: }
12057: $fileloc =~ s{^/}{};
12058: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12059: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12060: }
12061: }
12062: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12063: $udom = $cdom;
12064: $uname = $cnum;
12065: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12066: $toplevel = $url;
12067: $path = $url;
12068: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12069: $fileloc =~ s{^/}{};
12070: }
12071:
12072: # parses the dependency paths to get some info
12073: # fills $newfiles, $mapping, $subdependencies, $dependencies
12074: # $newfiles: hash URL -> 1 for new files or external URLs
12075: # (will be completed later)
12076: # $mapping:
12077: # for external URLs: external URL -> external URL
12078: # for relative paths: clean path -> original path
12079: # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12080: # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12081: foreach my $file (keys(%{$allfiles})) {
12082: my $embed_file;
12083: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12084: $embed_file = $1;
12085: } else {
12086: $embed_file = $file;
12087: }
12088: my ($absolutepath,$cleaned_file);
12089: if ($embed_file =~ m{^\w+://}) {
12090: $cleaned_file = $embed_file;
12091: $newfiles{$cleaned_file} = 1;
12092: $mapping{$cleaned_file} = $embed_file;
12093: } else {
12094: $cleaned_file = &clean_path($embed_file);
12095: if ($embed_file =~ m{^/}) {
12096: $absolutepath = $embed_file;
12097: }
12098: if ($cleaned_file =~ m{/}) {
12099: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12100: $path = &check_for_traversal($path,$url,$toplevel);
12101: my $item = $fname;
12102: if ($path ne '') {
12103: $item = $path.'/'.$fname;
12104: $subdependencies{$path}{$fname} = 1;
12105: } else {
12106: $dependencies{$item} = 1;
12107: }
12108: if ($absolutepath) {
12109: $mapping{$item} = $absolutepath;
12110: } else {
12111: $mapping{$item} = $embed_file;
12112: }
12113: } else {
12114: $dependencies{$embed_file} = 1;
12115: if ($absolutepath) {
12116: $mapping{$cleaned_file} = $absolutepath;
12117: } else {
12118: $mapping{$cleaned_file} = $embed_file;
12119: }
12120: }
12121: }
12122: }
12123:
12124: # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12125: # and lists
12126: # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12127: # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12128: # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12129: # the path had to be cleaned up
12130: # $existing: hash clean path -> 1 if the file exists
12131: # $numexisting: number of keys in $existing
12132: # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12133: # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12134: # dependency subdirectories that are
12135: # not listed as dependencies, with some exceptions using $rem
12136: my $dirptr = 16384;
12137: foreach my $path (keys(%subdependencies)) {
12138: $currsubfile{$path} = {};
12139: if (($actionurl eq '/adm/portfolio') ||
12140: ($actionurl eq '/adm/coursegrp_portfolio')) {
12141: my ($sublistref,$listerror) =
12142: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12143: if (ref($sublistref) eq 'ARRAY') {
12144: foreach my $line (@{$sublistref}) {
12145: my ($file_name,$rest) = split(/\&/,$line,2);
12146: $currsubfile{$path}{$file_name} = 1;
12147: }
12148: }
12149: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12150: if (opendir(my $dir,$url.'/'.$path)) {
12151: my @subdir_list = grep(!/^\./,readdir($dir));
12152: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12153: }
12154: } elsif (($actionurl eq '/adm/dependencies') ||
12155: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12156: ($args->{'context'} eq 'paste')) ||
12157: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12158: if ($env{'request.course.id'} ne '') {
12159: my $dir;
12160: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12161: $dir = $fileloc;
12162: } else {
12163: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12164: }
12165: if ($dir ne '') {
12166: my ($sublistref,$listerror) =
12167: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12168: if (ref($sublistref) eq 'ARRAY') {
12169: foreach my $line (@{$sublistref}) {
12170: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12171: undef,$mtime)=split(/\&/,$line,12);
12172: unless (($testdir&$dirptr) ||
12173: ($file_name =~ /^\.\.?$/)) {
12174: $currsubfile{$path}{$file_name} = [$size,$mtime];
12175: }
12176: }
12177: }
12178: }
12179: }
12180: }
12181: foreach my $file (keys(%{$subdependencies{$path}})) {
12182: if (exists($currsubfile{$path}{$file})) {
12183: my $item = $path.'/'.$file;
12184: unless ($mapping{$item} eq $item) {
12185: $pathchanges{$item} = 1;
12186: }
12187: $existing{$item} = 1;
12188: $numexisting ++;
12189: } else {
12190: $newfiles{$path.'/'.$file} = 1;
12191: }
12192: }
12193: if ($actionurl eq '/adm/dependencies') {
12194: foreach my $path (keys(%currsubfile)) {
12195: if (ref($currsubfile{$path}) eq 'HASH') {
12196: foreach my $file (keys(%{$currsubfile{$path}})) {
12197: unless ($subdependencies{$path}{$file}) {
12198: next if (($rem ne '') &&
12199: (($env{"httpref.$rem"."$path/$file"} ne '') ||
12200: (ref($navmap) &&
12201: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12202: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12203: ($navmap->getResourceByUrl($rem."$path/$1")))))));
12204: $unused{$path.'/'.$file} = 1;
12205: }
12206: }
12207: }
12208: }
12209: }
12210: }
12211:
12212: # fills $currfile, hash file name -> 1 or [$size,$mtime]
12213: # for files in $url or $fileloc (target directory) in some contexts
12214: my %currfile;
12215: if (($actionurl eq '/adm/portfolio') ||
12216: ($actionurl eq '/adm/coursegrp_portfolio')) {
12217: my ($dirlistref,$listerror) =
12218: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12219: if (ref($dirlistref) eq 'ARRAY') {
12220: foreach my $line (@{$dirlistref}) {
12221: my ($file_name,$rest) = split(/\&/,$line,2);
12222: $currfile{$file_name} = 1;
12223: }
12224: }
12225: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12226: if (opendir(my $dir,$url)) {
12227: my @dir_list = grep(!/^\./,readdir($dir));
12228: map {$currfile{$_} = 1;} @dir_list;
12229: }
12230: } elsif (($actionurl eq '/adm/dependencies') ||
12231: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12232: ($args->{'context'} eq 'paste')) ||
12233: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12234: if ($env{'request.course.id'} ne '') {
12235: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12236: if ($dir ne '') {
12237: my ($dirlistref,$listerror) =
12238: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12239: if (ref($dirlistref) eq 'ARRAY') {
12240: foreach my $line (@{$dirlistref}) {
12241: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12242: $size,undef,$mtime)=split(/\&/,$line,12);
12243: unless (($testdir&$dirptr) ||
12244: ($file_name =~ /^\.\.?$/)) {
12245: $currfile{$file_name} = [$size,$mtime];
12246: }
12247: }
12248: }
12249: }
12250: }
12251: }
12252: # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12253: # are not in subdirectories, using $currfile
12254: foreach my $file (keys(%dependencies)) {
12255: if (exists($currfile{$file})) {
12256: unless ($mapping{$file} eq $file) {
12257: $pathchanges{$file} = 1;
12258: }
12259: $existing{$file} = 1;
12260: $numexisting ++;
12261: } else {
12262: $newfiles{$file} = 1;
12263: }
12264: }
12265: foreach my $file (keys(%currfile)) {
12266: unless (($file eq $filename) ||
12267: ($file eq $filename.'.bak') ||
12268: ($dependencies{$file})) {
12269: if ($actionurl eq '/adm/dependencies') {
12270: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12271: next if (($rem ne '') &&
12272: (($env{"httpref.$rem".$file} ne '') ||
12273: (ref($navmap) &&
12274: (($navmap->getResourceByUrl($rem.$file) ne '') ||
12275: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12276: ($navmap->getResourceByUrl($rem.$1)))))));
12277: }
12278: }
12279: $unused{$file} = 1;
12280: }
12281: }
12282:
12283: # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12284: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12285: ($args->{'context'} eq 'paste')) {
12286: $counter = scalar(keys(%existing));
12287: $numpathchg = scalar(keys(%pathchanges));
12288: return ($output,$counter,$numpathchg,\%existing);
12289: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
12290: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12291: $counter = scalar(keys(%existing));
12292: $numpathchg = scalar(keys(%pathchanges));
12293: return ($output,$counter,$numpathchg,\%existing,\%mapping);
12294: }
12295:
12296: # returns HTML otherwise, with dependency results and to ask for more uploads
12297:
12298: # $upload_output: missing dependencies (with upload form)
12299: # $modify_output: uploaded dependencies (in use)
12300: # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12301: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12302: if ($actionurl eq '/adm/dependencies') {
12303: next if ($embed_file =~ m{^\w+://});
12304: }
12305: $upload_output .= &start_data_table_row().
12306: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12307: '<span class="LC_filename">'.$embed_file.'</span>';
12308: unless ($mapping{$embed_file} eq $embed_file) {
12309: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12310: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12311: }
12312: $upload_output .= '</td>';
12313: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
12314: $upload_output.='<td align="right">'.
12315: '<span class="LC_info LC_fontsize_medium">'.
12316: &mt("URL points to web address").'</span>';
12317: $numremref++;
12318: } elsif ($args->{'error_on_invalid_names'}
12319: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12320: $upload_output.='<td align="right"><span class="LC_warning">'.
12321: &mt('Invalid characters').'</span>';
12322: $numinvalid++;
12323: } else {
12324: $upload_output .= '<td>'.
12325: &embedded_file_element('upload_embedded',$counter,
12326: $embed_file,\%mapping,
12327: $allfiles,$codebase,'upload');
12328: $counter ++;
12329: $numnew ++;
12330: }
12331: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12332: }
12333: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12334: if ($actionurl eq '/adm/dependencies') {
12335: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12336: $modify_output .= &start_data_table_row().
12337: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12338: '<img src="'.&icon($embed_file).'" border="0" />'.
12339: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
12340: '<td>'.$size.'</td>'.
12341: '<td>'.$mtime.'</td>'.
12342: '<td><label><input type="checkbox" name="mod_upload_dep" '.
12343: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12344: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12345: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12346: &embedded_file_element('upload_embedded',$counter,
12347: $embed_file,\%mapping,
12348: $allfiles,$codebase,'modify').
12349: '</div></td>'.
12350: &end_data_table_row()."\n";
12351: $counter ++;
12352: } else {
12353: $upload_output .= &start_data_table_row().
12354: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12355: '<span class="LC_filename">'.$embed_file.'</span></td>'.
12356: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12357: &Apache::loncommon::end_data_table_row()."\n";
12358: }
12359: }
12360: my $delidx = $counter;
12361: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12362: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12363: $delete_output .= &start_data_table_row().
12364: '<td><img src="'.&icon($oldfile).'" />'.
12365: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
12366: '<td>'.$size.'</td>'.
12367: '<td>'.$mtime.'</td>'.
12368: '<td><label><input type="checkbox" name="del_upload_dep" '.
12369: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12370: &embedded_file_element('upload_embedded',$delidx,
12371: $oldfile,\%mapping,$allfiles,
12372: $codebase,'delete').'</td>'.
12373: &end_data_table_row()."\n";
12374: $numunused ++;
12375: $delidx ++;
12376: }
12377: if ($upload_output) {
12378: $upload_output = &start_data_table().
12379: $upload_output.
12380: &end_data_table()."\n";
12381: }
12382: if ($modify_output) {
12383: $modify_output = &start_data_table().
12384: &start_data_table_header_row().
12385: '<th>'.&mt('File').'</th>'.
12386: '<th>'.&mt('Size (KB)').'</th>'.
12387: '<th>'.&mt('Modified').'</th>'.
12388: '<th>'.&mt('Upload replacement?').'</th>'.
12389: &end_data_table_header_row().
12390: $modify_output.
12391: &end_data_table()."\n";
12392: }
12393: if ($delete_output) {
12394: $delete_output = &start_data_table().
12395: &start_data_table_header_row().
12396: '<th>'.&mt('File').'</th>'.
12397: '<th>'.&mt('Size (KB)').'</th>'.
12398: '<th>'.&mt('Modified').'</th>'.
12399: '<th>'.&mt('Delete?').'</th>'.
12400: &end_data_table_header_row().
12401: $delete_output.
12402: &end_data_table()."\n";
12403: }
12404: my $applies = 0;
12405: if ($numremref) {
12406: $applies ++;
12407: }
12408: if ($numinvalid) {
12409: $applies ++;
12410: }
12411: if ($numexisting) {
12412: $applies ++;
12413: }
12414: if ($counter || $numunused) {
12415: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12416: ' method="post" enctype="multipart/form-data">'."\n".
12417: $state.'<h3>'.$heading.'</h3>';
12418: if ($actionurl eq '/adm/dependencies') {
12419: if ($numnew) {
12420: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12421: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12422: $upload_output.'<br />'."\n";
12423: }
12424: if ($numexisting) {
12425: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12426: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12427: $modify_output.'<br />'."\n";
12428: $buttontext = &mt('Save changes');
12429: }
12430: if ($numunused) {
12431: $output .= '<h4>'.&mt('Unused files').'</h4>'.
12432: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12433: $delete_output.'<br />'."\n";
12434: $buttontext = &mt('Save changes');
12435: }
12436: } else {
12437: $output .= $upload_output.'<br />'."\n";
12438: }
12439: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12440: $counter.'" />'."\n";
12441: if ($actionurl eq '/adm/dependencies') {
12442: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12443: $numnew.'" />'."\n";
12444: } elsif ($actionurl eq '') {
12445: $output .= '<input type="hidden" name="phase" value="three" />';
12446: }
12447: } elsif ($applies) {
12448: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12449: if ($applies > 1) {
12450: $output .=
12451: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12452: if ($numremref) {
12453: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12454: }
12455: if ($numinvalid) {
12456: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12457: }
12458: if ($numexisting) {
12459: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12460: }
12461: $output .= '</ul><br />';
12462: } elsif ($numremref) {
12463: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12464: } elsif ($numinvalid) {
12465: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12466: } elsif ($numexisting) {
12467: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12468: }
12469: $output .= $upload_output.'<br />';
12470: }
12471: my ($pathchange_output,$chgcount);
12472: $chgcount = $counter;
12473: if (keys(%pathchanges) > 0) {
12474: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12475: if ($counter) {
12476: $output .= &embedded_file_element('pathchange',$chgcount,
12477: $embed_file,\%mapping,
12478: $allfiles,$codebase,'change');
12479: } else {
12480: $pathchange_output .=
12481: &start_data_table_row().
12482: '<td><input type ="checkbox" name="namechange" value="'.
12483: $chgcount.'" checked="checked" /></td>'.
12484: '<td>'.$mapping{$embed_file}.'</td>'.
12485: '<td>'.$embed_file.
12486: &embedded_file_element('pathchange',$numpathchg,$embed_file,
12487: \%mapping,$allfiles,$codebase,'change').
12488: '</td>'.&end_data_table_row();
12489: }
12490: $numpathchg ++;
12491: $chgcount ++;
12492: }
12493: }
12494: if (($counter) || ($numunused)) {
12495: if ($numpathchg) {
12496: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12497: $numpathchg.'" />'."\n";
12498: }
12499: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12500: ($actionurl eq '/adm/imsimport')) {
12501: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12502: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12503: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12504: } elsif ($actionurl eq '/adm/dependencies') {
12505: $output .= '<input type="hidden" name="action" value="process_changes" />';
12506: }
12507: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12508: } elsif ($numpathchg) {
12509: my %pathchange = ();
12510: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12511: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12512: $output .= '<p>'.&mt('or').'</p>';
12513: }
12514: }
12515: return ($output,$counter,$numpathchg);
12516: }
12517:
12518: =pod
12519:
12520: =item * clean_path($name)
12521:
12522: Performs clean-up of directories, subdirectories and filename in an
12523: embedded object, referenced in an HTML file which is being uploaded
12524: to a course or portfolio, where
12525: "Upload embedded images/multimedia files if HTML file" checkbox was
12526: checked.
12527:
12528: Clean-up is similar to replacements in lonnet::clean_filename()
12529: except each / between sub-directory and next level is preserved.
12530:
12531: =cut
12532:
12533: sub clean_path {
12534: my ($embed_file) = @_;
12535: $embed_file =~s{^/+}{};
12536: my @contents;
12537: if ($embed_file =~ m{/}) {
12538: @contents = split(/\//,$embed_file);
12539: } else {
12540: @contents = ($embed_file);
12541: }
12542: my $lastidx = scalar(@contents)-1;
12543: for (my $i=0; $i<=$lastidx; $i++) {
12544: $contents[$i]=~s{\\}{/}g;
12545: $contents[$i]=~s/\s+/\_/g;
12546: $contents[$i]=~s{[^/\w\.\-]}{}g;
12547: if ($i == $lastidx) {
12548: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12549: }
12550: }
12551: if ($lastidx > 0) {
12552: return join('/',@contents);
12553: } else {
12554: return $contents[0];
12555: }
12556: }
12557:
12558: sub embedded_file_element {
12559: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12560: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12561: (ref($codebase) eq 'HASH'));
12562: my $output;
12563: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12564: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12565: }
12566: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12567: &escape($embed_file).'" />';
12568: unless (($context eq 'upload_embedded') &&
12569: ($mapping->{$embed_file} eq $embed_file)) {
12570: $output .='
12571: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12572: }
12573: my $attrib;
12574: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12575: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12576: }
12577: $output .=
12578: "\n\t\t".
12579: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12580: $attrib.'" />';
12581: if (exists($codebase->{$mapping->{$embed_file}})) {
12582: $output .=
12583: "\n\t\t".
12584: '<input name="codebase_'.$num.'" type="hidden" value="'.
12585: &escape($codebase->{$mapping->{$embed_file}}).'" />';
12586: }
12587: return $output;
12588: }
12589:
12590: sub get_dependency_details {
12591: my ($currfile,$currsubfile,$embed_file) = @_;
12592: my ($size,$mtime,$showsize,$showmtime);
12593: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12594: if ($embed_file =~ m{/}) {
12595: my ($path,$fname) = split(/\//,$embed_file);
12596: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12597: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12598: }
12599: } else {
12600: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12601: ($size,$mtime) = @{$currfile->{$embed_file}};
12602: }
12603: }
12604: $showsize = $size/1024.0;
12605: $showsize = sprintf("%.1f",$showsize);
12606: if ($mtime > 0) {
12607: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12608: }
12609: }
12610: return ($showsize,$showmtime);
12611: }
12612:
12613: sub ask_embedded_js {
12614: return <<"END";
12615: <script type="text/javascript"">
12616: // <![CDATA[
12617: function toggleBrowse(counter) {
12618: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12619: var fileid = document.getElementById('embedded_item_'+counter);
12620: var uploaddivid = document.getElementById('moduploaddep_'+counter);
12621: if (chkboxid.checked == true) {
12622: uploaddivid.style.display='block';
12623: } else {
12624: uploaddivid.style.display='none';
12625: fileid.value = '';
12626: }
12627: }
12628: // ]]>
12629: </script>
12630:
12631: END
12632: }
12633:
12634: sub upload_embedded {
12635: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12636: $current_disk_usage,$hiddenstate,$actionurl) = @_;
12637: my (%pathchange,$output,$modifyform,$footer,$returnflag);
12638: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12639: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12640: my $orig_uploaded_filename =
12641: $env{'form.embedded_item_'.$i.'.filename'};
12642: foreach my $type ('orig','ref','attrib','codebase') {
12643: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12644: $env{'form.embedded_'.$type.'_'.$i} =
12645: &unescape($env{'form.embedded_'.$type.'_'.$i});
12646: }
12647: }
12648: my ($path,$fname) =
12649: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12650: # no path, whole string is fname
12651: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12652: $fname = &Apache::lonnet::clean_filename($fname);
12653: # See if there is anything left
12654: next if ($fname eq '');
12655:
12656: # Check if file already exists as a file or directory.
12657: my ($state,$msg);
12658: if ($context eq 'portfolio') {
12659: my $port_path = $dirpath;
12660: if ($group ne '') {
12661: $port_path = "groups/$group/$port_path";
12662: }
12663: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12664: $fname,$group,'embedded_item_'.$i,
12665: $dir_root,$port_path,$disk_quota,
12666: $current_disk_usage,$uname,$udom);
12667: if ($state eq 'will_exceed_quota'
12668: || $state eq 'file_locked') {
12669: $output .= $msg;
12670: next;
12671: }
12672: } elsif (($context eq 'author') || ($context eq 'testbank')) {
12673: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12674: if ($state eq 'exists') {
12675: $output .= $msg;
12676: next;
12677: }
12678: }
12679: # Check if extension is valid
12680: if (($fname =~ /\.(\w+)$/) &&
12681: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12682: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12683: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12684: next;
12685: } elsif (($fname =~ /\.(\w+)$/) &&
12686: (!defined(&Apache::loncommon::fileembstyle($1)))) {
12687: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12688: next;
12689: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12690: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12691: next;
12692: }
12693: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12694: my $subdir = $path;
12695: $subdir =~ s{/+$}{};
12696: if ($context eq 'portfolio') {
12697: my $result;
12698: if ($state eq 'existingfile') {
12699: $result=
12700: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12701: $dirpath.$env{'form.currentpath'}.$subdir);
12702: } else {
12703: $result=
12704: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12705: $dirpath.
12706: $env{'form.currentpath'}.$subdir);
12707: if ($result !~ m|^/uploaded/|) {
12708: $output .= '<span class="LC_error">'
12709: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12710: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12711: .'</span><br />';
12712: next;
12713: } else {
12714: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12715: $path.$fname.'</span>').'<br />';
12716: }
12717: }
12718: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12719: my $extendedsubdir = $dirpath.'/'.$subdir;
12720: $extendedsubdir =~ s{/+$}{};
12721: my $result =
12722: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12723: if ($result !~ m|^/uploaded/|) {
12724: $output .= '<span class="LC_error">'
12725: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12726: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12727: .'</span><br />';
12728: next;
12729: } else {
12730: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12731: $path.$fname.'</span>').'<br />';
12732: if ($context eq 'syllabus') {
12733: &Apache::lonnet::make_public_indefinitely($result);
12734: }
12735: }
12736: } else {
12737: # Save the file
12738: my $target = $env{'form.embedded_item_'.$i};
12739: my $fullpath = $dir_root.$dirpath.'/'.$path;
12740: my $dest = $fullpath.$fname;
12741: my $url = $url_root.$dirpath.'/'.$path.$fname;
12742: my @parts=split(/\//,"$dirpath/$path");
12743: my $count;
12744: my $filepath = $dir_root;
12745: foreach my $subdir (@parts) {
12746: $filepath .= "/$subdir";
12747: if (!-e $filepath) {
12748: mkdir($filepath,0770);
12749: }
12750: }
12751: my $fh;
12752: if (!open($fh,'>'.$dest)) {
12753: &Apache::lonnet::logthis('Failed to create '.$dest);
12754: $output .= '<span class="LC_error">'.
12755: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12756: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12757: '</span><br />';
12758: } else {
12759: if (!print $fh $env{'form.embedded_item_'.$i}) {
12760: &Apache::lonnet::logthis('Failed to write to '.$dest);
12761: $output .= '<span class="LC_error">'.
12762: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12763: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12764: '</span><br />';
12765: } else {
12766: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12767: $url.'</span>').'<br />';
12768: unless ($context eq 'testbank') {
12769: $footer .= &mt('View embedded file: [_1]',
12770: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12771: }
12772: }
12773: close($fh);
12774: }
12775: }
12776: if ($env{'form.embedded_ref_'.$i}) {
12777: $pathchange{$i} = 1;
12778: }
12779: }
12780: if ($output) {
12781: $output = '<p>'.$output.'</p>';
12782: }
12783: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12784: $returnflag = 'ok';
12785: my $numpathchgs = scalar(keys(%pathchange));
12786: if ($numpathchgs > 0) {
12787: if ($context eq 'portfolio') {
12788: $output .= '<p>'.&mt('or').'</p>';
12789: } elsif ($context eq 'testbank') {
12790: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12791: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12792: $returnflag = 'modify_orightml';
12793: }
12794: }
12795: return ($output.$footer,$returnflag,$numpathchgs);
12796: }
12797:
12798: sub modify_html_form {
12799: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12800: my $end = 0;
12801: my $modifyform;
12802: if ($context eq 'upload_embedded') {
12803: return unless (ref($pathchange) eq 'HASH');
12804: if ($env{'form.number_embedded_items'}) {
12805: $end += $env{'form.number_embedded_items'};
12806: }
12807: if ($env{'form.number_pathchange_items'}) {
12808: $end += $env{'form.number_pathchange_items'};
12809: }
12810: if ($end) {
12811: for (my $i=0; $i<$end; $i++) {
12812: if ($i < $env{'form.number_embedded_items'}) {
12813: next unless($pathchange->{$i});
12814: }
12815: $modifyform .=
12816: &start_data_table_row().
12817: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12818: 'checked="checked" /></td>'.
12819: '<td>'.$env{'form.embedded_ref_'.$i}.
12820: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12821: &escape($env{'form.embedded_ref_'.$i}).'" />'.
12822: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12823: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12824: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12825: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12826: '<td>'.$env{'form.embedded_orig_'.$i}.
12827: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12828: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12829: &end_data_table_row();
12830: }
12831: }
12832: } else {
12833: $modifyform = $pathchgtable;
12834: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12835: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12836: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12837: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12838: }
12839: }
12840: if ($modifyform) {
12841: if ($actionurl eq '/adm/dependencies') {
12842: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12843: }
12844: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12845: '<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".
12846: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12847: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12848: '</ol></p>'."\n".'<p>'.
12849: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12850: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12851: &start_data_table()."\n".
12852: &start_data_table_header_row().
12853: '<th>'.&mt('Change?').'</th>'.
12854: '<th>'.&mt('Current reference').'</th>'.
12855: '<th>'.&mt('Required reference').'</th>'.
12856: &end_data_table_header_row()."\n".
12857: $modifyform.
12858: &end_data_table().'<br />'."\n".$hiddenstate.
12859: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12860: '</form>'."\n";
12861: }
12862: return;
12863: }
12864:
12865: sub modify_html_refs {
12866: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12867: my $container;
12868: if ($context eq 'portfolio') {
12869: $container = $env{'form.container'};
12870: } elsif ($context eq 'coursedoc') {
12871: $container = $env{'form.primaryurl'};
12872: } elsif ($context eq 'manage_dependencies') {
12873: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12874: $container = "/$container";
12875: } elsif ($context eq 'syllabus') {
12876: $container = $url;
12877: } else {
12878: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12879: }
12880: my (%allfiles,%codebase,$output,$content);
12881: my @changes = &get_env_multiple('form.namechange');
12882: unless ((@changes > 0) || ($context eq 'syllabus')) {
12883: if (wantarray) {
12884: return ('',0,0);
12885: } else {
12886: return;
12887: }
12888: }
12889: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12890: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12891: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12892: if (wantarray) {
12893: return ('',0,0);
12894: } else {
12895: return;
12896: }
12897: }
12898: $content = &Apache::lonnet::getfile($container);
12899: if ($content eq '-1') {
12900: if (wantarray) {
12901: return ('',0,0);
12902: } else {
12903: return;
12904: }
12905: }
12906: } else {
12907: unless ($container =~ /^\Q$dir_root\E/) {
12908: if (wantarray) {
12909: return ('',0,0);
12910: } else {
12911: return;
12912: }
12913: }
12914: if (open(my $fh,'<',$container)) {
12915: $content = join('', <$fh>);
12916: close($fh);
12917: } else {
12918: if (wantarray) {
12919: return ('',0,0);
12920: } else {
12921: return;
12922: }
12923: }
12924: }
12925: my ($count,$codebasecount) = (0,0);
12926: my $mm = new File::MMagic;
12927: my $mime_type = $mm->checktype_contents($content);
12928: if ($mime_type eq 'text/html') {
12929: my $parse_result =
12930: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12931: \%codebase,\$content);
12932: if ($parse_result eq 'ok') {
12933: foreach my $i (@changes) {
12934: my $orig = &unescape($env{'form.embedded_orig_'.$i});
12935: my $ref = &unescape($env{'form.embedded_ref_'.$i});
12936: if ($allfiles{$ref}) {
12937: my $newname = $orig;
12938: my ($attrib_regexp,$codebase);
12939: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12940: if ($attrib_regexp =~ /:/) {
12941: $attrib_regexp =~ s/\:/|/g;
12942: }
12943: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12944: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12945: $count += $numchg;
12946: $allfiles{$newname} = $allfiles{$ref};
12947: delete($allfiles{$ref});
12948: }
12949: if ($env{'form.embedded_codebase_'.$i} ne '') {
12950: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12951: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12952: $codebasecount ++;
12953: }
12954: }
12955: }
12956: my $skiprewrites;
12957: if ($count || $codebasecount) {
12958: my $saveresult;
12959: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12960: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12961: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12962: if ($url eq $container) {
12963: my ($fname) = ($container =~ m{/([^/]+)$});
12964: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12965: $count,'<span class="LC_filename">'.
12966: $fname.'</span>').'</p>';
12967: } else {
12968: $output = '<p class="LC_error">'.
12969: &mt('Error: update failed for: [_1].',
12970: '<span class="LC_filename">'.
12971: $container.'</span>').'</p>';
12972: }
12973: if ($context eq 'syllabus') {
12974: unless ($saveresult eq 'ok') {
12975: $skiprewrites = 1;
12976: }
12977: }
12978: } else {
12979: if (open(my $fh,'>',$container)) {
12980: print $fh $content;
12981: close($fh);
12982: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12983: $count,'<span class="LC_filename">'.
12984: $container.'</span>').'</p>';
12985: } else {
12986: $output = '<p class="LC_error">'.
12987: &mt('Error: could not update [_1].',
12988: '<span class="LC_filename">'.
12989: $container.'</span>').'</p>';
12990: }
12991: }
12992: }
12993: if (($context eq 'syllabus') && (!$skiprewrites)) {
12994: my ($actionurl,$state);
12995: $actionurl = "/public/$udom/$uname/syllabus";
12996: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12997: &ask_for_embedded_content($actionurl,$state,\%allfiles,
12998: \%codebase,
12999: {'context' => 'rewrites',
13000: 'ignore_remote_references' => 1,});
13001: if (ref($mapping) eq 'HASH') {
13002: my $rewrites = 0;
13003: foreach my $key (keys(%{$mapping})) {
13004: next if ($key =~ m{^https?://});
13005: my $ref = $mapping->{$key};
13006: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13007: my $attrib;
13008: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13009: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13010: }
13011: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13012: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13013: $rewrites += $numchg;
13014: }
13015: }
13016: if ($rewrites) {
13017: my $saveresult;
13018: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13019: if ($url eq $container) {
13020: my ($fname) = ($container =~ m{/([^/]+)$});
13021: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13022: $count,'<span class="LC_filename">'.
13023: $fname.'</span>').'</p>';
13024: } else {
13025: $output .= '<p class="LC_error">'.
13026: &mt('Error: could not update links in [_1].',
13027: '<span class="LC_filename">'.
13028: $container.'</span>').'</p>';
13029:
13030: }
13031: }
13032: }
13033: }
13034: } else {
13035: &logthis('Failed to parse '.$container.
13036: ' to modify references: '.$parse_result);
13037: }
13038: }
13039: if (wantarray) {
13040: return ($output,$count,$codebasecount);
13041: } else {
13042: return $output;
13043: }
13044: }
13045:
13046: sub check_for_existing {
13047: my ($path,$fname,$element) = @_;
13048: my ($state,$msg);
13049: if (-d $path.'/'.$fname) {
13050: $state = 'exists';
13051: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13052: } elsif (-e $path.'/'.$fname) {
13053: $state = 'exists';
13054: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13055: }
13056: if ($state eq 'exists') {
13057: $msg = '<span class="LC_error">'.$msg.'</span><br />';
13058: }
13059: return ($state,$msg);
13060: }
13061:
13062: sub check_for_upload {
13063: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13064: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13065: my $filesize = length($env{'form.'.$element});
13066: if (!$filesize) {
13067: my $msg = '<span class="LC_error">'.
13068: &mt('Unable to upload [_1]. (size = [_2] bytes)',
13069: '<span class="LC_filename">'.$fname.'</span>',
13070: $filesize).'<br />'.
13071: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13072: '</span>';
13073: return ('zero_bytes',$msg);
13074: }
13075: $filesize = $filesize/1000; #express in k (1024?)
13076: my $getpropath = 1;
13077: my ($dirlistref,$listerror) =
13078: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13079: my $found_file = 0;
13080: my $locked_file = 0;
13081: my @lockers;
13082: my $navmap;
13083: if ($env{'request.course.id'}) {
13084: $navmap = Apache::lonnavmaps::navmap->new();
13085: }
13086: if (ref($dirlistref) eq 'ARRAY') {
13087: foreach my $line (@{$dirlistref}) {
13088: my ($file_name,$rest)=split(/\&/,$line,2);
13089: if ($file_name eq $fname){
13090: $file_name = $path.$file_name;
13091: if ($group ne '') {
13092: $file_name = $group.$file_name;
13093: }
13094: $found_file = 1;
13095: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13096: foreach my $lock (@lockers) {
13097: if (ref($lock) eq 'ARRAY') {
13098: my ($symb,$crsid) = @{$lock};
13099: if ($crsid eq $env{'request.course.id'}) {
13100: if (ref($navmap)) {
13101: my $res = $navmap->getBySymb($symb);
13102: foreach my $part (@{$res->parts()}) {
13103: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13104: unless (($slot_status == $res->RESERVED) ||
13105: ($slot_status == $res->RESERVED_LOCATION)) {
13106: $locked_file = 1;
13107: }
13108: }
13109: } else {
13110: $locked_file = 1;
13111: }
13112: } else {
13113: $locked_file = 1;
13114: }
13115: }
13116: }
13117: } else {
13118: my @info = split(/\&/,$rest);
13119: my $currsize = $info[6]/1000;
13120: if ($currsize < $filesize) {
13121: my $extra = $filesize - $currsize;
13122: if (($current_disk_usage + $extra) > $disk_quota) {
13123: my $msg = '<p class="LC_warning">'.
13124: &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.',
13125: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13126: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13127: $disk_quota,$current_disk_usage).'</p>';
13128: return ('will_exceed_quota',$msg);
13129: }
13130: }
13131: }
13132: }
13133: }
13134: }
13135: if (($current_disk_usage + $filesize) > $disk_quota){
13136: my $msg = '<p class="LC_warning">'.
13137: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13138: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13139: return ('will_exceed_quota',$msg);
13140: } elsif ($found_file) {
13141: if ($locked_file) {
13142: my $msg = '<p class="LC_warning">';
13143: $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>');
13144: $msg .= '</p>';
13145: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13146: return ('file_locked',$msg);
13147: } else {
13148: my $msg = '<p class="LC_error">';
13149: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13150: $msg .= '</p>';
13151: return ('existingfile',$msg);
13152: }
13153: }
13154: }
13155:
13156: sub check_for_traversal {
13157: my ($path,$url,$toplevel) = @_;
13158: my @parts=split(/\//,$path);
13159: my $cleanpath;
13160: my $fullpath = $url;
13161: for (my $i=0;$i<@parts;$i++) {
13162: next if ($parts[$i] eq '.');
13163: if ($parts[$i] eq '..') {
13164: $fullpath =~ s{([^/]+/)$}{};
13165: } else {
13166: $fullpath .= $parts[$i].'/';
13167: }
13168: }
13169: if ($fullpath =~ /^\Q$url\E(.*)$/) {
13170: $cleanpath = $1;
13171: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13172: my $curr_toprel = $1;
13173: my @parts = split(/\//,$curr_toprel);
13174: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13175: my @urlparts = split(/\//,$url_toprel);
13176: my $doubledots;
13177: my $startdiff = -1;
13178: for (my $i=0; $i<@urlparts; $i++) {
13179: if ($startdiff == -1) {
13180: unless ($urlparts[$i] eq $parts[$i]) {
13181: $startdiff = $i;
13182: $doubledots .= '../';
13183: }
13184: } else {
13185: $doubledots .= '../';
13186: }
13187: }
13188: if ($startdiff > -1) {
13189: $cleanpath = $doubledots;
13190: for (my $i=$startdiff; $i<@parts; $i++) {
13191: $cleanpath .= $parts[$i].'/';
13192: }
13193: }
13194: }
13195: $cleanpath =~ s{(/)$}{};
13196: return $cleanpath;
13197: }
13198:
13199: sub is_archive_file {
13200: my ($mimetype) = @_;
13201: if (($mimetype eq 'application/octet-stream') ||
13202: ($mimetype eq 'application/x-stuffit') ||
13203: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13204: return 1;
13205: }
13206: return;
13207: }
13208:
13209: sub decompress_form {
13210: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13211: my %lt = &Apache::lonlocal::texthash (
13212: this => 'This file is an archive file.',
13213: camt => 'This file is a Camtasia archive file.',
13214: itsc => 'Its contents are as follows:',
13215: youm => 'You may wish to extract its contents.',
13216: extr => 'Extract contents',
13217: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13218: proa => 'Process automatically?',
13219: yes => 'Yes',
13220: no => 'No',
13221: fold => 'Title for folder containing movie',
13222: movi => 'Title for page containing embedded movie',
13223: );
13224: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13225: my ($is_camtasia,$topdir,%toplevel,@paths);
13226: my $info = &list_archive_contents($fileloc,\@paths);
13227: if (@paths) {
13228: foreach my $path (@paths) {
13229: $path =~ s{^/}{};
13230: if ($path =~ m{^([^/]+)/$}) {
13231: $topdir = $1;
13232: }
13233: if ($path =~ m{^([^/]+)/}) {
13234: $toplevel{$1} = $path;
13235: } else {
13236: $toplevel{$path} = $path;
13237: }
13238: }
13239: }
13240: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13241: my @camtasia6 = ("$topdir/","$topdir/index.html",
13242: "$topdir/media/",
13243: "$topdir/media/$topdir.mp4",
13244: "$topdir/media/FirstFrame.png",
13245: "$topdir/media/player.swf",
13246: "$topdir/media/swfobject.js",
13247: "$topdir/media/expressInstall.swf");
13248: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13249: "$topdir/$topdir.mp4",
13250: "$topdir/$topdir\_config.xml",
13251: "$topdir/$topdir\_controller.swf",
13252: "$topdir/$topdir\_embed.css",
13253: "$topdir/$topdir\_First_Frame.png",
13254: "$topdir/$topdir\_player.html",
13255: "$topdir/$topdir\_Thumbnails.png",
13256: "$topdir/playerProductInstall.swf",
13257: "$topdir/scripts/",
13258: "$topdir/scripts/config_xml.js",
13259: "$topdir/scripts/handlebars.js",
13260: "$topdir/scripts/jquery-1.7.1.min.js",
13261: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13262: "$topdir/scripts/modernizr.js",
13263: "$topdir/scripts/player-min.js",
13264: "$topdir/scripts/swfobject.js",
13265: "$topdir/skins/",
13266: "$topdir/skins/configuration_express.xml",
13267: "$topdir/skins/express_show/",
13268: "$topdir/skins/express_show/player-min.css",
13269: "$topdir/skins/express_show/spritesheet.png");
13270: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13271: "$topdir/$topdir.mp4",
13272: "$topdir/$topdir\_config.xml",
13273: "$topdir/$topdir\_controller.swf",
13274: "$topdir/$topdir\_embed.css",
13275: "$topdir/$topdir\_First_Frame.png",
13276: "$topdir/$topdir\_player.html",
13277: "$topdir/$topdir\_Thumbnails.png",
13278: "$topdir/playerProductInstall.swf",
13279: "$topdir/scripts/",
13280: "$topdir/scripts/config_xml.js",
13281: "$topdir/scripts/techsmith-smart-player.min.js",
13282: "$topdir/skins/",
13283: "$topdir/skins/configuration_express.xml",
13284: "$topdir/skins/express_show/",
13285: "$topdir/skins/express_show/spritesheet.min.css",
13286: "$topdir/skins/express_show/spritesheet.png",
13287: "$topdir/skins/express_show/techsmith-smart-player.min.css");
13288: my @diffs = &compare_arrays(\@paths,\@camtasia6);
13289: if (@diffs == 0) {
13290: $is_camtasia = 6;
13291: } else {
13292: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13293: if (@diffs == 0) {
13294: $is_camtasia = 8;
13295: } else {
13296: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13297: if (@diffs == 0) {
13298: $is_camtasia = 8;
13299: }
13300: }
13301: }
13302: }
13303: my $output;
13304: if ($is_camtasia) {
13305: $output = <<"ENDCAM";
13306: <script type="text/javascript" language="Javascript">
13307: // <![CDATA[
13308:
13309: function camtasiaToggle() {
13310: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13311: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13312: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13313: document.getElementById('camtasia_titles').style.display='block';
13314: } else {
13315: document.getElementById('camtasia_titles').style.display='none';
13316: }
13317: }
13318: }
13319: return;
13320: }
13321:
13322: // ]]>
13323: </script>
13324: <p>$lt{'camt'}</p>
13325: ENDCAM
13326: } else {
13327: $output = '<p>'.$lt{'this'};
13328: if ($info eq '') {
13329: $output .= ' '.$lt{'youm'}.'</p>'."\n";
13330: } else {
13331: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13332: '<div><pre>'.$info.'</pre></div>';
13333: }
13334: }
13335: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13336: my $duplicates;
13337: my $num = 0;
13338: if (ref($dirlist) eq 'ARRAY') {
13339: foreach my $item (@{$dirlist}) {
13340: if (ref($item) eq 'ARRAY') {
13341: if (exists($toplevel{$item->[0]})) {
13342: $duplicates .=
13343: &start_data_table_row().
13344: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13345: 'value="0" checked="checked" />'.&mt('No').'</label>'.
13346: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
13347: 'value="1" />'.&mt('Yes').'</label>'.
13348: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13349: '<td>'.$item->[0].'</td>';
13350: if ($item->[2]) {
13351: $duplicates .= '<td>'.&mt('Directory').'</td>';
13352: } else {
13353: $duplicates .= '<td>'.&mt('File').'</td>';
13354: }
13355: $duplicates .= '<td>'.$item->[3].'</td>'.
13356: '<td>'.
13357: &Apache::lonlocal::locallocaltime($item->[4]).
13358: '</td>'.
13359: &end_data_table_row();
13360: $num ++;
13361: }
13362: }
13363: }
13364: }
13365: my $itemcount;
13366: if (@paths > 0) {
13367: $itemcount = scalar(@paths);
13368: } else {
13369: $itemcount = 1;
13370: }
13371: if ($is_camtasia) {
13372: $output .= $lt{'auto'}.'<br />'.
13373: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13374: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13375: $lt{'yes'}.'</label> <label>'.
13376: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13377: $lt{'no'}.'</label></span><br />'.
13378: '<div id="camtasia_titles" style="display:block">'.
13379: &Apache::lonhtmlcommon::start_pick_box().
13380: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13381: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13382: &Apache::lonhtmlcommon::row_closure().
13383: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13384: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13385: &Apache::lonhtmlcommon::row_closure(1).
13386: &Apache::lonhtmlcommon::end_pick_box().
13387: '</div>';
13388: }
13389: $output .=
13390: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13391: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13392: "\n";
13393: if ($duplicates ne '') {
13394: $output .= '<p><span class="LC_warning">'.
13395: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
13396: &start_data_table().
13397: &start_data_table_header_row().
13398: '<th>'.&mt('Overwrite?').'</th>'.
13399: '<th>'.&mt('Name').'</th>'.
13400: '<th>'.&mt('Type').'</th>'.
13401: '<th>'.&mt('Size').'</th>'.
13402: '<th>'.&mt('Last modified').'</th>'.
13403: &end_data_table_header_row().
13404: $duplicates.
13405: &end_data_table().
13406: '</p>';
13407: }
13408: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13409: if (ref($hiddenelements) eq 'HASH') {
13410: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13411: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13412: }
13413: }
13414: $output .= <<"END";
13415: <br />
13416: <input type="submit" name="decompress" value="$lt{'extr'}" />
13417: </form>
13418: $noextract
13419: END
13420: return $output;
13421: }
13422:
13423: sub decompression_utility {
13424: my ($program) = @_;
13425: my @utilities = ('tar','gunzip','bunzip2','unzip');
13426: my $location;
13427: if (grep(/^\Q$program\E$/,@utilities)) {
13428: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13429: '/usr/sbin/') {
13430: if (-x $dir.$program) {
13431: $location = $dir.$program;
13432: last;
13433: }
13434: }
13435: }
13436: return $location;
13437: }
13438:
13439: sub list_archive_contents {
13440: my ($file,$pathsref) = @_;
13441: my (@cmd,$output);
13442: my $needsregexp;
13443: if ($file =~ /\.zip$/) {
13444: @cmd = (&decompression_utility('unzip'),"-l");
13445: $needsregexp = 1;
13446: } elsif (($file =~ m/\.tar\.gz$/) ||
13447: ($file =~ /\.tgz$/)) {
13448: @cmd = (&decompression_utility('tar'),"-ztf");
13449: } elsif ($file =~ /\.tar\.bz2$/) {
13450: @cmd = (&decompression_utility('tar'),"-jtf");
13451: } elsif ($file =~ m|\.tar$|) {
13452: @cmd = (&decompression_utility('tar'),"-tf");
13453: }
13454: if (@cmd) {
13455: undef($!);
13456: undef($@);
13457: if (open(my $fh,"-|", @cmd, $file)) {
13458: while (my $line = <$fh>) {
13459: $output .= $line;
13460: chomp($line);
13461: my $item;
13462: if ($needsregexp) {
13463: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
13464: } else {
13465: $item = $line;
13466: }
13467: if ($item ne '') {
13468: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13469: push(@{$pathsref},$item);
13470: }
13471: }
13472: }
13473: close($fh);
13474: }
13475: }
13476: return $output;
13477: }
13478:
13479: sub decompress_uploaded_file {
13480: my ($file,$dir) = @_;
13481: &Apache::lonnet::appenv({'cgi.file' => $file});
13482: &Apache::lonnet::appenv({'cgi.dir' => $dir});
13483: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13484: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13485: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13486: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13487: my $decompressed = $env{'cgi.decompressed'};
13488: &Apache::lonnet::delenv('cgi.file');
13489: &Apache::lonnet::delenv('cgi.dir');
13490: &Apache::lonnet::delenv('cgi.decompressed');
13491: return ($decompressed,$result);
13492: }
13493:
13494: sub process_decompression {
13495: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13496: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13497: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13498: &mt('Unexpected file path.').'</p>'."\n";
13499: }
13500: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13501: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13502: &mt('Unexpected course context.').'</p>'."\n";
13503: }
13504: unless ($file eq &Apache::lonnet::clean_filename($file)) {
13505: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13506: &mt('Filename contained unexpected characters.').'</p>'."\n";
13507: }
13508: my ($dir,$error,$warning,$output);
13509: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13510: $error = &mt('Filename not a supported archive file type.').
13511: '<br />'.&mt('Filename should end with one of: [_1].',
13512: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13513: } else {
13514: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13515: if ($docuhome eq 'no_host') {
13516: $error = &mt('Could not determine home server for course.');
13517: } else {
13518: my @ids=&Apache::lonnet::current_machine_ids();
13519: my $currdir = "$dir_root/$destination";
13520: if (grep(/^\Q$docuhome\E$/,@ids)) {
13521: $dir = &LONCAPA::propath($docudom,$docuname).
13522: "$dir_root/$destination";
13523: } else {
13524: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13525: "$dir_root/$docudom/$docuname/$destination";
13526: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13527: $error = &mt('Archive file not found.');
13528: }
13529: }
13530: my (@to_overwrite,@to_skip);
13531: if ($env{'form.archive_overwrite_total'} > 0) {
13532: my $total = $env{'form.archive_overwrite_total'};
13533: for (my $i=0; $i<$total; $i++) {
13534: if ($env{'form.archive_overwrite_'.$i} == 1) {
13535: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13536: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13537: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13538: }
13539: }
13540: }
13541: my $numskip = scalar(@to_skip);
13542: my $numoverwrite = scalar(@to_overwrite);
13543: if (($numskip) && (!$numoverwrite)) {
13544: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
13545: } elsif ($dir eq '') {
13546: $error = &mt('Directory containing archive file unavailable.');
13547: } elsif (!$error) {
13548: my ($decompressed,$display);
13549: if (($numskip) || ($numoverwrite)) {
13550: my $tempdir = time.'_'.$$.int(rand(10000));
13551: mkdir("$dir/$tempdir",0755);
13552: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13553: ($decompressed,$display) =
13554: &decompress_uploaded_file($file,"$dir/$tempdir");
13555: foreach my $item (@to_skip) {
13556: if (($item ne '') && ($item !~ /\.\./)) {
13557: if (-f "$dir/$tempdir/$item") {
13558: unlink("$dir/$tempdir/$item");
13559: } elsif (-d "$dir/$tempdir/$item") {
13560: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13561: }
13562: }
13563: }
13564: foreach my $item (@to_overwrite) {
13565: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13566: if (($item ne '') && ($item !~ /\.\./)) {
13567: if (-f "$dir/$item") {
13568: unlink("$dir/$item");
13569: } elsif (-d "$dir/$item") {
13570: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13571: }
13572: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13573: }
13574: }
13575: }
13576: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13577: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13578: }
13579: }
13580: } else {
13581: ($decompressed,$display) =
13582: &decompress_uploaded_file($file,$dir);
13583: }
13584: if ($decompressed eq 'ok') {
13585: $output = '<p class="LC_info">'.
13586: &mt('Files extracted successfully from archive.').
13587: '</p>'."\n";
13588: my ($warning,$result,@contents);
13589: my ($newdirlistref,$newlisterror) =
13590: &Apache::lonnet::dirlist($currdir,$docudom,
13591: $docuname,1);
13592: my (%is_dir,%changes,@newitems);
13593: my $dirptr = 16384;
13594: if (ref($newdirlistref) eq 'ARRAY') {
13595: foreach my $dir_line (@{$newdirlistref}) {
13596: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13597: unless (($item =~ /^\.+$/) || ($item eq $file)) {
13598: push(@newitems,$item);
13599: if ($dirptr&$testdir) {
13600: $is_dir{$item} = 1;
13601: }
13602: $changes{$item} = 1;
13603: }
13604: }
13605: }
13606: if (keys(%changes) > 0) {
13607: foreach my $item (sort(@newitems)) {
13608: if ($changes{$item}) {
13609: push(@contents,$item);
13610: }
13611: }
13612: }
13613: if (@contents > 0) {
13614: my $wantform;
13615: unless ($env{'form.autoextract_camtasia'}) {
13616: $wantform = 1;
13617: }
13618: my (%children,%parent,%dirorder,%titles);
13619: my ($count,$datatable) = &get_extracted($docudom,$docuname,
13620: $currdir,\%is_dir,
13621: \%children,\%parent,
13622: \@contents,\%dirorder,
13623: \%titles,$wantform);
13624: if ($datatable ne '') {
13625: $output .= &archive_options_form('decompressed',$datatable,
13626: $count,$hiddenelem);
13627: my $startcount = 6;
13628: $output .= &archive_javascript($startcount,$count,
13629: \%titles,\%children);
13630: }
13631: if ($env{'form.autoextract_camtasia'}) {
13632: my $version = $env{'form.autoextract_camtasia'};
13633: my %displayed;
13634: my $total = 1;
13635: $env{'form.archive_directory'} = [];
13636: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13637: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13638: $path =~ s{/$}{};
13639: my $item;
13640: if ($path ne '') {
13641: $item = "$path/$titles{$i}";
13642: } else {
13643: $item = $titles{$i};
13644: }
13645: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13646: if ($item eq $contents[0]) {
13647: push(@{$env{'form.archive_directory'}},$i);
13648: $env{'form.archive_'.$i} = 'display';
13649: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13650: $displayed{'folder'} = $i;
13651: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13652: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13653: $env{'form.archive_'.$i} = 'display';
13654: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13655: $displayed{'web'} = $i;
13656: } else {
13657: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13658: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13659: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13660: push(@{$env{'form.archive_directory'}},$i);
13661: }
13662: $env{'form.archive_'.$i} = 'dependency';
13663: }
13664: $total ++;
13665: }
13666: for (my $i=1; $i<$total; $i++) {
13667: next if ($i == $displayed{'web'});
13668: next if ($i == $displayed{'folder'});
13669: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13670: }
13671: $env{'form.phase'} = 'decompress_cleanup';
13672: $env{'form.archivedelete'} = 1;
13673: $env{'form.archive_count'} = $total-1;
13674: $output .=
13675: &process_extracted_files('coursedocs',$docudom,
13676: $docuname,$destination,
13677: $dir_root,$hiddenelem);
13678: }
13679: } else {
13680: $warning = &mt('No new items extracted from archive file.');
13681: }
13682: } else {
13683: $output = $display;
13684: $error = &mt('An error occurred during extraction from the archive file.');
13685: }
13686: }
13687: }
13688: }
13689: if ($error) {
13690: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13691: $error.'</p>'."\n";
13692: }
13693: if ($warning) {
13694: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13695: }
13696: return $output;
13697: }
13698:
13699: sub get_extracted {
13700: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13701: $titles,$wantform) = @_;
13702: my $count = 0;
13703: my $depth = 0;
13704: my $datatable;
13705: my @hierarchy;
13706: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13707: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13708: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13709: foreach my $item (@{$contents}) {
13710: $count ++;
13711: @{$dirorder->{$count}} = @hierarchy;
13712: $titles->{$count} = $item;
13713: &archive_hierarchy($depth,$count,$parent,$children);
13714: if ($wantform) {
13715: $datatable .= &archive_row($is_dir->{$item},$item,
13716: $currdir,$depth,$count);
13717: }
13718: if ($is_dir->{$item}) {
13719: $depth ++;
13720: push(@hierarchy,$count);
13721: $parent->{$depth} = $count;
13722: $datatable .=
13723: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13724: \$depth,\$count,\@hierarchy,$dirorder,
13725: $children,$parent,$titles,$wantform);
13726: $depth --;
13727: pop(@hierarchy);
13728: }
13729: }
13730: return ($count,$datatable);
13731: }
13732:
13733: sub recurse_extracted_archive {
13734: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13735: $children,$parent,$titles,$wantform) = @_;
13736: my $result='';
13737: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13738: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13739: (ref($dirorder) eq 'HASH')) {
13740: return $result;
13741: }
13742: my $dirptr = 16384;
13743: my ($newdirlistref,$newlisterror) =
13744: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13745: if (ref($newdirlistref) eq 'ARRAY') {
13746: foreach my $dir_line (@{$newdirlistref}) {
13747: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13748: unless ($item =~ /^\.+$/) {
13749: $$count ++;
13750: @{$dirorder->{$$count}} = @{$hierarchy};
13751: $titles->{$$count} = $item;
13752: &archive_hierarchy($$depth,$$count,$parent,$children);
13753:
13754: my $is_dir;
13755: if ($dirptr&$testdir) {
13756: $is_dir = 1;
13757: }
13758: if ($wantform) {
13759: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13760: }
13761: if ($is_dir) {
13762: $$depth ++;
13763: push(@{$hierarchy},$$count);
13764: $parent->{$$depth} = $$count;
13765: $result .=
13766: &recurse_extracted_archive("$currdir/$item",$docudom,
13767: $docuname,$depth,$count,
13768: $hierarchy,$dirorder,$children,
13769: $parent,$titles,$wantform);
13770: $$depth --;
13771: pop(@{$hierarchy});
13772: }
13773: }
13774: }
13775: }
13776: return $result;
13777: }
13778:
13779: sub archive_hierarchy {
13780: my ($depth,$count,$parent,$children) =@_;
13781: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13782: if (exists($parent->{$depth})) {
13783: $children->{$parent->{$depth}} .= $count.':';
13784: }
13785: }
13786: return;
13787: }
13788:
13789: sub archive_row {
13790: my ($is_dir,$item,$currdir,$depth,$count) = @_;
13791: my ($name) = ($item =~ m{([^/]+)$});
13792: my %choices = &Apache::lonlocal::texthash (
13793: 'display' => 'Add as file',
13794: 'dependency' => 'Include as dependency',
13795: 'discard' => 'Discard',
13796: );
13797: if ($is_dir) {
13798: $choices{'display'} = &mt('Add as folder');
13799: }
13800: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13801: my $offset = 0;
13802: foreach my $action ('display','dependency','discard') {
13803: $offset ++;
13804: if ($action ne 'display') {
13805: $offset ++;
13806: }
13807: $output .= '<td><span class="LC_nobreak">'.
13808: '<label><input type="radio" name="archive_'.$count.
13809: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13810: my $text = $choices{$action};
13811: if ($is_dir) {
13812: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13813: if ($action eq 'display') {
13814: $text = &mt('Add as folder');
13815: }
13816: } else {
13817: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13818:
13819: }
13820: $output .= ' /> '.$choices{$action}.'</label></span>';
13821: if ($action eq 'dependency') {
13822: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13823: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
13824: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13825: '<option value=""></option>'."\n".
13826: '</select>'."\n".
13827: '</div>';
13828: } elsif ($action eq 'display') {
13829: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13830: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13831: '</div>';
13832: }
13833: $output .= '</td>';
13834: }
13835: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13836: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
13837: for (my $i=0; $i<$depth; $i++) {
13838: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13839: }
13840: if ($is_dir) {
13841: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
13842: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13843: } else {
13844: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13845: }
13846: $output .= ' '.$name.'</td>'."\n".
13847: &end_data_table_row();
13848: return $output;
13849: }
13850:
13851: sub archive_options_form {
13852: my ($form,$display,$count,$hiddenelem) = @_;
13853: my %lt = &Apache::lonlocal::texthash(
13854: perm => 'Permanently remove archive file?',
13855: hows => 'How should each extracted item be incorporated in the course?',
13856: cont => 'Content actions for all',
13857: addf => 'Add as folder/file',
13858: incd => 'Include as dependency for a displayed file',
13859: disc => 'Discard',
13860: no => 'No',
13861: yes => 'Yes',
13862: save => 'Save',
13863: );
13864: my $output = <<"END";
13865: <form name="$form" method="post" action="">
13866: <p><span class="LC_nobreak">$lt{'perm'}
13867: <label>
13868: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13869: </label>
13870:
13871: <label>
13872: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13873: </span>
13874: </p>
13875: <input type="hidden" name="phase" value="decompress_cleanup" />
13876: <br />$lt{'hows'}
13877: <div class="LC_columnSection">
13878: <fieldset>
13879: <legend>$lt{'cont'}</legend>
13880: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
13881: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13882: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13883: </fieldset>
13884: </div>
13885: END
13886: return $output.
13887: &start_data_table()."\n".
13888: $display."\n".
13889: &end_data_table()."\n".
13890: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13891: $hiddenelem.
13892: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13893: '</form>';
13894: }
13895:
13896: sub archive_javascript {
13897: my ($startcount,$numitems,$titles,$children) = @_;
13898: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13899: my $maintitle = $env{'form.comment'};
13900: my $scripttag = <<START;
13901: <script type="text/javascript">
13902: // <![CDATA[
13903:
13904: function checkAll(form,prefix) {
13905: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
13906: for (var i=0; i < form.elements.length; i++) {
13907: var id = form.elements[i].id;
13908: if ((id != '') && (id != undefined)) {
13909: if (idstr.test(id)) {
13910: if (form.elements[i].type == 'radio') {
13911: form.elements[i].checked = true;
13912: var nostart = i-$startcount;
13913: var offset = nostart%7;
13914: var count = (nostart-offset)/7;
13915: dependencyCheck(form,count,offset);
13916: }
13917: }
13918: }
13919: }
13920: }
13921:
13922: function propagateCheck(form,count) {
13923: if (count > 0) {
13924: var startelement = $startcount + ((count-1) * 7);
13925: for (var j=1; j<6; j++) {
13926: if ((j != 2) && (j != 4)) {
13927: var item = startelement + j;
13928: if (form.elements[item].type == 'radio') {
13929: if (form.elements[item].checked) {
13930: containerCheck(form,count,j);
13931: break;
13932: }
13933: }
13934: }
13935: }
13936: }
13937: }
13938:
13939: numitems = $numitems
13940: var titles = new Array(numitems);
13941: var parents = new Array(numitems);
13942: for (var i=0; i<numitems; i++) {
13943: parents[i] = new Array;
13944: }
13945: var maintitle = '$maintitle';
13946:
13947: START
13948:
13949: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13950: my @contents = split(/:/,$children->{$container});
13951: for (my $i=0; $i<@contents; $i ++) {
13952: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13953: }
13954: }
13955:
13956: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13957: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13958: }
13959:
13960: $scripttag .= <<END;
13961:
13962: function containerCheck(form,count,offset) {
13963: if (count > 0) {
13964: dependencyCheck(form,count,offset);
13965: var item = (offset+$startcount)+7*(count-1);
13966: form.elements[item].checked = true;
13967: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13968: if (parents[count].length > 0) {
13969: for (var j=0; j<parents[count].length; j++) {
13970: containerCheck(form,parents[count][j],offset);
13971: }
13972: }
13973: }
13974: }
13975: }
13976:
13977: function dependencyCheck(form,count,offset) {
13978: if (count > 0) {
13979: var chosen = (offset+$startcount)+7*(count-1);
13980: var depitem = $startcount + ((count-1) * 7) + 4;
13981: var currtype = form.elements[depitem].type;
13982: if (form.elements[chosen].value == 'dependency') {
13983: document.getElementById('arc_depon_'+count).style.display='block';
13984: form.elements[depitem].options.length = 0;
13985: form.elements[depitem].options[0] = new Option('Select','',true,true);
13986: for (var i=1; i<=numitems; i++) {
13987: if (i == count) {
13988: continue;
13989: }
13990: var startelement = $startcount + (i-1) * 7;
13991: for (var j=1; j<6; j++) {
13992: if ((j != 2) && (j!= 4)) {
13993: var item = startelement + j;
13994: if (form.elements[item].type == 'radio') {
13995: if (form.elements[item].checked) {
13996: if (form.elements[item].value == 'display') {
13997: var n = form.elements[depitem].options.length;
13998: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13999: }
14000: }
14001: }
14002: }
14003: }
14004: }
14005: } else {
14006: document.getElementById('arc_depon_'+count).style.display='none';
14007: form.elements[depitem].options.length = 0;
14008: form.elements[depitem].options[0] = new Option('Select','',true,true);
14009: }
14010: titleCheck(form,count,offset);
14011: }
14012: }
14013:
14014: function propagateSelect(form,count,offset) {
14015: if (count > 0) {
14016: var item = (1+offset+$startcount)+7*(count-1);
14017: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
14018: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14019: if (parents[count].length > 0) {
14020: for (var j=0; j<parents[count].length; j++) {
14021: containerSelect(form,parents[count][j],offset,picked);
14022: }
14023: }
14024: }
14025: }
14026: }
14027:
14028: function containerSelect(form,count,offset,picked) {
14029: if (count > 0) {
14030: var item = (offset+$startcount)+7*(count-1);
14031: if (form.elements[item].type == 'radio') {
14032: if (form.elements[item].value == 'dependency') {
14033: if (form.elements[item+1].type == 'select-one') {
14034: for (var i=0; i<form.elements[item+1].options.length; i++) {
14035: if (form.elements[item+1].options[i].value == picked) {
14036: form.elements[item+1].selectedIndex = i;
14037: break;
14038: }
14039: }
14040: }
14041: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14042: if (parents[count].length > 0) {
14043: for (var j=0; j<parents[count].length; j++) {
14044: containerSelect(form,parents[count][j],offset,picked);
14045: }
14046: }
14047: }
14048: }
14049: }
14050: }
14051: }
14052:
14053: function titleCheck(form,count,offset) {
14054: if (count > 0) {
14055: var chosen = (offset+$startcount)+7*(count-1);
14056: var depitem = $startcount + ((count-1) * 7) + 2;
14057: var currtype = form.elements[depitem].type;
14058: if (form.elements[chosen].value == 'display') {
14059: document.getElementById('arc_title_'+count).style.display='block';
14060: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14061: document.getElementById('archive_title_'+count).value=maintitle;
14062: }
14063: } else {
14064: document.getElementById('arc_title_'+count).style.display='none';
14065: if (currtype == 'text') {
14066: document.getElementById('archive_title_'+count).value='';
14067: }
14068: }
14069: }
14070: return;
14071: }
14072:
14073: // ]]>
14074: </script>
14075: END
14076: return $scripttag;
14077: }
14078:
14079: sub process_extracted_files {
14080: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14081: my $numitems = $env{'form.archive_count'};
14082: return if ((!$numitems) || ($numitems =~ /\D/));
14083: my @ids=&Apache::lonnet::current_machine_ids();
14084: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14085: %folders,%containers,%mapinner,%prompttofetch);
14086: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14087: if (grep(/^\Q$docuhome\E$/,@ids)) {
14088: $prefix = &LONCAPA::propath($docudom,$docuname);
14089: $pathtocheck = "$dir_root/$destination";
14090: $dir = $dir_root;
14091: $ishome = 1;
14092: } else {
14093: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14094: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14095: $dir = "$dir_root/$docudom/$docuname";
14096: }
14097: my $currdir = "$dir_root/$destination";
14098: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14099: if ($env{'form.folderpath'}) {
14100: my @items = split('&',$env{'form.folderpath'});
14101: $folders{'0'} = $items[-2];
14102: if ($env{'form.folderpath'} =~ /\:1$/) {
14103: $containers{'0'}='page';
14104: } else {
14105: $containers{'0'}='sequence';
14106: }
14107: }
14108: my @archdirs = &get_env_multiple('form.archive_directory');
14109: if ($numitems) {
14110: for (my $i=1; $i<=$numitems; $i++) {
14111: my $path = $env{'form.archive_content_'.$i};
14112: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14113: my $item = $1;
14114: $toplevelitems{$item} = $i;
14115: if (grep(/^\Q$i\E$/,@archdirs)) {
14116: $is_dir{$item} = 1;
14117: }
14118: }
14119: }
14120: }
14121: my ($output,%children,%parent,%titles,%dirorder,$result);
14122: if (keys(%toplevelitems) > 0) {
14123: my @contents = sort(keys(%toplevelitems));
14124: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14125: \%parent,\@contents,\%dirorder,\%titles);
14126: }
14127: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14128: if ($numitems) {
14129: for (my $i=1; $i<=$numitems; $i++) {
14130: next if ($env{'form.archive_'.$i} eq 'dependency');
14131: my $path = $env{'form.archive_content_'.$i};
14132: if ($path =~ /^\Q$pathtocheck\E/) {
14133: if ($env{'form.archive_'.$i} eq 'discard') {
14134: if ($prefix ne '' && $path ne '') {
14135: if (-e $prefix.$path) {
14136: if ((@archdirs > 0) &&
14137: (grep(/^\Q$i\E$/,@archdirs))) {
14138: $todeletedir{$prefix.$path} = 1;
14139: } else {
14140: $todelete{$prefix.$path} = 1;
14141: }
14142: }
14143: }
14144: } elsif ($env{'form.archive_'.$i} eq 'display') {
14145: my ($docstitle,$title,$url,$outer);
14146: ($title) = ($path =~ m{/([^/]+)$});
14147: $docstitle = $env{'form.archive_title_'.$i};
14148: if ($docstitle eq '') {
14149: $docstitle = $title;
14150: }
14151: $outer = 0;
14152: if (ref($dirorder{$i}) eq 'ARRAY') {
14153: if (@{$dirorder{$i}} > 0) {
14154: foreach my $item (reverse(@{$dirorder{$i}})) {
14155: if ($env{'form.archive_'.$item} eq 'display') {
14156: $outer = $item;
14157: last;
14158: }
14159: }
14160: }
14161: }
14162: my ($errtext,$fatal) =
14163: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14164: '/'.$folders{$outer}.'.'.
14165: $containers{$outer});
14166: next if ($fatal);
14167: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14168: if ($context eq 'coursedocs') {
14169: $mapinner{$i} = time;
14170: $folders{$i} = 'default_'.$mapinner{$i};
14171: $containers{$i} = 'sequence';
14172: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14173: $folders{$i}.'.'.$containers{$i};
14174: my $newidx = &LONCAPA::map::getresidx();
14175: $LONCAPA::map::resources[$newidx]=
14176: $docstitle.':'.$url.':false:normal:res';
14177: push(@LONCAPA::map::order,$newidx);
14178: my ($outtext,$errtext) =
14179: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14180: $docuname.'/'.$folders{$outer}.
14181: '.'.$containers{$outer},1,1);
14182: $newseqid{$i} = $newidx;
14183: unless ($errtext) {
14184: $result .= '<li>'.&mt('Folder: [_1] added to course',
14185: &HTML::Entities::encode($docstitle,'<>&"')).
14186: '</li>'."\n";
14187: }
14188: }
14189: } else {
14190: if ($context eq 'coursedocs') {
14191: my $newidx=&LONCAPA::map::getresidx();
14192: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14193: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14194: $title;
14195: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
14196: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14197: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14198: }
14199: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14200: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14201: }
14202: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14203: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14204: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14205: unless ($ishome) {
14206: my $fetch = "$newdest{$i}/$title";
14207: $fetch =~ s/^\Q$prefix$dir\E//;
14208: $prompttofetch{$fetch} = 1;
14209: }
14210: }
14211: }
14212: $LONCAPA::map::resources[$newidx]=
14213: $docstitle.':'.$url.':false:normal:res';
14214: push(@LONCAPA::map::order, $newidx);
14215: my ($outtext,$errtext)=
14216: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14217: $docuname.'/'.$folders{$outer}.
14218: '.'.$containers{$outer},1,1);
14219: unless ($errtext) {
14220: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14221: $result .= '<li>'.&mt('File: [_1] added to course',
14222: &HTML::Entities::encode($docstitle,'<>&"')).
14223: '</li>'."\n";
14224: }
14225: }
14226: } else {
14227: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14228: &HTML::Entities::encode($path,'<>&"')).'<br />';
14229: }
14230: }
14231: }
14232: }
14233: } else {
14234: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14235: &HTML::Entities::encode($path,'<>&"')).'<br />';
14236: }
14237: }
14238: for (my $i=1; $i<=$numitems; $i++) {
14239: next unless ($env{'form.archive_'.$i} eq 'dependency');
14240: my $path = $env{'form.archive_content_'.$i};
14241: if ($path =~ /^\Q$pathtocheck\E/) {
14242: my ($title) = ($path =~ m{/([^/]+)$});
14243: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14244: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14245: if (ref($dirorder{$i}) eq 'ARRAY') {
14246: my ($itemidx,$fullpath,$relpath);
14247: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14248: my $container = $dirorder{$referrer{$i}}->[-1];
14249: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14250: if ($dirorder{$i}->[$j] eq $container) {
14251: $itemidx = $j;
14252: }
14253: }
14254: }
14255: if ($itemidx eq '') {
14256: $itemidx = 0;
14257: }
14258: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14259: if ($mapinner{$referrer{$i}}) {
14260: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14261: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14262: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14263: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14264: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14265: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14266: if (!-e $fullpath) {
14267: mkdir($fullpath,0755);
14268: }
14269: }
14270: } else {
14271: last;
14272: }
14273: }
14274: }
14275: } elsif ($newdest{$referrer{$i}}) {
14276: $fullpath = $newdest{$referrer{$i}};
14277: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14278: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14279: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14280: last;
14281: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14282: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14283: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14284: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14285: if (!-e $fullpath) {
14286: mkdir($fullpath,0755);
14287: }
14288: }
14289: } else {
14290: last;
14291: }
14292: }
14293: }
14294: if ($fullpath ne '') {
14295: if (-e "$prefix$path") {
14296: unless (rename("$prefix$path","$fullpath/$title")) {
14297: $warning .= &mt('Failed to rename dependency').'<br />';
14298: }
14299: }
14300: if (-e "$fullpath/$title") {
14301: my $showpath;
14302: if ($relpath ne '') {
14303: $showpath = "$relpath/$title";
14304: } else {
14305: $showpath = "/$title";
14306: }
14307: $result .= '<li>'.&mt('[_1] included as a dependency',
14308: &HTML::Entities::encode($showpath,'<>&"')).
14309: '</li>'."\n";
14310: unless ($ishome) {
14311: my $fetch = "$fullpath/$title";
14312: $fetch =~ s/^\Q$prefix$dir\E//;
14313: $prompttofetch{$fetch} = 1;
14314: }
14315: }
14316: }
14317: }
14318: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14319: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14320: &HTML::Entities::encode($path,'<>&"'),
14321: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14322: '<br />';
14323: }
14324: } else {
14325: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14326: &HTML::Entities::encode($path)).'<br />';
14327: }
14328: }
14329: if (keys(%todelete)) {
14330: foreach my $key (keys(%todelete)) {
14331: unlink($key);
14332: }
14333: }
14334: if (keys(%todeletedir)) {
14335: foreach my $key (keys(%todeletedir)) {
14336: rmdir($key);
14337: }
14338: }
14339: foreach my $dir (sort(keys(%is_dir))) {
14340: if (($pathtocheck ne '') && ($dir ne '')) {
14341: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14342: }
14343: }
14344: if ($result ne '') {
14345: $output .= '<ul>'."\n".
14346: $result."\n".
14347: '</ul>';
14348: }
14349: unless ($ishome) {
14350: my $replicationfail;
14351: foreach my $item (keys(%prompttofetch)) {
14352: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14353: unless ($fetchresult eq 'ok') {
14354: $replicationfail .= '<li>'.$item.'</li>'."\n";
14355: }
14356: }
14357: if ($replicationfail) {
14358: $output .= '<p class="LC_error">'.
14359: &mt('Course home server failed to retrieve:').'<ul>'.
14360: $replicationfail.
14361: '</ul></p>';
14362: }
14363: }
14364: } else {
14365: $warning = &mt('No items found in archive.');
14366: }
14367: if ($error) {
14368: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14369: $error.'</p>'."\n";
14370: }
14371: if ($warning) {
14372: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14373: }
14374: return $output;
14375: }
14376:
14377: sub cleanup_empty_dirs {
14378: my ($path) = @_;
14379: if (($path ne '') && (-d $path)) {
14380: if (opendir(my $dirh,$path)) {
14381: my @dircontents = grep(!/^\./,readdir($dirh));
14382: my $numitems = 0;
14383: foreach my $item (@dircontents) {
14384: if (-d "$path/$item") {
14385: &cleanup_empty_dirs("$path/$item");
14386: if (-e "$path/$item") {
14387: $numitems ++;
14388: }
14389: } else {
14390: $numitems ++;
14391: }
14392: }
14393: if ($numitems == 0) {
14394: rmdir($path);
14395: }
14396: closedir($dirh);
14397: }
14398: }
14399: return;
14400: }
14401:
14402: =pod
14403:
14404: =item * &get_folder_hierarchy()
14405:
14406: Provides hierarchy of names of folders/sub-folders containing the current
14407: item,
14408:
14409: Inputs: 3
14410: - $navmap - navmaps object
14411:
14412: - $map - url for map (either the trigger itself, or map containing
14413: the resource, which is the trigger).
14414:
14415: - $showitem - 1 => show title for map itself; 0 => do not show.
14416:
14417: Outputs: 1 @pathitems - array of folder/subfolder names.
14418:
14419: =cut
14420:
14421: sub get_folder_hierarchy {
14422: my ($navmap,$map,$showitem) = @_;
14423: my @pathitems;
14424: if (ref($navmap)) {
14425: my $mapres = $navmap->getResourceByUrl($map);
14426: if (ref($mapres)) {
14427: my $pcslist = $mapres->map_hierarchy();
14428: if ($pcslist ne '') {
14429: my @pcs = split(/,/,$pcslist);
14430: foreach my $pc (@pcs) {
14431: if ($pc == 1) {
14432: push(@pathitems,&mt('Main Content'));
14433: } else {
14434: my $res = $navmap->getByMapPc($pc);
14435: if (ref($res)) {
14436: my $title = $res->compTitle();
14437: $title =~ s/\W+/_/g;
14438: if ($title ne '') {
14439: push(@pathitems,$title);
14440: }
14441: }
14442: }
14443: }
14444: }
14445: if ($showitem) {
14446: if ($mapres->{ID} eq '0.0') {
14447: push(@pathitems,&mt('Main Content'));
14448: } else {
14449: my $maptitle = $mapres->compTitle();
14450: $maptitle =~ s/\W+/_/g;
14451: if ($maptitle ne '') {
14452: push(@pathitems,$maptitle);
14453: }
14454: }
14455: }
14456: }
14457: }
14458: return @pathitems;
14459: }
14460:
14461: =pod
14462:
14463: =item * &get_turnedin_filepath()
14464:
14465: Determines path in a user's portfolio file for storage of files uploaded
14466: to a specific essayresponse or dropbox item.
14467:
14468: Inputs: 3 required + 1 optional.
14469: $symb is symb for resource, $uname and $udom are for current user (required).
14470: $caller is optional (can be "submission", if routine is called when storing
14471: an upoaded file when "Submit Answer" button was pressed).
14472:
14473: Returns array containing $path and $multiresp.
14474: $path is path in portfolio. $multiresp is 1 if this resource contains more
14475: than one file upload item. Callers of routine should append partid as a
14476: subdirectory to $path in cases where $multiresp is 1.
14477:
14478: Called by: homework/essayresponse.pm and homework/structuretags.pm
14479:
14480: =cut
14481:
14482: sub get_turnedin_filepath {
14483: my ($symb,$uname,$udom,$caller) = @_;
14484: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14485: my $turnindir;
14486: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14487: $turnindir = $userhash{'turnindir'};
14488: my ($path,$multiresp);
14489: if ($turnindir eq '') {
14490: if ($caller eq 'submission') {
14491: $turnindir = &mt('turned in');
14492: $turnindir =~ s/\W+/_/g;
14493: my %newhash = (
14494: 'turnindir' => $turnindir,
14495: );
14496: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14497: }
14498: }
14499: if ($turnindir ne '') {
14500: $path = '/'.$turnindir.'/';
14501: my ($multipart,$turnin,@pathitems);
14502: my $navmap = Apache::lonnavmaps::navmap->new();
14503: if (defined($navmap)) {
14504: my $mapres = $navmap->getResourceByUrl($map);
14505: if (ref($mapres)) {
14506: my $pcslist = $mapres->map_hierarchy();
14507: if ($pcslist ne '') {
14508: foreach my $pc (split(/,/,$pcslist)) {
14509: my $res = $navmap->getByMapPc($pc);
14510: if (ref($res)) {
14511: my $title = $res->compTitle();
14512: $title =~ s/\W+/_/g;
14513: if ($title ne '') {
14514: if (($pc > 1) && (length($title) > 12)) {
14515: $title = substr($title,0,12);
14516: }
14517: push(@pathitems,$title);
14518: }
14519: }
14520: }
14521: }
14522: my $maptitle = $mapres->compTitle();
14523: $maptitle =~ s/\W+/_/g;
14524: if ($maptitle ne '') {
14525: if (length($maptitle) > 12) {
14526: $maptitle = substr($maptitle,0,12);
14527: }
14528: push(@pathitems,$maptitle);
14529: }
14530: unless ($env{'request.state'} eq 'construct') {
14531: my $res = $navmap->getBySymb($symb);
14532: if (ref($res)) {
14533: my $partlist = $res->parts();
14534: my $totaluploads = 0;
14535: if (ref($partlist) eq 'ARRAY') {
14536: foreach my $part (@{$partlist}) {
14537: my @types = $res->responseType($part);
14538: my @ids = $res->responseIds($part);
14539: for (my $i=0; $i < scalar(@ids); $i++) {
14540: if ($types[$i] eq 'essay') {
14541: my $partid = $part.'_'.$ids[$i];
14542: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14543: $totaluploads ++;
14544: }
14545: }
14546: }
14547: }
14548: if ($totaluploads > 1) {
14549: $multiresp = 1;
14550: }
14551: }
14552: }
14553: }
14554: } else {
14555: return;
14556: }
14557: } else {
14558: return;
14559: }
14560: my $restitle=&Apache::lonnet::gettitle($symb);
14561: $restitle =~ s/\W+/_/g;
14562: if ($restitle eq '') {
14563: $restitle = ($resurl =~ m{/[^/]+$});
14564: if ($restitle eq '') {
14565: $restitle = time;
14566: }
14567: }
14568: if (length($restitle) > 12) {
14569: $restitle = substr($restitle,0,12);
14570: }
14571: push(@pathitems,$restitle);
14572: $path .= join('/',@pathitems);
14573: }
14574: return ($path,$multiresp);
14575: }
14576:
14577: =pod
14578:
14579: =back
14580:
14581: =head1 CSV Upload/Handling functions
14582:
14583: =over 4
14584:
14585: =item * &upfile_store($r)
14586:
14587: Store uploaded file, $r should be the HTTP Request object,
14588: needs $env{'form.upfile'}
14589: returns $datatoken to be put into hidden field
14590:
14591: =cut
14592:
14593: sub upfile_store {
14594: my $r=shift;
14595: $env{'form.upfile'}=~s/\r/\n/gs;
14596: $env{'form.upfile'}=~s/\f/\n/gs;
14597: $env{'form.upfile'}=~s/\n+/\n/gs;
14598: $env{'form.upfile'}=~s/\n+$//gs;
14599:
14600: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14601: '_enroll_'.$env{'request.course.id'}.'_'.
14602: time.'_'.$$);
14603: return if ($datatoken eq '');
14604:
14605: {
14606: my $datafile = $r->dir_config('lonDaemons').
14607: '/tmp/'.$datatoken.'.tmp';
14608: if ( open(my $fh,'>',$datafile) ) {
14609: print $fh $env{'form.upfile'};
14610: close($fh);
14611: }
14612: }
14613: return $datatoken;
14614: }
14615:
14616: =pod
14617:
14618: =item * &load_tmp_file($r,$datatoken)
14619:
14620: Load uploaded file from tmp, $r should be the HTTP Request object,
14621: $datatoken is the name to assign to the temporary file.
14622: sets $env{'form.upfile'} to the contents of the file
14623:
14624: =cut
14625:
14626: sub load_tmp_file {
14627: my ($r,$datatoken) = @_;
14628: return if ($datatoken eq '');
14629: my @studentdata=();
14630: {
14631: my $studentfile = $r->dir_config('lonDaemons').
14632: '/tmp/'.$datatoken.'.tmp';
14633: if ( open(my $fh,'<',$studentfile) ) {
14634: @studentdata=<$fh>;
14635: close($fh);
14636: }
14637: }
14638: $env{'form.upfile'}=join('',@studentdata);
14639: }
14640:
14641: sub valid_datatoken {
14642: my ($datatoken) = @_;
14643: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14644: return $datatoken;
14645: }
14646: return;
14647: }
14648:
14649: =pod
14650:
14651: =item * &upfile_record_sep()
14652:
14653: Separate uploaded file into records
14654: returns array of records,
14655: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14656:
14657: =cut
14658:
14659: sub upfile_record_sep {
14660: if ($env{'form.upfiletype'} eq 'xml') {
14661: } else {
14662: my @records;
14663: foreach my $line (split(/\n/,$env{'form.upfile'})) {
14664: if ($line=~/^\s*$/) { next; }
14665: push(@records,$line);
14666: }
14667: return @records;
14668: }
14669: }
14670:
14671: =pod
14672:
14673: =item * &record_sep($record)
14674:
14675: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14676:
14677: =cut
14678:
14679: sub takeleft {
14680: my $index=shift;
14681: return substr('0000'.$index,-4,4);
14682: }
14683:
14684: sub record_sep {
14685: my $record=shift;
14686: my %components=();
14687: if ($env{'form.upfiletype'} eq 'xml') {
14688: } elsif ($env{'form.upfiletype'} eq 'space') {
14689: my $i=0;
14690: foreach my $field (split(/\s+/,$record)) {
14691: $field=~s/^(\"|\')//;
14692: $field=~s/(\"|\')$//;
14693: $components{&takeleft($i)}=$field;
14694: $i++;
14695: }
14696: } elsif ($env{'form.upfiletype'} eq 'tab') {
14697: my $i=0;
14698: foreach my $field (split(/\t/,$record)) {
14699: $field=~s/^(\"|\')//;
14700: $field=~s/(\"|\')$//;
14701: $components{&takeleft($i)}=$field;
14702: $i++;
14703: }
14704: } else {
14705: my $separator=',';
14706: if ($env{'form.upfiletype'} eq 'semisv') {
14707: $separator=';';
14708: }
14709: my $i=0;
14710: # the character we are looking for to indicate the end of a quote or a record
14711: my $looking_for=$separator;
14712: # do not add the characters to the fields
14713: my $ignore=0;
14714: # we just encountered a separator (or the beginning of the record)
14715: my $just_found_separator=1;
14716: # store the field we are working on here
14717: my $field='';
14718: # work our way through all characters in record
14719: foreach my $character ($record=~/(.)/g) {
14720: if ($character eq $looking_for) {
14721: if ($character ne $separator) {
14722: # Found the end of a quote, again looking for separator
14723: $looking_for=$separator;
14724: $ignore=1;
14725: } else {
14726: # Found a separator, store away what we got
14727: $components{&takeleft($i)}=$field;
14728: $i++;
14729: $just_found_separator=1;
14730: $ignore=0;
14731: $field='';
14732: }
14733: next;
14734: }
14735: # single or double quotation marks after a separator indicate beginning of a quote
14736: # we are now looking for the end of the quote and need to ignore separators
14737: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
14738: $looking_for=$character;
14739: next;
14740: }
14741: # ignore would be true after we reached the end of a quote
14742: if ($ignore) { next; }
14743: if (($just_found_separator) && ($character=~/\s/)) { next; }
14744: $field.=$character;
14745: $just_found_separator=0;
14746: }
14747: # catch the very last entry, since we never encountered the separator
14748: $components{&takeleft($i)}=$field;
14749: }
14750: return %components;
14751: }
14752:
14753: ######################################################
14754: ######################################################
14755:
14756: =pod
14757:
14758: =item * &upfile_select_html()
14759:
14760: Return HTML code to select a file from the users machine and specify
14761: the file type.
14762:
14763: =cut
14764:
14765: ######################################################
14766: ######################################################
14767: sub upfile_select_html {
14768: my %Types = (
14769: csv => &mt('CSV (comma separated values, spreadsheet)'),
14770: semisv => &mt('Semicolon separated values'),
14771: space => &mt('Space separated'),
14772: tab => &mt('Tabulator separated'),
14773: # xml => &mt('HTML/XML'),
14774: );
14775: my $Str = '<input type="file" name="upfile" size="50" />'.
14776: '<br />'.&mt('Type').': <select name="upfiletype">';
14777: foreach my $type (sort(keys(%Types))) {
14778: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14779: }
14780: $Str .= "</select>\n";
14781: return $Str;
14782: }
14783:
14784: sub get_samples {
14785: my ($records,$toget) = @_;
14786: my @samples=({});
14787: my $got=0;
14788: foreach my $rec (@$records) {
14789: my %temp = &record_sep($rec);
14790: if (! grep(/\S/, values(%temp))) { next; }
14791: if (%temp) {
14792: $samples[$got]=\%temp;
14793: $got++;
14794: if ($got == $toget) { last; }
14795: }
14796: }
14797: return \@samples;
14798: }
14799:
14800: ######################################################
14801: ######################################################
14802:
14803: =pod
14804:
14805: =item * &csv_print_samples($r,$records)
14806:
14807: Prints a table of sample values from each column uploaded $r is an
14808: Apache Request ref, $records is an arrayref from
14809: &Apache::loncommon::upfile_record_sep
14810:
14811: =cut
14812:
14813: ######################################################
14814: ######################################################
14815: sub csv_print_samples {
14816: my ($r,$records) = @_;
14817: my $samples = &get_samples($records,5);
14818:
14819: $r->print(&mt('Samples').'<br />'.&start_data_table().
14820: &start_data_table_header_row());
14821: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14822: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14823: $r->print(&end_data_table_header_row());
14824: foreach my $hash (@$samples) {
14825: $r->print(&start_data_table_row());
14826: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14827: $r->print('<td>');
14828: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14829: $r->print('</td>');
14830: }
14831: $r->print(&end_data_table_row());
14832: }
14833: $r->print(&end_data_table().'<br />'."\n");
14834: }
14835:
14836: ######################################################
14837: ######################################################
14838:
14839: =pod
14840:
14841: =item * &csv_print_select_table($r,$records,$d)
14842:
14843: Prints a table to create associations between values and table columns.
14844:
14845: $r is an Apache Request ref,
14846: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14847: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14848:
14849: =cut
14850:
14851: ######################################################
14852: ######################################################
14853: sub csv_print_select_table {
14854: my ($r,$records,$d) = @_;
14855: my $i=0;
14856: my $samples = &get_samples($records,1);
14857: $r->print(&mt('Associate columns with student attributes.')."\n".
14858: &start_data_table().&start_data_table_header_row().
14859: '<th>'.&mt('Attribute').'</th>'.
14860: '<th>'.&mt('Column').'</th>'.
14861: &end_data_table_header_row()."\n");
14862: foreach my $array_ref (@$d) {
14863: my ($value,$display,$defaultcol)=@{ $array_ref };
14864: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
14865:
14866: $r->print('<td><select name="f'.$i.'"'.
14867: ' onchange="javascript:flip(this.form,'.$i.');">');
14868: $r->print('<option value="none"></option>');
14869: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14870: $r->print('<option value="'.$sample.'"'.
14871: ($sample eq $defaultcol ? ' selected="selected" ' : '').
14872: '>'.&mt('Column [_1]',($sample+1)).'</option>');
14873: }
14874: $r->print('</select></td>'.&end_data_table_row()."\n");
14875: $i++;
14876: }
14877: $r->print(&end_data_table());
14878: $i--;
14879: return $i;
14880: }
14881:
14882: ######################################################
14883: ######################################################
14884:
14885: =pod
14886:
14887: =item * &csv_samples_select_table($r,$records,$d)
14888:
14889: Prints a table of sample values from the upload and can make associate samples to internal names.
14890:
14891: $r is an Apache Request ref,
14892: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14893: $d is an array of 2 element arrays (internal name, displayed name)
14894:
14895: =cut
14896:
14897: ######################################################
14898: ######################################################
14899: sub csv_samples_select_table {
14900: my ($r,$records,$d) = @_;
14901: my $i=0;
14902: #
14903: my $max_samples = 5;
14904: my $samples = &get_samples($records,$max_samples);
14905: $r->print(&start_data_table().
14906: &start_data_table_header_row().'<th>'.
14907: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14908: &end_data_table_header_row());
14909:
14910: foreach my $key (sort(keys(%{ $samples->[0] }))) {
14911: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14912: ' onchange="javascript:flip(this.form,'.$i.');">');
14913: foreach my $option (@$d) {
14914: my ($value,$display,$defaultcol)=@{ $option };
14915: $r->print('<option value="'.$value.'"'.
14916: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14917: $display.'</option>');
14918: }
14919: $r->print('</select></td><td>');
14920: foreach my $line (0..($max_samples-1)) {
14921: if (defined($samples->[$line]{$key})) {
14922: $r->print($samples->[$line]{$key}."<br />\n");
14923: }
14924: }
14925: $r->print('</td>'.&end_data_table_row());
14926: $i++;
14927: }
14928: $r->print(&end_data_table());
14929: $i--;
14930: return($i);
14931: }
14932:
14933: ######################################################
14934: ######################################################
14935:
14936: =pod
14937:
14938: =item * &clean_excel_name($name)
14939:
14940: Returns a replacement for $name which does not contain any illegal characters.
14941:
14942: =cut
14943:
14944: ######################################################
14945: ######################################################
14946: sub clean_excel_name {
14947: my ($name) = @_;
14948: $name =~ s/[:\*\?\/\\]//g;
14949: if (length($name) > 31) {
14950: $name = substr($name,0,31);
14951: }
14952: return $name;
14953: }
14954:
14955: =pod
14956:
14957: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14958:
14959: Returns either 1 or undef
14960:
14961: 1 if the part is to be hidden, undef if it is to be shown
14962:
14963: Arguments are:
14964:
14965: $id the id of the part to be checked
14966: $symb, optional the symb of the resource to check
14967: $udom, optional the domain of the user to check for
14968: $uname, optional the username of the user to check for
14969:
14970: =cut
14971:
14972: sub check_if_partid_hidden {
14973: my ($id,$symb,$udom,$uname) = @_;
14974: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14975: $symb,$udom,$uname);
14976: my $truth=1;
14977: #if the string starts with !, then the list is the list to show not hide
14978: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14979: my @hiddenlist=split(/,/,$hiddenparts);
14980: foreach my $checkid (@hiddenlist) {
14981: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14982: }
14983: return !$truth;
14984: }
14985:
14986:
14987: ############################################################
14988: ############################################################
14989:
14990: =pod
14991:
14992: =back
14993:
14994: =head1 cgi-bin script and graphing routines
14995:
14996: =over 4
14997:
14998: =item * &get_cgi_id()
14999:
15000: Inputs: none
15001:
15002: Returns an id which can be used to pass environment variables
15003: to various cgi-bin scripts. These environment variables will
15004: be removed from the users environment after a given time by
15005: the routine &Apache::lonnet::transfer_profile_to_env.
15006:
15007: =cut
15008:
15009: ############################################################
15010: ############################################################
15011: my $uniq=0;
15012: sub get_cgi_id {
15013: $uniq=($uniq+1)%100000;
15014: return (time.'_'.$$.'_'.$uniq);
15015: }
15016:
15017: ############################################################
15018: ############################################################
15019:
15020: =pod
15021:
15022: =item * &DrawBarGraph()
15023:
15024: Facilitates the plotting of data in a (stacked) bar graph.
15025: Puts plot definition data into the users environment in order for
15026: graph.png to plot it. Returns an <img> tag for the plot.
15027: The bars on the plot are labeled '1','2',...,'n'.
15028:
15029: Inputs:
15030:
15031: =over 4
15032:
15033: =item $Title: string, the title of the plot
15034:
15035: =item $xlabel: string, text describing the X-axis of the plot
15036:
15037: =item $ylabel: string, text describing the Y-axis of the plot
15038:
15039: =item $Max: scalar, the maximum Y value to use in the plot
15040: If $Max is < any data point, the graph will not be rendered.
15041:
15042: =item $colors: array ref holding the colors to be used for the data sets when
15043: they are plotted. If undefined, default values will be used.
15044:
15045: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15046:
15047: =item @Values: An array of array references. Each array reference holds data
15048: to be plotted in a stacked bar chart.
15049:
15050: =item If the final element of @Values is a hash reference the key/value
15051: pairs will be added to the graph definition.
15052:
15053: =back
15054:
15055: Returns:
15056:
15057: An <img> tag which references graph.png and the appropriate identifying
15058: information for the plot.
15059:
15060: =cut
15061:
15062: ############################################################
15063: ############################################################
15064: sub DrawBarGraph {
15065: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15066: #
15067: if (! defined($colors)) {
15068: $colors = ['#33ff00',
15069: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15070: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15071: ];
15072: }
15073: my $extra_settings = {};
15074: if (ref($Values[-1]) eq 'HASH') {
15075: $extra_settings = pop(@Values);
15076: }
15077: #
15078: my $identifier = &get_cgi_id();
15079: my $id = 'cgi.'.$identifier;
15080: if (! @Values || ref($Values[0]) ne 'ARRAY') {
15081: return '';
15082: }
15083: #
15084: my @Labels;
15085: if (defined($labels)) {
15086: @Labels = @$labels;
15087: } else {
15088: for (my $i=0;$i<@{$Values[0]};$i++) {
15089: push(@Labels,$i+1);
15090: }
15091: }
15092: #
15093: my $NumBars = scalar(@{$Values[0]});
15094: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15095: my %ValuesHash;
15096: my $NumSets=1;
15097: foreach my $array (@Values) {
15098: next if (! ref($array));
15099: $ValuesHash{$id.'.data.'.$NumSets++} =
15100: join(',',@$array);
15101: }
15102: #
15103: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15104: if ($NumBars < 3) {
15105: $width = 120+$NumBars*32;
15106: $xskip = 1;
15107: $bar_width = 30;
15108: } elsif ($NumBars < 5) {
15109: $width = 120+$NumBars*20;
15110: $xskip = 1;
15111: $bar_width = 20;
15112: } elsif ($NumBars < 10) {
15113: $width = 120+$NumBars*15;
15114: $xskip = 1;
15115: $bar_width = 15;
15116: } elsif ($NumBars <= 25) {
15117: $width = 120+$NumBars*11;
15118: $xskip = 5;
15119: $bar_width = 8;
15120: } elsif ($NumBars <= 50) {
15121: $width = 120+$NumBars*8;
15122: $xskip = 5;
15123: $bar_width = 4;
15124: } else {
15125: $width = 120+$NumBars*8;
15126: $xskip = 5;
15127: $bar_width = 4;
15128: }
15129: #
15130: $Max = 1 if ($Max < 1);
15131: if ( int($Max) < $Max ) {
15132: $Max++;
15133: $Max = int($Max);
15134: }
15135: $Title = '' if (! defined($Title));
15136: $xlabel = '' if (! defined($xlabel));
15137: $ylabel = '' if (! defined($ylabel));
15138: $ValuesHash{$id.'.title'} = &escape($Title);
15139: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
15140: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
15141: $ValuesHash{$id.'.y_max_value'} = $Max;
15142: $ValuesHash{$id.'.NumBars'} = $NumBars;
15143: $ValuesHash{$id.'.NumSets'} = $NumSets;
15144: $ValuesHash{$id.'.PlotType'} = 'bar';
15145: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15146: $ValuesHash{$id.'.height'} = $height;
15147: $ValuesHash{$id.'.width'} = $width;
15148: $ValuesHash{$id.'.xskip'} = $xskip;
15149: $ValuesHash{$id.'.bar_width'} = $bar_width;
15150: $ValuesHash{$id.'.labels'} = join(',',@Labels);
15151: #
15152: # Deal with other parameters
15153: while (my ($key,$value) = each(%$extra_settings)) {
15154: $ValuesHash{$id.'.'.$key} = $value;
15155: }
15156: #
15157: &Apache::lonnet::appenv(\%ValuesHash);
15158: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15159: }
15160:
15161: ############################################################
15162: ############################################################
15163:
15164: =pod
15165:
15166: =item * &DrawXYGraph()
15167:
15168: Facilitates the plotting of data in an XY graph.
15169: Puts plot definition data into the users environment in order for
15170: graph.png to plot it. Returns an <img> tag for the plot.
15171:
15172: Inputs:
15173:
15174: =over 4
15175:
15176: =item $Title: string, the title of the plot
15177:
15178: =item $xlabel: string, text describing the X-axis of the plot
15179:
15180: =item $ylabel: string, text describing the Y-axis of the plot
15181:
15182: =item $Max: scalar, the maximum Y value to use in the plot
15183: If $Max is < any data point, the graph will not be rendered.
15184:
15185: =item $colors: Array ref containing the hex color codes for the data to be
15186: plotted in. If undefined, default values will be used.
15187:
15188: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15189:
15190: =item $Ydata: Array ref containing Array refs.
15191: Each of the contained arrays will be plotted as a separate curve.
15192:
15193: =item %Values: hash indicating or overriding any default values which are
15194: passed to graph.png.
15195: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15196:
15197: =back
15198:
15199: Returns:
15200:
15201: An <img> tag which references graph.png and the appropriate identifying
15202: information for the plot.
15203:
15204: =cut
15205:
15206: ############################################################
15207: ############################################################
15208: sub DrawXYGraph {
15209: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15210: #
15211: # Create the identifier for the graph
15212: my $identifier = &get_cgi_id();
15213: my $id = 'cgi.'.$identifier;
15214: #
15215: $Title = '' if (! defined($Title));
15216: $xlabel = '' if (! defined($xlabel));
15217: $ylabel = '' if (! defined($ylabel));
15218: my %ValuesHash =
15219: (
15220: $id.'.title' => &escape($Title),
15221: $id.'.xlabel' => &escape($xlabel),
15222: $id.'.ylabel' => &escape($ylabel),
15223: $id.'.y_max_value'=> $Max,
15224: $id.'.labels' => join(',',@$Xlabels),
15225: $id.'.PlotType' => 'XY',
15226: );
15227: #
15228: if (defined($colors) && ref($colors) eq 'ARRAY') {
15229: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15230: }
15231: #
15232: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15233: return '';
15234: }
15235: my $NumSets=1;
15236: foreach my $array (@{$Ydata}){
15237: next if (! ref($array));
15238: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15239: }
15240: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15241: #
15242: # Deal with other parameters
15243: while (my ($key,$value) = each(%Values)) {
15244: $ValuesHash{$id.'.'.$key} = $value;
15245: }
15246: #
15247: &Apache::lonnet::appenv(\%ValuesHash);
15248: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15249: }
15250:
15251: ############################################################
15252: ############################################################
15253:
15254: =pod
15255:
15256: =item * &DrawXYYGraph()
15257:
15258: Facilitates the plotting of data in an XY graph with two Y axes.
15259: Puts plot definition data into the users environment in order for
15260: graph.png to plot it. Returns an <img> tag for the plot.
15261:
15262: Inputs:
15263:
15264: =over 4
15265:
15266: =item $Title: string, the title of the plot
15267:
15268: =item $xlabel: string, text describing the X-axis of the plot
15269:
15270: =item $ylabel: string, text describing the Y-axis of the plot
15271:
15272: =item $colors: Array ref containing the hex color codes for the data to be
15273: plotted in. If undefined, default values will be used.
15274:
15275: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15276:
15277: =item $Ydata1: The first data set
15278:
15279: =item $Min1: The minimum value of the left Y-axis
15280:
15281: =item $Max1: The maximum value of the left Y-axis
15282:
15283: =item $Ydata2: The second data set
15284:
15285: =item $Min2: The minimum value of the right Y-axis
15286:
15287: =item $Max2: The maximum value of the left Y-axis
15288:
15289: =item %Values: hash indicating or overriding any default values which are
15290: passed to graph.png.
15291: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15292:
15293: =back
15294:
15295: Returns:
15296:
15297: An <img> tag which references graph.png and the appropriate identifying
15298: information for the plot.
15299:
15300: =cut
15301:
15302: ############################################################
15303: ############################################################
15304: sub DrawXYYGraph {
15305: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15306: $Ydata2,$Min2,$Max2,%Values)=@_;
15307: #
15308: # Create the identifier for the graph
15309: my $identifier = &get_cgi_id();
15310: my $id = 'cgi.'.$identifier;
15311: #
15312: $Title = '' if (! defined($Title));
15313: $xlabel = '' if (! defined($xlabel));
15314: $ylabel = '' if (! defined($ylabel));
15315: my %ValuesHash =
15316: (
15317: $id.'.title' => &escape($Title),
15318: $id.'.xlabel' => &escape($xlabel),
15319: $id.'.ylabel' => &escape($ylabel),
15320: $id.'.labels' => join(',',@$Xlabels),
15321: $id.'.PlotType' => 'XY',
15322: $id.'.NumSets' => 2,
15323: $id.'.two_axes' => 1,
15324: $id.'.y1_max_value' => $Max1,
15325: $id.'.y1_min_value' => $Min1,
15326: $id.'.y2_max_value' => $Max2,
15327: $id.'.y2_min_value' => $Min2,
15328: );
15329: #
15330: if (defined($colors) && ref($colors) eq 'ARRAY') {
15331: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15332: }
15333: #
15334: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15335: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15336: return '';
15337: }
15338: my $NumSets=1;
15339: foreach my $array ($Ydata1,$Ydata2){
15340: next if (! ref($array));
15341: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15342: }
15343: #
15344: # Deal with other parameters
15345: while (my ($key,$value) = each(%Values)) {
15346: $ValuesHash{$id.'.'.$key} = $value;
15347: }
15348: #
15349: &Apache::lonnet::appenv(\%ValuesHash);
15350: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15351: }
15352:
15353: ############################################################
15354: ############################################################
15355:
15356: =pod
15357:
15358: =back
15359:
15360: =head1 Statistics helper routines?
15361:
15362: Bad place for them but what the hell.
15363:
15364: =over 4
15365:
15366: =item * &chartlink()
15367:
15368: Returns a link to the chart for a specific student.
15369:
15370: Inputs:
15371:
15372: =over 4
15373:
15374: =item $linktext: The text of the link
15375:
15376: =item $sname: The students username
15377:
15378: =item $sdomain: The students domain
15379:
15380: =back
15381:
15382: =back
15383:
15384: =cut
15385:
15386: ############################################################
15387: ############################################################
15388: sub chartlink {
15389: my ($linktext, $sname, $sdomain) = @_;
15390: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15391: '&SelectedStudent='.&escape($sname.':'.$sdomain).
15392: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
15393: '">'.$linktext.'</a>';
15394: }
15395:
15396: #######################################################
15397: #######################################################
15398:
15399: =pod
15400:
15401: =head1 Course Environment Routines
15402:
15403: =over 4
15404:
15405: =item * &restore_course_settings()
15406:
15407: =item * &store_course_settings()
15408:
15409: Restores/Store indicated form parameters from the course environment.
15410: Will not overwrite existing values of the form parameters.
15411:
15412: Inputs:
15413: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15414:
15415: a hash ref describing the data to be stored. For example:
15416:
15417: %Save_Parameters = ('Status' => 'scalar',
15418: 'chartoutputmode' => 'scalar',
15419: 'chartoutputdata' => 'scalar',
15420: 'Section' => 'array',
15421: 'Group' => 'array',
15422: 'StudentData' => 'array',
15423: 'Maps' => 'array');
15424:
15425: Returns: both routines return nothing
15426:
15427: =back
15428:
15429: =cut
15430:
15431: #######################################################
15432: #######################################################
15433: sub store_course_settings {
15434: return &store_settings($env{'request.course.id'},@_);
15435: }
15436:
15437: sub store_settings {
15438: # save to the environment
15439: # appenv the same items, just to be safe
15440: my $udom = $env{'user.domain'};
15441: my $uname = $env{'user.name'};
15442: my ($context,$prefix,$Settings) = @_;
15443: my %SaveHash;
15444: my %AppHash;
15445: while (my ($setting,$type) = each(%$Settings)) {
15446: my $basename = join('.','internal',$context,$prefix,$setting);
15447: my $envname = 'environment.'.$basename;
15448: if (exists($env{'form.'.$setting})) {
15449: # Save this value away
15450: if ($type eq 'scalar' &&
15451: (! exists($env{$envname}) ||
15452: $env{$envname} ne $env{'form.'.$setting})) {
15453: $SaveHash{$basename} = $env{'form.'.$setting};
15454: $AppHash{$envname} = $env{'form.'.$setting};
15455: } elsif ($type eq 'array') {
15456: my $stored_form;
15457: if (ref($env{'form.'.$setting})) {
15458: $stored_form = join(',',
15459: map {
15460: &escape($_);
15461: } sort(@{$env{'form.'.$setting}}));
15462: } else {
15463: $stored_form =
15464: &escape($env{'form.'.$setting});
15465: }
15466: # Determine if the array contents are the same.
15467: if ($stored_form ne $env{$envname}) {
15468: $SaveHash{$basename} = $stored_form;
15469: $AppHash{$envname} = $stored_form;
15470: }
15471: }
15472: }
15473: }
15474: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15475: $udom,$uname);
15476: if ($put_result !~ /^(ok|delayed)/) {
15477: &Apache::lonnet::logthis('unable to save form parameters, '.
15478: 'got error:'.$put_result);
15479: }
15480: # Make sure these settings stick around in this session, too
15481: &Apache::lonnet::appenv(\%AppHash);
15482: return;
15483: }
15484:
15485: sub restore_course_settings {
15486: return &restore_settings($env{'request.course.id'},@_);
15487: }
15488:
15489: sub restore_settings {
15490: my ($context,$prefix,$Settings) = @_;
15491: while (my ($setting,$type) = each(%$Settings)) {
15492: next if (exists($env{'form.'.$setting}));
15493: my $envname = 'environment.internal.'.$context.'.'.$prefix.
15494: '.'.$setting;
15495: if (exists($env{$envname})) {
15496: if ($type eq 'scalar') {
15497: $env{'form.'.$setting} = $env{$envname};
15498: } elsif ($type eq 'array') {
15499: $env{'form.'.$setting} = [
15500: map {
15501: &unescape($_);
15502: } split(',',$env{$envname})
15503: ];
15504: }
15505: }
15506: }
15507: }
15508:
15509: #######################################################
15510: #######################################################
15511:
15512: =pod
15513:
15514: =head1 Domain E-mail Routines
15515:
15516: =over 4
15517:
15518: =item * &build_recipient_list()
15519:
15520: Build recipient lists for following types of e-mail:
15521: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15522: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15523: module change checking, student/employee ID conflict checks, as
15524: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15525: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15526:
15527: Inputs:
15528: defmail (scalar - email address of default recipient),
15529: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15530: requestsmail, updatesmail, or idconflictsmail).
15531:
15532: defdom (domain for which to retrieve configuration settings),
15533:
15534: origmail (scalar - email address of recipient from loncapa.conf,
15535: i.e., predates configuration by DC via domainprefs.pm
15536:
15537: $requname username of requester (if mailing type is helpdeskmail)
15538:
15539: $requdom domain of requester (if mailing type is helpdeskmail)
15540:
15541: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15542:
15543:
15544: Returns: comma separated list of addresses to which to send e-mail.
15545:
15546: =back
15547:
15548: =cut
15549:
15550: ############################################################
15551: ############################################################
15552: sub build_recipient_list {
15553: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15554: my @recipients;
15555: my ($otheremails,$lastresort,$allbcc,$addtext);
15556: my %domconfig =
15557: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15558: if (ref($domconfig{'contacts'}) eq 'HASH') {
15559: if (exists($domconfig{'contacts'}{$mailing})) {
15560: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15561: my @contacts = ('adminemail','supportemail');
15562: foreach my $item (@contacts) {
15563: if ($domconfig{'contacts'}{$mailing}{$item}) {
15564: my $addr = $domconfig{'contacts'}{$item};
15565: if (!grep(/^\Q$addr\E$/,@recipients)) {
15566: push(@recipients,$addr);
15567: }
15568: }
15569: }
15570: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15571: if ($mailing eq 'helpdeskmail') {
15572: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15573: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15574: my @ok_bccs;
15575: foreach my $bcc (@bccs) {
15576: $bcc =~ s/^\s+//g;
15577: $bcc =~ s/\s+$//g;
15578: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15579: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15580: push(@ok_bccs,$bcc);
15581: }
15582: }
15583: }
15584: if (@ok_bccs > 0) {
15585: $allbcc = join(', ',@ok_bccs);
15586: }
15587: }
15588: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15589: }
15590: }
15591: } elsif ($origmail ne '') {
15592: $lastresort = $origmail;
15593: }
15594: if ($mailing eq 'helpdeskmail') {
15595: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15596: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15597: my ($inststatus,$inststatus_checked);
15598: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15599: ($env{'user.domain'} ne 'public')) {
15600: $inststatus_checked = 1;
15601: $inststatus = $env{'environment.inststatus'};
15602: }
15603: unless ($inststatus_checked) {
15604: if (($requname ne '') && ($requdom ne '')) {
15605: if (($requname =~ /^$match_username$/) &&
15606: ($requdom =~ /^$match_domain$/) &&
15607: (&Apache::lonnet::domain($requdom))) {
15608: my $requhome = &Apache::lonnet::homeserver($requname,
15609: $requdom);
15610: unless ($requhome eq 'no_host') {
15611: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15612: $inststatus = $userenv{'inststatus'};
15613: $inststatus_checked = 1;
15614: }
15615: }
15616: }
15617: }
15618: unless ($inststatus_checked) {
15619: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15620: my %srch = (srchby => 'email',
15621: srchdomain => $defdom,
15622: srchterm => $reqemail,
15623: srchtype => 'exact');
15624: my %srch_results = &Apache::lonnet::usersearch(\%srch);
15625: foreach my $uname (keys(%srch_results)) {
15626: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15627: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15628: $inststatus_checked = 1;
15629: last;
15630: }
15631: }
15632: unless ($inststatus_checked) {
15633: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15634: if ($dirsrchres eq 'ok') {
15635: foreach my $uname (keys(%srch_results)) {
15636: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15637: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15638: $inststatus_checked = 1;
15639: last;
15640: }
15641: }
15642: }
15643: }
15644: }
15645: }
15646: if ($inststatus ne '') {
15647: foreach my $status (split(/\:/,$inststatus)) {
15648: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15649: my @contacts = ('adminemail','supportemail');
15650: foreach my $item (@contacts) {
15651: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15652: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15653: if (!grep(/^\Q$addr\E$/,@recipients)) {
15654: push(@recipients,$addr);
15655: }
15656: }
15657: }
15658: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15659: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15660: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15661: my @ok_bccs;
15662: foreach my $bcc (@bccs) {
15663: $bcc =~ s/^\s+//g;
15664: $bcc =~ s/\s+$//g;
15665: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15666: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15667: push(@ok_bccs,$bcc);
15668: }
15669: }
15670: }
15671: if (@ok_bccs > 0) {
15672: $allbcc = join(', ',@ok_bccs);
15673: }
15674: }
15675: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15676: last;
15677: }
15678: }
15679: }
15680: }
15681: }
15682: } elsif ($origmail ne '') {
15683: $lastresort = $origmail;
15684: }
15685: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15686: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15687: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15688: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15689: my %what = (
15690: perlvar => 1,
15691: );
15692: my $primary = &Apache::lonnet::domain($defdom,'primary');
15693: if ($primary) {
15694: my $gotaddr;
15695: my ($result,$returnhash) =
15696: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15697: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15698: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15699: $lastresort = $returnhash->{'lonSupportEMail'};
15700: $gotaddr = 1;
15701: }
15702: }
15703: unless ($gotaddr) {
15704: my $uintdom = &Apache::lonnet::internet_dom($primary);
15705: my $intdom = &Apache::lonnet::internet_dom($lonhost);
15706: unless ($uintdom eq $intdom) {
15707: my %domconfig =
15708: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15709: if (ref($domconfig{'contacts'}) eq 'HASH') {
15710: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15711: my @contacts = ('adminemail','supportemail');
15712: foreach my $item (@contacts) {
15713: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15714: my $addr = $domconfig{'contacts'}{$item};
15715: if (!grep(/^\Q$addr\E$/,@recipients)) {
15716: push(@recipients,$addr);
15717: }
15718: }
15719: }
15720: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15721: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15722: }
15723: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15724: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15725: my @ok_bccs;
15726: foreach my $bcc (@bccs) {
15727: $bcc =~ s/^\s+//g;
15728: $bcc =~ s/\s+$//g;
15729: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15730: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15731: push(@ok_bccs,$bcc);
15732: }
15733: }
15734: }
15735: if (@ok_bccs > 0) {
15736: $allbcc = join(', ',@ok_bccs);
15737: }
15738: }
15739: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15740: }
15741: }
15742: }
15743: }
15744: }
15745: }
15746: }
15747: if (defined($defmail)) {
15748: if ($defmail ne '') {
15749: push(@recipients,$defmail);
15750: }
15751: }
15752: if ($otheremails) {
15753: my @others;
15754: if ($otheremails =~ /,/) {
15755: @others = split(/,/,$otheremails);
15756: } else {
15757: push(@others,$otheremails);
15758: }
15759: foreach my $addr (@others) {
15760: if (!grep(/^\Q$addr\E$/,@recipients)) {
15761: push(@recipients,$addr);
15762: }
15763: }
15764: }
15765: if ($mailing eq 'helpdeskmail') {
15766: if ((!@recipients) && ($lastresort ne '')) {
15767: push(@recipients,$lastresort);
15768: }
15769: } elsif ($lastresort ne '') {
15770: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15771: push(@recipients,$lastresort);
15772: }
15773: }
15774: my $recipientlist = join(',',@recipients);
15775: if (wantarray) {
15776: return ($recipientlist,$allbcc,$addtext);
15777: } else {
15778: return $recipientlist;
15779: }
15780: }
15781:
15782: ############################################################
15783: ############################################################
15784:
15785: =pod
15786:
15787: =over 4
15788:
15789: =item * &mime_email()
15790:
15791: Sends an email with a possible attachment
15792:
15793: Inputs:
15794:
15795: =over 4
15796:
15797: from - Sender's email address
15798:
15799: replyto - Reply-To email address
15800:
15801: to - Email address of recipient
15802:
15803: subject - Subject of email
15804:
15805: body - Body of email
15806:
15807: cc_string - Carbon copy email address
15808:
15809: bcc - Blind carbon copy email address
15810:
15811: attachment_path - Path of file to be attached
15812:
15813: file_name - Name of file to be attached
15814:
15815: attachment_text - The body of an attachment of type "TEXT"
15816:
15817: =back
15818:
15819: =back
15820:
15821: =cut
15822:
15823: ############################################################
15824: ############################################################
15825:
15826: sub mime_email {
15827: my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path,
15828: $file_name,$attachment_text) = @_;
15829:
15830: my $msg = MIME::Lite->new(
15831: From => $from,
15832: To => $to,
15833: Subject => $subject,
15834: Type =>'TEXT',
15835: Data => $body,
15836: );
15837: if ($replyto ne '') {
15838: $msg->add("Reply-To" => $replyto);
15839: }
15840: if ($cc_string ne '') {
15841: $msg->add("Cc" => $cc_string);
15842: }
15843: if ($bcc ne '') {
15844: $msg->add("Bcc" => $bcc);
15845: }
15846: $msg->attr("content-type" => "text/plain");
15847: $msg->attr("content-type.charset" => "UTF-8");
15848: # Attach file if given
15849: if ($attachment_path) {
15850: unless ($file_name) {
15851: if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15852: }
15853: my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15854: $msg->attach(Type => $type,
15855: Path => $attachment_path,
15856: Filename => $file_name
15857: );
15858: # Otherwise attach text if given
15859: } elsif ($attachment_text) {
15860: $msg->attach(Type => 'TEXT',
15861: Data => $attachment_text);
15862: }
15863: # Send it
15864: $msg->send('sendmail');
15865: }
15866:
15867: ############################################################
15868: ############################################################
15869:
15870: =pod
15871:
15872: =head1 Course Catalog Routines
15873:
15874: =over 4
15875:
15876: =item * &gather_categories()
15877:
15878: Converts category definitions - keys of categories hash stored in
15879: coursecategories in configuration.db on the primary library server in a
15880: domain - to an array. Also generates javascript and idx hash used to
15881: generate Domain Coordinator interface for editing Course Categories.
15882:
15883: Inputs:
15884:
15885: categories (reference to hash of category definitions).
15886:
15887: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15888: categories and subcategories).
15889:
15890: idx (reference to hash of counters used in Domain Coordinator interface for
15891: editing Course Categories).
15892:
15893: jsarray (reference to array of categories used to create Javascript arrays for
15894: Domain Coordinator interface for editing Course Categories).
15895:
15896: Returns: nothing
15897:
15898: Side effects: populates cats, idx and jsarray.
15899:
15900: =cut
15901:
15902: sub gather_categories {
15903: my ($categories,$cats,$idx,$jsarray) = @_;
15904: my %counters;
15905: my $num = 0;
15906: foreach my $item (keys(%{$categories})) {
15907: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15908: if ($container eq '' && $depth == 0) {
15909: $cats->[$depth][$categories->{$item}] = $cat;
15910: } else {
15911: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15912: }
15913: my ($escitem,$tail) = split(/:/,$item,2);
15914: if ($counters{$tail} eq '') {
15915: $counters{$tail} = $num;
15916: $num ++;
15917: }
15918: if (ref($idx) eq 'HASH') {
15919: $idx->{$item} = $counters{$tail};
15920: }
15921: if (ref($jsarray) eq 'ARRAY') {
15922: push(@{$jsarray->[$counters{$tail}]},$item);
15923: }
15924: }
15925: return;
15926: }
15927:
15928: =pod
15929:
15930: =item * &extract_categories()
15931:
15932: Used to generate breadcrumb trails for course categories.
15933:
15934: Inputs:
15935:
15936: categories (reference to hash of category definitions).
15937:
15938: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15939: categories and subcategories).
15940:
15941: trails (reference to array of breacrumb trails for each category).
15942:
15943: allitems (reference to hash - key is category key
15944: (format: escaped(name):escaped(parent category):depth in hierarchy).
15945:
15946: idx (reference to hash of counters used in Domain Coordinator interface for
15947: editing Course Categories).
15948:
15949: jsarray (reference to array of categories used to create Javascript arrays for
15950: Domain Coordinator interface for editing Course Categories).
15951:
15952: subcats (reference to hash of arrays containing all subcategories within each
15953: category, -recursive)
15954:
15955: maxd (reference to hash used to hold max depth for all top-level categories).
15956:
15957: Returns: nothing
15958:
15959: Side effects: populates trails and allitems hash references.
15960:
15961: =cut
15962:
15963: sub extract_categories {
15964: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15965: if (ref($categories) eq 'HASH') {
15966: &gather_categories($categories,$cats,$idx,$jsarray);
15967: if (ref($cats->[0]) eq 'ARRAY') {
15968: for (my $i=0; $i<@{$cats->[0]}; $i++) {
15969: my $name = $cats->[0][$i];
15970: my $item = &escape($name).'::0';
15971: my $trailstr;
15972: if ($name eq 'instcode') {
15973: $trailstr = &mt('Official courses (with institutional codes)');
15974: } elsif ($name eq 'communities') {
15975: $trailstr = &mt('Communities');
15976: } elsif ($name eq 'placement') {
15977: $trailstr = &mt('Placement Tests');
15978: } else {
15979: $trailstr = $name;
15980: }
15981: if ($allitems->{$item} eq '') {
15982: push(@{$trails},$trailstr);
15983: $allitems->{$item} = scalar(@{$trails})-1;
15984: }
15985: my @parents = ($name);
15986: if (ref($cats->[1]{$name}) eq 'ARRAY') {
15987: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15988: my $category = $cats->[1]{$name}[$j];
15989: if (ref($subcats) eq 'HASH') {
15990: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15991: }
15992: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15993: }
15994: } else {
15995: if (ref($subcats) eq 'HASH') {
15996: $subcats->{$item} = [];
15997: }
15998: if (ref($maxd) eq 'HASH') {
15999: $maxd->{$name} = 1;
16000: }
16001: }
16002: }
16003: }
16004: }
16005: return;
16006: }
16007:
16008: =pod
16009:
16010: =item * &recurse_categories()
16011:
16012: Recursively used to generate breadcrumb trails for course categories.
16013:
16014: Inputs:
16015:
16016: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16017: categories and subcategories).
16018:
16019: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16020:
16021: category (current course category, for which breadcrumb trail is being generated).
16022:
16023: trails (reference to array of breadcrumb trails for each category).
16024:
16025: allitems (reference to hash - key is category key
16026: (format: escaped(name):escaped(parent category):depth in hierarchy).
16027:
16028: parents (array containing containers directories for current category,
16029: back to top level).
16030:
16031: Returns: nothing
16032:
16033: Side effects: populates trails and allitems hash references
16034:
16035: =cut
16036:
16037: sub recurse_categories {
16038: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16039: my $shallower = $depth - 1;
16040: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16041: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16042: my $name = $cats->[$depth]{$category}[$k];
16043: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16044: my $trailstr = join(' » ',(@{$parents},$category));
16045: if ($allitems->{$item} eq '') {
16046: push(@{$trails},$trailstr);
16047: $allitems->{$item} = scalar(@{$trails})-1;
16048: }
16049: my $deeper = $depth+1;
16050: push(@{$parents},$category);
16051: if (ref($subcats) eq 'HASH') {
16052: my $subcat = &escape($name).':'.$category.':'.$depth;
16053: for (my $j=@{$parents}; $j>=0; $j--) {
16054: my $higher;
16055: if ($j > 0) {
16056: $higher = &escape($parents->[$j]).':'.
16057: &escape($parents->[$j-1]).':'.$j;
16058: } else {
16059: $higher = &escape($parents->[$j]).'::'.$j;
16060: }
16061: push(@{$subcats->{$higher}},$subcat);
16062: }
16063: }
16064: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16065: $subcats,$maxd);
16066: pop(@{$parents});
16067: }
16068: } else {
16069: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16070: my $trailstr = join(' » ',(@{$parents},$category));
16071: if ($allitems->{$item} eq '') {
16072: push(@{$trails},$trailstr);
16073: $allitems->{$item} = scalar(@{$trails})-1;
16074: }
16075: if (ref($maxd) eq 'HASH') {
16076: if ($depth > $maxd->{$parents->[0]}) {
16077: $maxd->{$parents->[0]} = $depth;
16078: }
16079: }
16080: }
16081: return;
16082: }
16083:
16084: =pod
16085:
16086: =item * &assign_categories_table()
16087:
16088: Create a datatable for display of hierarchical categories in a domain,
16089: with checkboxes to allow a course to be categorized.
16090:
16091: Inputs:
16092:
16093: cathash - reference to hash of categories defined for the domain (from
16094: configuration.db)
16095:
16096: currcat - scalar with an & separated list of categories assigned to a course.
16097:
16098: type - scalar contains course type (Course or Community).
16099:
16100: disabled - scalar (optional) contains disabled="disabled" if input elements are
16101: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16102:
16103: Returns: $output (markup to be displayed)
16104:
16105: =cut
16106:
16107: sub assign_categories_table {
16108: my ($cathash,$currcat,$type,$disabled) = @_;
16109: my $output;
16110: if (ref($cathash) eq 'HASH') {
16111: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16112: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16113: $maxdepth = scalar(@cats);
16114: if (@cats > 0) {
16115: my $itemcount = 0;
16116: if (ref($cats[0]) eq 'ARRAY') {
16117: my @currcategories;
16118: if ($currcat ne '') {
16119: @currcategories = split('&',$currcat);
16120: }
16121: my $table;
16122: for (my $i=0; $i<@{$cats[0]}; $i++) {
16123: my $parent = $cats[0][$i];
16124: next if ($parent eq 'instcode');
16125: if ($type eq 'Community') {
16126: next unless ($parent eq 'communities');
16127: } elsif ($type eq 'Placement') {
16128: next unless ($parent eq 'placement');
16129: } else {
16130: next if (($parent eq 'communities') || ($parent eq 'placement'));
16131: }
16132: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16133: my $item = &escape($parent).'::0';
16134: my $checked = '';
16135: if (@currcategories > 0) {
16136: if (grep(/^\Q$item\E$/,@currcategories)) {
16137: $checked = ' checked="checked"';
16138: }
16139: }
16140: my $parent_title = $parent;
16141: if ($parent eq 'communities') {
16142: $parent_title = &mt('Communities');
16143: } elsif ($parent eq 'placement') {
16144: $parent_title = &mt('Placement Tests');
16145: }
16146: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16147: '<input type="checkbox" name="usecategory" value="'.
16148: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16149: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16150: my $depth = 1;
16151: push(@path,$parent);
16152: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16153: pop(@path);
16154: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16155: $itemcount ++;
16156: }
16157: if ($itemcount) {
16158: $output = &Apache::loncommon::start_data_table().
16159: $table.
16160: &Apache::loncommon::end_data_table();
16161: }
16162: }
16163: }
16164: }
16165: return $output;
16166: }
16167:
16168: =pod
16169:
16170: =item * &assign_category_rows()
16171:
16172: Create a datatable row for display of nested categories in a domain,
16173: with checkboxes to allow a course to be categorized,called recursively.
16174:
16175: Inputs:
16176:
16177: itemcount - track row number for alternating colors
16178:
16179: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16180: categories and subcategories.
16181:
16182: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16183:
16184: parent - parent of current category item
16185:
16186: path - Array containing all categories back up through the hierarchy from the
16187: current category to the top level.
16188:
16189: currcategories - reference to array of current categories assigned to the course
16190:
16191: disabled - scalar (optional) contains disabled="disabled" if input elements are
16192: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16193:
16194: Returns: $output (markup to be displayed).
16195:
16196: =cut
16197:
16198: sub assign_category_rows {
16199: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16200: my ($text,$name,$item,$chgstr);
16201: if (ref($cats) eq 'ARRAY') {
16202: my $maxdepth = scalar(@{$cats});
16203: if (ref($cats->[$depth]) eq 'HASH') {
16204: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16205: my $numchildren = @{$cats->[$depth]{$parent}};
16206: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16207: $text .= '<td><table class="LC_data_table">';
16208: for (my $j=0; $j<$numchildren; $j++) {
16209: $name = $cats->[$depth]{$parent}[$j];
16210: $item = &escape($name).':'.&escape($parent).':'.$depth;
16211: my $deeper = $depth+1;
16212: my $checked = '';
16213: if (ref($currcategories) eq 'ARRAY') {
16214: if (@{$currcategories} > 0) {
16215: if (grep(/^\Q$item\E$/,@{$currcategories})) {
16216: $checked = ' checked="checked"';
16217: }
16218: }
16219: }
16220: $text .= '<tr><td><span class="LC_nobreak"><label>'.
16221: '<input type="checkbox" name="usecategory" value="'.
16222: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16223: '<input type="hidden" name="catname" value="'.$name.'" />'.
16224: '</td><td>';
16225: if (ref($path) eq 'ARRAY') {
16226: push(@{$path},$name);
16227: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16228: pop(@{$path});
16229: }
16230: $text .= '</td></tr>';
16231: }
16232: $text .= '</table></td>';
16233: }
16234: }
16235: }
16236: return $text;
16237: }
16238:
16239: =pod
16240:
16241: =back
16242:
16243: =cut
16244:
16245: ############################################################
16246: ############################################################
16247:
16248:
16249: sub commit_customrole {
16250: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
16251: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16252: ($start?', '.&mt('starting').' '.localtime($start):'').
16253: ($end?', ending '.localtime($end):'').': <b>'.
16254: &Apache::lonnet::assigncustomrole(
16255: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
16256: '</b><br />';
16257: return $output;
16258: }
16259:
16260: sub commit_standardrole {
16261: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
16262: my ($output,$logmsg,$linefeed);
16263: if ($context eq 'auto') {
16264: $linefeed = "\n";
16265: } else {
16266: $linefeed = "<br />\n";
16267: }
16268: if ($three eq 'st') {
16269: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16270: $one,$two,$sec,$context,$credits);
16271: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
16272: ($result eq 'unknown_course') || ($result eq 'refused')) {
16273: $output = $logmsg.' '.&mt('Error: ').$result."\n";
16274: } else {
16275: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16276: ($start?', '.&mt('starting').' '.localtime($start):'').
16277: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16278: if ($context eq 'auto') {
16279: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16280: } else {
16281: $output .= '<b>'.$result.'</b>'.$linefeed.
16282: &mt('Add to classlist').': <b>ok</b>';
16283: }
16284: $output .= $linefeed;
16285: }
16286: } else {
16287: $output = &mt('Assigning').' '.$three.' in '.$url.
16288: ($start?', '.&mt('starting').' '.localtime($start):'').
16289: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16290: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
16291: if ($context eq 'auto') {
16292: $output .= $result.$linefeed;
16293: } else {
16294: $output .= '<b>'.$result.'</b>'.$linefeed;
16295: }
16296: }
16297: return $output;
16298: }
16299:
16300: sub commit_studentrole {
16301: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16302: $credits) = @_;
16303: my ($result,$linefeed,$oldsecurl,$newsecurl);
16304: if ($context eq 'auto') {
16305: $linefeed = "\n";
16306: } else {
16307: $linefeed = '<br />'."\n";
16308: }
16309: if (defined($one) && defined($two)) {
16310: my $cid=$one.'_'.$two;
16311: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16312: my $secchange = 0;
16313: my $expire_role_result;
16314: my $modify_section_result;
16315: if ($oldsec ne '-1') {
16316: if ($oldsec ne $sec) {
16317: $secchange = 1;
16318: my $now = time;
16319: my $uurl='/'.$cid;
16320: $uurl=~s/\_/\//g;
16321: if ($oldsec) {
16322: $uurl.='/'.$oldsec;
16323: }
16324: $oldsecurl = $uurl;
16325: $expire_role_result =
16326: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
16327: if ($env{'request.course.sec'} ne '') {
16328: if ($expire_role_result eq 'refused') {
16329: my @roles = ('st');
16330: my @statuses = ('previous');
16331: my @roledoms = ($one);
16332: my $withsec = 1;
16333: my %roleshash =
16334: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16335: \@statuses,\@roles,\@roledoms,$withsec);
16336: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16337: my ($oldstart,$oldend) =
16338: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16339: if ($oldend > 0 && $oldend <= $now) {
16340: $expire_role_result = 'ok';
16341: }
16342: }
16343: }
16344: }
16345: $result = $expire_role_result;
16346: }
16347: }
16348: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16349: $modify_section_result =
16350: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16351: undef,undef,undef,$sec,
16352: $end,$start,'','',$cid,
16353: '',$context,$credits);
16354: if ($modify_section_result =~ /^ok/) {
16355: if ($secchange == 1) {
16356: if ($sec eq '') {
16357: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16358: } else {
16359: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16360: }
16361: } elsif ($oldsec eq '-1') {
16362: if ($sec eq '') {
16363: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16364: } else {
16365: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16366: }
16367: } else {
16368: if ($sec eq '') {
16369: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16370: } else {
16371: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16372: }
16373: }
16374: } else {
16375: if ($secchange) {
16376: $$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;
16377: } else {
16378: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16379: }
16380: }
16381: $result = $modify_section_result;
16382: } elsif ($secchange == 1) {
16383: if ($oldsec eq '') {
16384: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16385: } else {
16386: $$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;
16387: }
16388: if ($expire_role_result eq 'refused') {
16389: my $newsecurl = '/'.$cid;
16390: $newsecurl =~ s/\_/\//g;
16391: if ($sec ne '') {
16392: $newsecurl.='/'.$sec;
16393: }
16394: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16395: if ($sec eq '') {
16396: $$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;
16397: } else {
16398: $$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;
16399: }
16400: }
16401: }
16402: }
16403: } else {
16404: $$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;
16405: $result = "error: incomplete course id\n";
16406: }
16407: return $result;
16408: }
16409:
16410: sub show_role_extent {
16411: my ($scope,$context,$role) = @_;
16412: $scope =~ s{^/}{};
16413: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16414: push(@courseroles,'co');
16415: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16416: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16417: $scope =~ s{/}{_};
16418: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16419: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16420: my ($audom,$auname) = split(/\//,$scope);
16421: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16422: &Apache::loncommon::plainname($auname,$audom).'</span>');
16423: } else {
16424: $scope =~ s{/$}{};
16425: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16426: &Apache::lonnet::domain($scope,'description').'</span>');
16427: }
16428: }
16429:
16430: ############################################################
16431: ############################################################
16432:
16433: sub check_clone {
16434: my ($args,$linefeed) = @_;
16435: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16436: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16437: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16438: my $clonetitle;
16439: my @clonemsg;
16440: my $can_clone = 0;
16441: my $lctype = lc($args->{'crstype'});
16442: if ($lctype ne 'community') {
16443: $lctype = 'course';
16444: }
16445: if ($clonehome eq 'no_host') {
16446: if ($args->{'crstype'} eq 'Community') {
16447: push(@clonemsg,({
16448: mt => 'No new community created.',
16449: args => [],
16450: },
16451: {
16452: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16453: args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16454: }));
16455: } else {
16456: push(@clonemsg,({
16457: mt => 'No new course created.',
16458: args => [],
16459: },
16460: {
16461: mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16462: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16463: }));
16464: }
16465: } else {
16466: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16467: $clonetitle = $clonedesc{'description'};
16468: if ($args->{'crstype'} eq 'Community') {
16469: if ($clonedesc{'type'} ne 'Community') {
16470: push(@clonemsg,({
16471: mt => 'No new community created.',
16472: args => [],
16473: },
16474: {
16475: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16476: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16477: }));
16478: return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16479: }
16480: }
16481: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16482: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16483: $can_clone = 1;
16484: } else {
16485: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16486: $args->{'clonedomain'},$args->{'clonecourse'});
16487: if ($clonehash{'cloners'} eq '') {
16488: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16489: if ($domdefs{'canclone'}) {
16490: unless ($domdefs{'canclone'} eq 'none') {
16491: if ($domdefs{'canclone'} eq 'domain') {
16492: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16493: $can_clone = 1;
16494: }
16495: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16496: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16497: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16498: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16499: $can_clone = 1;
16500: }
16501: }
16502: }
16503: }
16504: } else {
16505: my @cloners = split(/,/,$clonehash{'cloners'});
16506: if (grep(/^\*$/,@cloners)) {
16507: $can_clone = 1;
16508: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16509: $can_clone = 1;
16510: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16511: $can_clone = 1;
16512: }
16513: unless ($can_clone) {
16514: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16515: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16516: my (%gotdomdefaults,%gotcodedefaults);
16517: foreach my $cloner (@cloners) {
16518: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16519: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16520: my (%codedefaults,@code_order);
16521: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16522: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16523: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16524: }
16525: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16526: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16527: }
16528: } else {
16529: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16530: \%codedefaults,
16531: \@code_order);
16532: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16533: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16534: }
16535: if (@code_order > 0) {
16536: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16537: $cloner,$clonehash{'internal.coursecode'},
16538: $args->{'crscode'})) {
16539: $can_clone = 1;
16540: last;
16541: }
16542: }
16543: }
16544: }
16545: }
16546: }
16547: }
16548: unless ($can_clone) {
16549: my $ccrole = 'cc';
16550: if ($args->{'crstype'} eq 'Community') {
16551: $ccrole = 'co';
16552: }
16553: my %roleshash =
16554: &Apache::lonnet::get_my_roles($args->{'ccuname'},
16555: $args->{'ccdomain'},
16556: 'userroles',['active'],[$ccrole],
16557: [$args->{'clonedomain'}]);
16558: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16559: $can_clone = 1;
16560: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16561: $args->{'ccuname'},$args->{'ccdomain'})) {
16562: $can_clone = 1;
16563: }
16564: }
16565: unless ($can_clone) {
16566: if ($args->{'crstype'} eq 'Community') {
16567: push(@clonemsg,({
16568: mt => 'No new community created.',
16569: args => [],
16570: },
16571: {
16572: 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]).',
16573: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16574: }));
16575: } else {
16576: push(@clonemsg,({
16577: mt => 'No new course created.',
16578: args => [],
16579: },
16580: {
16581: 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]).',
16582: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16583: }));
16584: }
16585: }
16586: }
16587: }
16588: return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16589: }
16590:
16591: sub construct_course {
16592: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16593: $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16594: my ($outcome,$msgref,$clonemsgref);
16595: my $linefeed = '<br />'."\n";
16596: if ($context eq 'auto') {
16597: $linefeed = "\n";
16598: }
16599:
16600: #
16601: # Are we cloning?
16602: #
16603: my ($can_clone,$cloneid,$clonehome,$clonetitle);
16604: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16605: ($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16606: if (!$can_clone) {
16607: return (0,$outcome,$clonemsgref);
16608: }
16609: }
16610:
16611: #
16612: # Open course
16613: #
16614: my $showncrstype;
16615: if ($args->{'crstype'} eq 'Placement') {
16616: $showncrstype = 'placement test';
16617: } else {
16618: $showncrstype = lc($args->{'crstype'});
16619: }
16620: my %cenv=();
16621: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16622: $args->{'cdescr'},
16623: $args->{'curl'},
16624: $args->{'course_home'},
16625: $args->{'nonstandard'},
16626: $args->{'crscode'},
16627: $args->{'ccuname'}.':'.
16628: $args->{'ccdomain'},
16629: $args->{'crstype'},
16630: $cnum,$context,$category,
16631: $callercontext);
16632:
16633: # Note: The testing routines depend on this being output; see
16634: # Utils::Course. This needs to at least be output as a comment
16635: # if anyone ever decides to not show this, and Utils::Course::new
16636: # will need to be suitably modified.
16637: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16638: $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16639: } else {
16640: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16641: }
16642: if ($$courseid =~ /^error:/) {
16643: return (0,$outcome,$clonemsgref);
16644: }
16645:
16646: #
16647: # Check if created correctly
16648: #
16649: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16650: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16651: if ($crsuhome eq 'no_host') {
16652: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16653: $outcome .= &mt_user($user_lh,
16654: 'Course creation failed, unrecognized course home server.');
16655: } else {
16656: $outcome .= &mt('Course creation failed, unrecognized course home server.');
16657: }
16658: $outcome .= $linefeed;
16659: return (0,$outcome,$clonemsgref);
16660: }
16661: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16662:
16663: #
16664: # Do the cloning
16665: #
16666: my @clonemsg;
16667: if ($can_clone && $cloneid) {
16668: push(@clonemsg,
16669: {
16670: mt => 'Created [_1] by cloning from [_2]',
16671: args => [$showncrstype,$clonetitle],
16672: });
16673: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16674: # Copy all files
16675: my @info =
16676: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16677: $args->{'dateshift'},$args->{'crscode'},
16678: $args->{'ccuname'}.':'.$args->{'ccdomain'},
16679: $args->{'tinyurls'});
16680: if (@info) {
16681: push(@clonemsg,@info);
16682: }
16683: # Restore URL
16684: $cenv{'url'}=$oldcenv{'url'};
16685: # Restore title
16686: $cenv{'description'}=$oldcenv{'description'};
16687: # Restore creation date, creator and creation context.
16688: $cenv{'internal.created'}=$oldcenv{'internal.created'};
16689: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16690: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16691: # Mark as cloned
16692: $cenv{'clonedfrom'}=$cloneid;
16693: # Need to clone grading mode
16694: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16695: $cenv{'grading'}=$newenv{'grading'};
16696: # Do not clone these environment entries
16697: &Apache::lonnet::del('environment',
16698: ['default_enrollment_start_date',
16699: 'default_enrollment_end_date',
16700: 'question.email',
16701: 'policy.email',
16702: 'comment.email',
16703: 'pch.users.denied',
16704: 'plc.users.denied',
16705: 'hidefromcat',
16706: 'checkforpriv',
16707: 'categories'],
16708: $$crsudom,$$crsunum);
16709: if ($args->{'textbook'}) {
16710: $cenv{'internal.textbook'} = $args->{'textbook'};
16711: }
16712: }
16713:
16714: #
16715: # Set environment (will override cloned, if existing)
16716: #
16717: my @sections = ();
16718: my @xlists = ();
16719: if ($args->{'crstype'}) {
16720: $cenv{'type'}=$args->{'crstype'};
16721: }
16722: if ($args->{'lti'}) {
16723: $cenv{'internal.lti'}=$args->{'lti'};
16724: }
16725: if ($args->{'crsid'}) {
16726: $cenv{'courseid'}=$args->{'crsid'};
16727: }
16728: if ($args->{'crscode'}) {
16729: $cenv{'internal.coursecode'}=$args->{'crscode'};
16730: }
16731: if ($args->{'crsquota'} ne '') {
16732: $cenv{'internal.coursequota'}=$args->{'crsquota'};
16733: } else {
16734: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16735: }
16736: if ($args->{'ccuname'}) {
16737: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16738: ':'.$args->{'ccdomain'};
16739: } else {
16740: $cenv{'internal.courseowner'} = $args->{'curruser'};
16741: }
16742: if ($args->{'defaultcredits'}) {
16743: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16744: }
16745: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16746: if ($args->{'crssections'}) {
16747: $cenv{'internal.sectionnums'} = '';
16748: if ($args->{'crssections'} =~ m/,/) {
16749: @sections = split/,/,$args->{'crssections'};
16750: } else {
16751: $sections[0] = $args->{'crssections'};
16752: }
16753: if (@sections > 0) {
16754: foreach my $item (@sections) {
16755: my ($sec,$gp) = split/:/,$item;
16756: my $class = $args->{'crscode'}.$sec;
16757: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16758: $cenv{'internal.sectionnums'} .= $item.',';
16759: unless ($addcheck eq 'ok') {
16760: push(@badclasses,$class);
16761: }
16762: }
16763: $cenv{'internal.sectionnums'} =~ s/,$//;
16764: }
16765: }
16766: # do not hide course coordinator from staff listing,
16767: # even if privileged
16768: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16769: # add course coordinator's domain to domains to check for privileged users
16770: # if different to course domain
16771: if ($$crsudom ne $args->{'ccdomain'}) {
16772: $cenv{'checkforpriv'} = $args->{'ccdomain'};
16773: }
16774: # add crosslistings
16775: if ($args->{'crsxlist'}) {
16776: $cenv{'internal.crosslistings'}='';
16777: if ($args->{'crsxlist'} =~ m/,/) {
16778: @xlists = split/,/,$args->{'crsxlist'};
16779: } else {
16780: $xlists[0] = $args->{'crsxlist'};
16781: }
16782: if (@xlists > 0) {
16783: foreach my $item (@xlists) {
16784: my ($xl,$gp) = split/:/,$item;
16785: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16786: $cenv{'internal.crosslistings'} .= $item.',';
16787: unless ($addcheck eq 'ok') {
16788: push(@badclasses,$xl);
16789: }
16790: }
16791: $cenv{'internal.crosslistings'} =~ s/,$//;
16792: }
16793: }
16794: if ($args->{'autoadds'}) {
16795: $cenv{'internal.autoadds'}=$args->{'autoadds'};
16796: }
16797: if ($args->{'autodrops'}) {
16798: $cenv{'internal.autodrops'}=$args->{'autodrops'};
16799: }
16800: # check for notification of enrollment changes
16801: my @notified = ();
16802: if ($args->{'notify_owner'}) {
16803: if ($args->{'ccuname'} ne '') {
16804: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16805: }
16806: }
16807: if ($args->{'notify_dc'}) {
16808: if ($uname ne '') {
16809: push(@notified,$uname.':'.$udom);
16810: }
16811: }
16812: if (@notified > 0) {
16813: my $notifylist;
16814: if (@notified > 1) {
16815: $notifylist = join(',',@notified);
16816: } else {
16817: $notifylist = $notified[0];
16818: }
16819: $cenv{'internal.notifylist'} = $notifylist;
16820: }
16821: if (@badclasses > 0) {
16822: my %lt=&Apache::lonlocal::texthash(
16823: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16824: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16825: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16826: );
16827: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16828: &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'};
16829: if ($context eq 'auto') {
16830: $outcome .= $badclass_msg.$linefeed;
16831: } else {
16832: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16833: }
16834: foreach my $item (@badclasses) {
16835: if ($context eq 'auto') {
16836: $outcome .= " - $item\n";
16837: } else {
16838: $outcome .= "<li>$item</li>\n";
16839: }
16840: }
16841: if ($context eq 'auto') {
16842: $outcome .= $linefeed;
16843: } else {
16844: $outcome .= "</ul><br /><br /></div>\n";
16845: }
16846: }
16847: if ($args->{'no_end_date'}) {
16848: $args->{'endaccess'} = 0;
16849: }
16850: $cenv{'internal.autostart'}=$args->{'enrollstart'};
16851: $cenv{'internal.autoend'}=$args->{'enrollend'};
16852: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16853: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16854: if ($args->{'showphotos'}) {
16855: $cenv{'internal.showphotos'}=$args->{'showphotos'};
16856: }
16857: $cenv{'internal.authtype'} = $args->{'authtype'};
16858: $cenv{'internal.autharg'} = $args->{'autharg'};
16859: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16860: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
16861: 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');
16862: if ($context eq 'auto') {
16863: $outcome .= $krb_msg;
16864: } else {
16865: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16866: }
16867: $outcome .= $linefeed;
16868: }
16869: }
16870: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16871: if ($args->{'setpolicy'}) {
16872: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16873: }
16874: if ($args->{'setcontent'}) {
16875: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16876: }
16877: if ($args->{'setcomment'}) {
16878: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16879: }
16880: }
16881: if ($args->{'reshome'}) {
16882: $cenv{'reshome'}=$args->{'reshome'}.'/';
16883: $cenv{'reshome'}=~s/\/+$/\//;
16884: }
16885: #
16886: # course has keyed access
16887: #
16888: if ($args->{'setkeys'}) {
16889: $cenv{'keyaccess'}='yes';
16890: }
16891: # if specified, key authority is not course, but user
16892: # only active if keyaccess is yes
16893: if ($args->{'keyauth'}) {
16894: my ($user,$domain) = split(':',$args->{'keyauth'});
16895: $user = &LONCAPA::clean_username($user);
16896: $domain = &LONCAPA::clean_username($domain);
16897: if ($user ne '' && $domain ne '') {
16898: $cenv{'keyauth'}=$user.':'.$domain;
16899: }
16900: }
16901:
16902: #
16903: # generate and store uniquecode (available to course requester), if course should have one.
16904: #
16905: if ($args->{'uniquecode'}) {
16906: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16907: if ($code) {
16908: $cenv{'internal.uniquecode'} = $code;
16909: my %crsinfo =
16910: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16911: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16912: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16913: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16914: }
16915: if (ref($coderef)) {
16916: $$coderef = $code;
16917: }
16918: }
16919: }
16920:
16921: if ($args->{'disresdis'}) {
16922: $cenv{'pch.roles.denied'}='st';
16923: }
16924: if ($args->{'disablechat'}) {
16925: $cenv{'plc.roles.denied'}='st';
16926: }
16927:
16928: # Record we've not yet viewed the Course Initialization Helper for this
16929: # course
16930: $cenv{'course.helper.not.run'} = 1;
16931: #
16932: # Use new Randomseed
16933: #
16934: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16935: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16936: #
16937: # The encryption code and receipt prefix for this course
16938: #
16939: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16940: $cenv{'internal.encpref'}=100+int(9*rand(99));
16941: #
16942: # By default, use standard grading
16943: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16944:
16945: $outcome .= $linefeed.&mt('Setting environment').': '.
16946: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16947: #
16948: # Open all assignments
16949: #
16950: if ($args->{'openall'}) {
16951: my $opendate = time;
16952: if ($args->{'openallfrom'} =~ /^\d+$/) {
16953: $opendate = $args->{'openallfrom'};
16954: }
16955: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16956: my %storecontent = ($storeunder => $opendate,
16957: $storeunder.'.type' => 'date_start');
16958: $outcome .= &mt('All assignments open starting [_1]',
16959: &Apache::lonlocal::locallocaltime($opendate)).': '.
16960: &Apache::lonnet::cput
16961: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16962: }
16963: #
16964: # Set first page
16965: #
16966: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16967: || ($cloneid)) {
16968: use LONCAPA::map;
16969: $outcome .= &mt('Setting first resource').': ';
16970:
16971: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16972: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16973:
16974: $outcome .= ($fatal?$errtext:'read ok').' - ';
16975: my $title; my $url;
16976: if ($args->{'firstres'} eq 'syl') {
16977: $title=&mt('Syllabus');
16978: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16979: } else {
16980: $title=&mt('Table of Contents');
16981: $url='/adm/navmaps';
16982: }
16983:
16984: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16985: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16986:
16987: if ($errtext) { $fatal=2; }
16988: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16989: }
16990:
16991: #
16992: # Set params for Placement Tests
16993: #
16994: if ($args->{'crstype'} eq 'Placement') {
16995: my %storecontent;
16996: my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16997: my %defaults = (
16998: buttonshide => { value => 'yes',
16999: type => 'string_yesno',},
17000: type => { value => 'randomizetry',
17001: type => 'string_questiontype',},
17002: maxtries => { value => 1,
17003: type => 'int_pos',},
17004: problemstatus => { value => 'no',
17005: type => 'string_problemstatus',},
17006: );
17007: foreach my $key (keys(%defaults)) {
17008: $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17009: $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17010: }
17011: &Apache::lonnet::cput
17012: ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
17013: }
17014:
17015: return (1,$outcome,\@clonemsg);
17016: }
17017:
17018: sub make_unique_code {
17019: my ($cdom,$cnum) = @_;
17020: # get lock on uniquecodes db
17021: my $lockhash = {
17022: $cnum."\0".'uniquecodes' => $env{'user.name'}.
17023: ':'.$env{'user.domain'},
17024: };
17025: my $tries = 0;
17026: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17027: my ($code,$error);
17028:
17029: while (($gotlock ne 'ok') && ($tries<3)) {
17030: $tries ++;
17031: sleep 1;
17032: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17033: }
17034: if ($gotlock eq 'ok') {
17035: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17036: my $gotcode;
17037: my $attempts = 0;
17038: while ((!$gotcode) && ($attempts < 100)) {
17039: $code = &generate_code();
17040: if (!exists($currcodes{$code})) {
17041: $gotcode = 1;
17042: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17043: $error = 'nostore';
17044: }
17045: }
17046: $attempts ++;
17047: }
17048: my @del_lock = ($cnum."\0".'uniquecodes');
17049: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17050: } else {
17051: $error = 'nolock';
17052: }
17053: return ($code,$error);
17054: }
17055:
17056: sub generate_code {
17057: my $code;
17058: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17059: for (my $i=0; $i<6; $i++) {
17060: my $lettnum = int (rand 2);
17061: my $item = '';
17062: if ($lettnum) {
17063: $item = $letts[int( rand(18) )];
17064: } else {
17065: $item = 1+int( rand(8) );
17066: }
17067: $code .= $item;
17068: }
17069: return $code;
17070: }
17071:
17072: ############################################################
17073: ############################################################
17074:
17075: # Community, Course and Placement Test
17076: sub course_type {
17077: my ($cid) = @_;
17078: if (!defined($cid)) {
17079: $cid = $env{'request.course.id'};
17080: }
17081: if (defined($env{'course.'.$cid.'.type'})) {
17082: return $env{'course.'.$cid.'.type'};
17083: } else {
17084: return 'Course';
17085: }
17086: }
17087:
17088: sub group_term {
17089: my $crstype = &course_type();
17090: my %names = (
17091: 'Course' => 'group',
17092: 'Community' => 'group',
17093: 'Placement' => 'group',
17094: );
17095: return $names{$crstype};
17096: }
17097:
17098: sub course_types {
17099: my @types = ('official','unofficial','community','textbook','placement','lti');
17100: my %typename = (
17101: official => 'Official course',
17102: unofficial => 'Unofficial course',
17103: community => 'Community',
17104: textbook => 'Textbook course',
17105: placement => 'Placement test',
17106: lti => 'LTI provider',
17107: );
17108: return (\@types,\%typename);
17109: }
17110:
17111: sub icon {
17112: my ($file)=@_;
17113: my $curfext = lc((split(/\./,$file))[-1]);
17114: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17115: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17116: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17117: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17118: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17119: $curfext.".gif") {
17120: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17121: $curfext.".gif";
17122: }
17123: }
17124: return &lonhttpdurl($iconname);
17125: }
17126:
17127: sub lonhttpdurl {
17128: #
17129: # Had been used for "small fry" static images on separate port 8080.
17130: # Modify here if lightweight http functionality desired again.
17131: # Currently eliminated due to increasing firewall issues.
17132: #
17133: my ($url)=@_;
17134: return $url;
17135: }
17136:
17137: sub connection_aborted {
17138: my ($r)=@_;
17139: $r->print(" ");$r->rflush();
17140: my $c = $r->connection;
17141: return $c->aborted();
17142: }
17143:
17144: # Escapes strings that may have embedded 's that will be put into
17145: # strings as 'strings'.
17146: sub escape_single {
17147: my ($input) = @_;
17148: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
17149: $input =~ s/\'/\\\'/g; # Esacpe the 's....
17150: return $input;
17151: }
17152:
17153: # Same as escape_single, but escape's "'s This
17154: # can be used for "strings"
17155: sub escape_double {
17156: my ($input) = @_;
17157: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
17158: $input =~ s/\"/\\\"/g; # Esacpe the "s....
17159: return $input;
17160: }
17161:
17162: # Escapes the last element of a full URL.
17163: sub escape_url {
17164: my ($url) = @_;
17165: my @urlslices = split(/\//, $url,-1);
17166: my $lastitem = &escape(pop(@urlslices));
17167: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17168: }
17169:
17170: sub compare_arrays {
17171: my ($arrayref1,$arrayref2) = @_;
17172: my (@difference,%count);
17173: @difference = ();
17174: %count = ();
17175: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17176: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17177: foreach my $element (keys(%count)) {
17178: if ($count{$element} == 1) {
17179: push(@difference,$element);
17180: }
17181: }
17182: }
17183: return @difference;
17184: }
17185:
17186: sub lon_status_items {
17187: my %defaults = (
17188: E => 100,
17189: W => 4,
17190: N => 1,
17191: U => 5,
17192: threshold => 200,
17193: sysmail => 2500,
17194: );
17195: my %names = (
17196: E => 'Errors',
17197: W => 'Warnings',
17198: N => 'Notices',
17199: U => 'Unsent',
17200: );
17201: return (\%defaults,\%names);
17202: }
17203:
17204: # -------------------------------------------------------- Initialize user login
17205: sub init_user_environment {
17206: my ($r, $username, $domain, $authhost, $form, $args) = @_;
17207: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17208:
17209: my $public=($username eq 'public' && $domain eq 'public');
17210:
17211: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
17212: my $now=time;
17213:
17214: if ($public) {
17215: my $max_public=100;
17216: my $oldest;
17217: my $oldest_time=0;
17218: for(my $next=1;$next<=$max_public;$next++) {
17219: if (-e $lonids."/publicuser_$next.id") {
17220: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17221: if ($mtime<$oldest_time || !$oldest_time) {
17222: $oldest_time=$mtime;
17223: $oldest=$next;
17224: }
17225: } else {
17226: $cookie="publicuser_$next";
17227: last;
17228: }
17229: }
17230: if (!$cookie) { $cookie="publicuser_$oldest"; }
17231: } else {
17232: # See if old ID present, if so, remove if this isn't a robot,
17233: # killing any existing non-robot sessions
17234: if (!$args->{'robot'}) {
17235: opendir(DIR,$lonids);
17236: while ($filename=readdir(DIR)) {
17237: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17238: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17239: &GDBM_READER(),0640)) {
17240: my $linkedfile;
17241: if (exists($oldenv{'user.linkedenv'})) {
17242: $linkedfile = $oldenv{'user.linkedenv'};
17243: }
17244: untie(%oldenv);
17245: if (unlink("$lonids/$filename")) {
17246: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17247: if (-l "$lonids/$linkedfile.id") {
17248: unlink("$lonids/$linkedfile.id");
17249: }
17250: }
17251: }
17252: } else {
17253: unlink($lonids.'/'.$filename);
17254: }
17255: }
17256: }
17257: closedir(DIR);
17258: # If there is a undeleted lockfile for the user's paste buffer remove it.
17259: my $namespace = 'nohist_courseeditor';
17260: my $lockingkey = 'paste'."\0".'locked_num';
17261: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17262: $domain,$username);
17263: if (exists($lockhash{$lockingkey})) {
17264: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17265: unless ($delresult eq 'ok') {
17266: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17267: }
17268: }
17269: }
17270: # Give them a new cookie
17271: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17272: : $now.$$.int(rand(10000)));
17273: $cookie="$username\_$id\_$domain\_$authhost";
17274:
17275: # Initialize roles
17276:
17277: ($userroles,$firstaccenv,$timerintenv) =
17278: &Apache::lonnet::rolesinit($domain,$username,$authhost);
17279: }
17280: # ------------------------------------ Check browser type and MathML capability
17281:
17282: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17283: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17284:
17285: # ------------------------------------------------------------- Get environment
17286:
17287: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17288: my ($tmp) = keys(%userenv);
17289: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17290: undef(%userenv);
17291: }
17292: if (($userenv{'interface'}) && (!$form->{'interface'})) {
17293: $form->{'interface'}=$userenv{'interface'};
17294: }
17295: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17296:
17297: # --------------- Do not trust query string to be put directly into environment
17298: foreach my $option ('interface','localpath','localres') {
17299: $form->{$option}=~s/[\n\r\=]//gs;
17300: }
17301: # --------------------------------------------------------- Write first profile
17302:
17303: {
17304: my $ip = &Apache::lonnet::get_requestor_ip($r);
17305: my %initial_env =
17306: ("user.name" => $username,
17307: "user.domain" => $domain,
17308: "user.home" => $authhost,
17309: "browser.type" => $clientbrowser,
17310: "browser.version" => $clientversion,
17311: "browser.mathml" => $clientmathml,
17312: "browser.unicode" => $clientunicode,
17313: "browser.os" => $clientos,
17314: "browser.mobile" => $clientmobile,
17315: "browser.info" => $clientinfo,
17316: "browser.osversion" => $clientosversion,
17317: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
17318: "request.course.fn" => '',
17319: "request.course.uri" => '',
17320: "request.course.sec" => '',
17321: "request.role" => 'cm',
17322: "request.role.adv" => $env{'user.adv'},
17323: "request.host" => $ip,);
17324:
17325: if ($form->{'localpath'}) {
17326: $initial_env{"browser.localpath"} = $form->{'localpath'};
17327: $initial_env{"browser.localres"} = $form->{'localres'};
17328: }
17329:
17330: if ($form->{'interface'}) {
17331: $form->{'interface'}=~s/\W//gs;
17332: $initial_env{"browser.interface"} = $form->{'interface'};
17333: $env{'browser.interface'}=$form->{'interface'};
17334: }
17335:
17336: if ($form->{'iptoken'}) {
17337: my $lonhost = $r->dir_config('lonHostID');
17338: $initial_env{"user.noloadbalance"} = $lonhost;
17339: $env{'user.noloadbalance'} = $lonhost;
17340: }
17341:
17342: if ($form->{'noloadbalance'}) {
17343: my @hosts = &Apache::lonnet::current_machine_ids();
17344: my $hosthere = $form->{'noloadbalance'};
17345: if (grep(/^\Q$hosthere\E$/,@hosts)) {
17346: $initial_env{"user.noloadbalance"} = $hosthere;
17347: $env{'user.noloadbalance'} = $hosthere;
17348: }
17349: }
17350:
17351: unless ($domain eq 'public') {
17352: my %is_adv = ( is_adv => $env{'user.adv'} );
17353: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17354:
17355: foreach my $tool ('aboutme','blog','webdav','portfolio') {
17356: $userenv{'availabletools.'.$tool} =
17357: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17358: undef,\%userenv,\%domdef,\%is_adv);
17359: }
17360:
17361: foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17362: $userenv{'canrequest.'.$crstype} =
17363: &Apache::lonnet::usertools_access($username,$domain,$crstype,
17364: 'reload','requestcourses',
17365: \%userenv,\%domdef,\%is_adv);
17366: }
17367:
17368: $userenv{'canrequest.author'} =
17369: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17370: 'reload','requestauthor',
17371: \%userenv,\%domdef,\%is_adv);
17372: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17373: $domain,$username);
17374: my $reqstatus = $reqauthor{'author_status'};
17375: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
17376: if (ref($reqauthor{'author'}) eq 'HASH') {
17377: $userenv{'requestauthorqueued'} = $reqstatus.':'.
17378: $reqauthor{'author'}{'timestamp'};
17379: }
17380: }
17381: my ($types,$typename) = &course_types();
17382: if (ref($types) eq 'ARRAY') {
17383: my @options = ('approval','validate','autolimit');
17384: my $optregex = join('|',@options);
17385: my (%willtrust,%trustchecked);
17386: foreach my $type (@{$types}) {
17387: my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17388: if ($dom_str ne '') {
17389: my $updatedstr = '';
17390: my @possdomains = split(',',$dom_str);
17391: foreach my $entry (@possdomains) {
17392: my ($extdom,$extopt) = split(':',$entry);
17393: unless ($trustchecked{$extdom}) {
17394: $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17395: $trustchecked{$extdom} = 1;
17396: }
17397: if ($willtrust{$extdom}) {
17398: $updatedstr .= $entry.',';
17399: }
17400: }
17401: $updatedstr =~ s/,$//;
17402: if ($updatedstr) {
17403: $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17404: } else {
17405: delete($userenv{'reqcrsotherdom.'.$type});
17406: }
17407: }
17408: }
17409: }
17410: }
17411: $env{'user.environment'} = "$lonids/$cookie.id";
17412:
17413: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17414: &GDBM_WRCREAT(),0640)) {
17415: &_add_to_env(\%disk_env,\%initial_env);
17416: &_add_to_env(\%disk_env,\%userenv,'environment.');
17417: &_add_to_env(\%disk_env,$userroles);
17418: if (ref($firstaccenv) eq 'HASH') {
17419: &_add_to_env(\%disk_env,$firstaccenv);
17420: }
17421: if (ref($timerintenv) eq 'HASH') {
17422: &_add_to_env(\%disk_env,$timerintenv);
17423: }
17424: if (ref($args->{'extra_env'})) {
17425: &_add_to_env(\%disk_env,$args->{'extra_env'});
17426: }
17427: untie(%disk_env);
17428: } else {
17429: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17430: 'Could not create environment storage in lonauth: '.$!.'</span>');
17431: return 'error: '.$!;
17432: }
17433: }
17434: $env{'request.role'}='cm';
17435: $env{'request.role.adv'}=$env{'user.adv'};
17436: $env{'browser.type'}=$clientbrowser;
17437:
17438: return $cookie;
17439:
17440: }
17441:
17442: sub _add_to_env {
17443: my ($idf,$env_data,$prefix) = @_;
17444: if (ref($env_data) eq 'HASH') {
17445: while (my ($key,$value) = each(%$env_data)) {
17446: $idf->{$prefix.$key} = $value;
17447: $env{$prefix.$key} = $value;
17448: }
17449: }
17450: }
17451:
17452: # --- Get the symbolic name of a problem and the url
17453: sub get_symb {
17454: my ($request,$silent) = @_;
17455: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17456: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17457: if ($symb eq '') {
17458: if (!$silent) {
17459: if (ref($request)) {
17460: $request->print("Unable to handle ambiguous references:$url:.");
17461: }
17462: return ();
17463: }
17464: }
17465: &Apache::lonenc::check_decrypt(\$symb);
17466: return ($symb);
17467: }
17468:
17469: # --------------------------------------------------------------Get annotation
17470:
17471: sub get_annotation {
17472: my ($symb,$enc) = @_;
17473:
17474: my $key = $symb;
17475: if (!$enc) {
17476: $key =
17477: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17478: }
17479: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17480: return $annotation{$key};
17481: }
17482:
17483: sub clean_symb {
17484: my ($symb,$delete_enc) = @_;
17485:
17486: &Apache::lonenc::check_decrypt(\$symb);
17487: my $enc = $env{'request.enc'};
17488: if ($delete_enc) {
17489: delete($env{'request.enc'});
17490: }
17491:
17492: return ($symb,$enc);
17493: }
17494:
17495: ############################################################
17496: ############################################################
17497:
17498: =pod
17499:
17500: =head1 Routines for building display used to search for courses
17501:
17502:
17503: =over 4
17504:
17505: =item * &build_filters()
17506:
17507: Create markup for a table used to set filters to use when selecting
17508: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
17509: and quotacheck.pl
17510:
17511:
17512: Inputs:
17513:
17514: filterlist - anonymous array of fields to include as potential filters
17515:
17516: crstype - course type
17517:
17518: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17519: to pop-open a course selector (will contain "extra element").
17520:
17521: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17522:
17523: filter - anonymous hash of criteria and their values
17524:
17525: action - form action
17526:
17527: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17528:
17529: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17530:
17531: cloneruname - username of owner of new course who wants to clone
17532:
17533: clonerudom - domain of owner of new course who wants to clone
17534:
17535: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
17536:
17537: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17538:
17539: codedom - domain
17540:
17541: formname - value of form element named "form".
17542:
17543: fixeddom - domain, if fixed.
17544:
17545: prevphase - value to assign to form element named "phase" when going back to the previous screen
17546:
17547: cnameelement - name of form element in form on opener page which will receive title of selected course
17548:
17549: cnumelement - name of form element in form on opener page which will receive courseID of selected course
17550:
17551: cdomelement - name of form element in form on opener page which will receive domain of selected course
17552:
17553: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17554:
17555: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17556:
17557: clonewarning - warning message about missing information for intended course owner when DC creates a course
17558:
17559:
17560: Returns: $output - HTML for display of search criteria, and hidden form elements.
17561:
17562:
17563: Side Effects: None
17564:
17565: =cut
17566:
17567: # ---------------------------------------------- search for courses based on last activity etc.
17568:
17569: sub build_filters {
17570: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17571: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17572: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17573: $cnameelement,$cnumelement,$cdomelement,$setroles,
17574: $clonetext,$clonewarning) = @_;
17575: my ($list,$jscript);
17576: my $onchange = 'javascript:updateFilters(this)';
17577: my ($domainselectform,$sincefilterform,$createdfilterform,
17578: $ownerdomselectform,$persondomselectform,$instcodeform,
17579: $typeselectform,$instcodetitle);
17580: if ($formname eq '') {
17581: $formname = $caller;
17582: }
17583: foreach my $item (@{$filterlist}) {
17584: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17585: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17586: if ($item eq 'domainfilter') {
17587: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17588: } elsif ($item eq 'coursefilter') {
17589: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17590: } elsif ($item eq 'ownerfilter') {
17591: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17592: } elsif ($item eq 'ownerdomfilter') {
17593: $filter->{'ownerdomfilter'} =
17594: &LONCAPA::clean_domain($filter->{$item});
17595: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17596: 'ownerdomfilter',1);
17597: } elsif ($item eq 'personfilter') {
17598: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17599: } elsif ($item eq 'persondomfilter') {
17600: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17601: 'persondomfilter',1);
17602: } else {
17603: $filter->{$item} =~ s/\W//g;
17604: }
17605: if (!$filter->{$item}) {
17606: $filter->{$item} = '';
17607: }
17608: }
17609: if ($item eq 'domainfilter') {
17610: my $allow_blank = 1;
17611: if ($formname eq 'portform') {
17612: $allow_blank=0;
17613: } elsif ($formname eq 'studentform') {
17614: $allow_blank=0;
17615: }
17616: if ($fixeddom) {
17617: $domainselectform = '<input type="hidden" name="domainfilter"'.
17618: ' value="'.$codedom.'" />'.
17619: &Apache::lonnet::domain($codedom,'description');
17620: } else {
17621: $domainselectform = &select_dom_form($filter->{$item},
17622: 'domainfilter',
17623: $allow_blank,'',$onchange);
17624: }
17625: } else {
17626: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17627: }
17628: }
17629:
17630: # last course activity filter and selection
17631: $sincefilterform = &timebased_select_form('sincefilter',$filter);
17632:
17633: # course created filter and selection
17634: if (exists($filter->{'createdfilter'})) {
17635: $createdfilterform = &timebased_select_form('createdfilter',$filter);
17636: }
17637:
17638: my $prefix = $crstype;
17639: if ($crstype eq 'Placement') {
17640: $prefix = 'Placement Test'
17641: }
17642: my %lt = &Apache::lonlocal::texthash(
17643: 'cac' => "$prefix Activity",
17644: 'ccr' => "$prefix Created",
17645: 'cde' => "$prefix Title",
17646: 'cdo' => "$prefix Domain",
17647: 'ins' => 'Institutional Code',
17648: 'inc' => 'Institutional Categorization',
17649: 'cow' => "$prefix Owner/Co-owner",
17650: 'cop' => "$prefix Personnel Includes",
17651: 'cog' => 'Type',
17652: );
17653:
17654: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17655: my $typeval = 'Course';
17656: if ($crstype eq 'Community') {
17657: $typeval = 'Community';
17658: } elsif ($crstype eq 'Placement') {
17659: $typeval = 'Placement';
17660: }
17661: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
17662: } else {
17663: $typeselectform = '<select name="type" size="1"';
17664: if ($onchange) {
17665: $typeselectform .= ' onchange="'.$onchange.'"';
17666: }
17667: $typeselectform .= '>'."\n";
17668: foreach my $posstype ('Course','Community','Placement') {
17669: my $shown;
17670: if ($posstype eq 'Placement') {
17671: $shown = &mt('Placement Test');
17672: } else {
17673: $shown = &mt($posstype);
17674: }
17675: $typeselectform.='<option value="'.$posstype.'"'.
17676: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
17677: }
17678: $typeselectform.="</select>";
17679: }
17680:
17681: my ($cloneableonlyform,$cloneabletitle);
17682: if (exists($filter->{'cloneableonly'})) {
17683: my $cloneableon = '';
17684: my $cloneableoff = ' checked="checked"';
17685: if ($filter->{'cloneableonly'}) {
17686: $cloneableon = $cloneableoff;
17687: $cloneableoff = '';
17688: }
17689: $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>';
17690: if ($formname eq 'ccrs') {
17691: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17692: } else {
17693: $cloneabletitle = &mt('Cloneable by you');
17694: }
17695: }
17696: my $officialjs;
17697: if ($crstype eq 'Course') {
17698: if (exists($filter->{'instcodefilter'})) {
17699: # if (($fixeddom) || ($formname eq 'requestcrs') ||
17700: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17701: if ($codedom) {
17702: $officialjs = 1;
17703: ($instcodeform,$jscript,$$numtitlesref) =
17704: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17705: $officialjs,$codetitlesref);
17706: if ($jscript) {
17707: $jscript = '<script type="text/javascript">'."\n".
17708: '// <![CDATA['."\n".
17709: $jscript."\n".
17710: '// ]]>'."\n".
17711: '</script>'."\n";
17712: }
17713: }
17714: if ($instcodeform eq '') {
17715: $instcodeform =
17716: '<input type="text" name="instcodefilter" size="10" value="'.
17717: $list->{'instcodefilter'}.'" />';
17718: $instcodetitle = $lt{'ins'};
17719: } else {
17720: $instcodetitle = $lt{'inc'};
17721: }
17722: if ($fixeddom) {
17723: $instcodetitle .= '<br />('.$codedom.')';
17724: }
17725: }
17726: }
17727: my $output = qq|
17728: <form method="post" name="filterpicker" action="$action">
17729: <input type="hidden" name="form" value="$formname" />
17730: |;
17731: if ($formname eq 'modifycourse') {
17732: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17733: '<input type="hidden" name="prevphase" value="'.
17734: $prevphase.'" />'."\n";
17735: } elsif ($formname eq 'quotacheck') {
17736: $output .= qq|
17737: <input type="hidden" name="sortby" value="" />
17738: <input type="hidden" name="sortorder" value="" />
17739: |;
17740: } else {
17741: my $name_input;
17742: if ($cnameelement ne '') {
17743: $name_input = '<input type="hidden" name="cnameelement" value="'.
17744: $cnameelement.'" />';
17745: }
17746: $output .= qq|
17747: <input type="hidden" name="cnumelement" value="$cnumelement" />
17748: <input type="hidden" name="cdomelement" value="$cdomelement" />
17749: $name_input
17750: $roleelement
17751: $multelement
17752: $typeelement
17753: |;
17754: if ($formname eq 'portform') {
17755: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17756: }
17757: }
17758: if ($fixeddom) {
17759: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17760: }
17761: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17762: if ($sincefilterform) {
17763: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17764: .$sincefilterform
17765: .&Apache::lonhtmlcommon::row_closure();
17766: }
17767: if ($createdfilterform) {
17768: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17769: .$createdfilterform
17770: .&Apache::lonhtmlcommon::row_closure();
17771: }
17772: if ($domainselectform) {
17773: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17774: .$domainselectform
17775: .&Apache::lonhtmlcommon::row_closure();
17776: }
17777: if ($typeselectform) {
17778: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17779: $output .= $typeselectform;
17780: } else {
17781: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17782: .$typeselectform
17783: .&Apache::lonhtmlcommon::row_closure();
17784: }
17785: }
17786: if ($instcodeform) {
17787: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17788: .$instcodeform
17789: .&Apache::lonhtmlcommon::row_closure();
17790: }
17791: if (exists($filter->{'ownerfilter'})) {
17792: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17793: '<table><tr><td>'.&mt('Username').'<br />'.
17794: '<input type="text" name="ownerfilter" size="20" value="'.
17795: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17796: $ownerdomselectform.'</td></tr></table>'.
17797: &Apache::lonhtmlcommon::row_closure();
17798: }
17799: if (exists($filter->{'personfilter'})) {
17800: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17801: '<table><tr><td>'.&mt('Username').'<br />'.
17802: '<input type="text" name="personfilter" size="20" value="'.
17803: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17804: $persondomselectform.'</td></tr></table>'.
17805: &Apache::lonhtmlcommon::row_closure();
17806: }
17807: if (exists($filter->{'coursefilter'})) {
17808: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17809: .'<input type="text" name="coursefilter" size="25" value="'
17810: .$list->{'coursefilter'}.'" />'
17811: .&Apache::lonhtmlcommon::row_closure();
17812: }
17813: if ($cloneableonlyform) {
17814: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17815: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17816: }
17817: if (exists($filter->{'descriptfilter'})) {
17818: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17819: .'<input type="text" name="descriptfilter" size="40" value="'
17820: .$list->{'descriptfilter'}.'" />'
17821: .&Apache::lonhtmlcommon::row_closure(1);
17822: }
17823: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17824: '<input type="hidden" name="updater" value="" />'."\n".
17825: '<input type="submit" name="gosearch" value="'.
17826: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17827: return $jscript.$clonewarning.$output;
17828: }
17829:
17830: =pod
17831:
17832: =item * &timebased_select_form()
17833:
17834: Create markup for a dropdown list used to select a time-based
17835: filter e.g., Course Activity, Course Created, when searching for courses
17836: or communities
17837:
17838: Inputs:
17839:
17840: item - name of form element (sincefilter or createdfilter)
17841:
17842: filter - anonymous hash of criteria and their values
17843:
17844: Returns: HTML for a select box contained a blank, then six time selections,
17845: with value set in incoming form variables currently selected.
17846:
17847: Side Effects: None
17848:
17849: =cut
17850:
17851: sub timebased_select_form {
17852: my ($item,$filter) = @_;
17853: if (ref($filter) eq 'HASH') {
17854: $filter->{$item} =~ s/[^\d-]//g;
17855: if (!$filter->{$item}) { $filter->{$item}=-1; }
17856: return &select_form(
17857: $filter->{$item},
17858: $item,
17859: { '-1' => '',
17860: '86400' => &mt('today'),
17861: '604800' => &mt('last week'),
17862: '2592000' => &mt('last month'),
17863: '7776000' => &mt('last three months'),
17864: '15552000' => &mt('last six months'),
17865: '31104000' => &mt('last year'),
17866: 'select_form_order' =>
17867: ['-1','86400','604800','2592000','7776000',
17868: '15552000','31104000']});
17869: }
17870: }
17871:
17872: =pod
17873:
17874: =item * &js_changer()
17875:
17876: Create script tag containing Javascript used to submit course search form
17877: when course type or domain is changed, and also to hide 'Searching ...' on
17878: page load completion for page showing search result.
17879:
17880: Inputs: None
17881:
17882: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17883:
17884: Side Effects: None
17885:
17886: =cut
17887:
17888: sub js_changer {
17889: return <<ENDJS;
17890: <script type="text/javascript">
17891: // <![CDATA[
17892: function updateFilters(caller) {
17893: if (typeof(caller) != "undefined") {
17894: document.filterpicker.updater.value = caller.name;
17895: }
17896: document.filterpicker.submit();
17897: }
17898:
17899: function hideSearching() {
17900: if (document.getElementById('searching')) {
17901: document.getElementById('searching').style.display = 'none';
17902: }
17903: return;
17904: }
17905:
17906: // ]]>
17907: </script>
17908:
17909: ENDJS
17910: }
17911:
17912: =pod
17913:
17914: =item * &search_courses()
17915:
17916: Process selected filters form course search form and pass to lonnet::courseiddump
17917: to retrieve a hash for which keys are courseIDs which match the selected filters.
17918:
17919: Inputs:
17920:
17921: dom - domain being searched
17922:
17923: type - course type ('Course' or 'Community' or '.' if any).
17924:
17925: filter - anonymous hash of criteria and their values
17926:
17927: numtitles - for institutional codes - number of categories
17928:
17929: cloneruname - optional username of new course owner
17930:
17931: clonerudom - optional domain of new course owner
17932:
17933: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17934: (used when DC is using course creation form)
17935:
17936: codetitles - reference to array of titles of components in institutional codes (official courses).
17937:
17938: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17939: (and so can clone automatically)
17940:
17941: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17942:
17943: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17944: courses to clone
17945:
17946: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17947:
17948:
17949: Side Effects: None
17950:
17951: =cut
17952:
17953:
17954: sub search_courses {
17955: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17956: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17957: my (%courses,%showcourses,$cloner);
17958: if (($filter->{'ownerfilter'} ne '') ||
17959: ($filter->{'ownerdomfilter'} ne '')) {
17960: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17961: $filter->{'ownerdomfilter'};
17962: }
17963: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17964: if (!$filter->{$item}) {
17965: $filter->{$item}='.';
17966: }
17967: }
17968: my $now = time;
17969: my $timefilter =
17970: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17971: my ($createdbefore,$createdafter);
17972: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17973: $createdbefore = $now;
17974: $createdafter = $now-$filter->{'createdfilter'};
17975: }
17976: my ($instcodefilter,$regexpok);
17977: if ($numtitles) {
17978: if ($env{'form.official'} eq 'on') {
17979: $instcodefilter =
17980: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17981: $regexpok = 1;
17982: } elsif ($env{'form.official'} eq 'off') {
17983: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17984: unless ($instcodefilter eq '') {
17985: $regexpok = -1;
17986: }
17987: }
17988: } else {
17989: $instcodefilter = $filter->{'instcodefilter'};
17990: }
17991: if ($instcodefilter eq '') { $instcodefilter = '.'; }
17992: if ($type eq '') { $type = '.'; }
17993:
17994: if (($clonerudom ne '') && ($cloneruname ne '')) {
17995: $cloner = $cloneruname.':'.$clonerudom;
17996: }
17997: %courses = &Apache::lonnet::courseiddump($dom,
17998: $filter->{'descriptfilter'},
17999: $timefilter,
18000: $instcodefilter,
18001: $filter->{'combownerfilter'},
18002: $filter->{'coursefilter'},
18003: undef,undef,$type,$regexpok,undef,undef,
18004: undef,undef,$cloner,$cc_clone,
18005: $filter->{'cloneableonly'},
18006: $createdbefore,$createdafter,undef,
18007: $domcloner,undef,$reqcrsdom,$reqinstcode);
18008: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18009: my $ccrole;
18010: if ($type eq 'Community') {
18011: $ccrole = 'co';
18012: } else {
18013: $ccrole = 'cc';
18014: }
18015: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18016: $filter->{'persondomfilter'},
18017: 'userroles',undef,
18018: [$ccrole,'in','ad','ep','ta','cr'],
18019: $dom);
18020: foreach my $role (keys(%rolehash)) {
18021: my ($cnum,$cdom,$courserole) = split(':',$role);
18022: my $cid = $cdom.'_'.$cnum;
18023: if (exists($courses{$cid})) {
18024: if (ref($courses{$cid}) eq 'HASH') {
18025: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18026: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18027: push(@{$courses{$cid}{roles}},$courserole);
18028: }
18029: } else {
18030: $courses{$cid}{roles} = [$courserole];
18031: }
18032: $showcourses{$cid} = $courses{$cid};
18033: }
18034: }
18035: }
18036: %courses = %showcourses;
18037: }
18038: return %courses;
18039: }
18040:
18041: =pod
18042:
18043: =back
18044:
18045: =head1 Routines for version requirements for current course.
18046:
18047: =over 4
18048:
18049: =item * &check_release_required()
18050:
18051: Compares required LON-CAPA version with version on server, and
18052: if required version is newer looks for a server with the required version.
18053:
18054: Looks first at servers in user's owen domain; if none suitable, looks at
18055: servers in course's domain are permitted to host sessions for user's domain.
18056:
18057: Inputs:
18058:
18059: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18060:
18061: $courseid - Course ID of current course
18062:
18063: $rolecode - User's current role in course (for switchserver query string).
18064:
18065: $required - LON-CAPA version needed by course (format: Major.Minor).
18066:
18067:
18068: Returns:
18069:
18070: $switchserver - query string tp append to /adm/switchserver call (if
18071: current server's LON-CAPA version is too old.
18072:
18073: $warning - Message is displayed if no suitable server could be found.
18074:
18075: =cut
18076:
18077: sub check_release_required {
18078: my ($loncaparev,$courseid,$rolecode,$required) = @_;
18079: my ($switchserver,$warning);
18080: if ($required ne '') {
18081: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18082: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18083: if ($reqdmajor ne '' && $reqdminor ne '') {
18084: my $otherserver;
18085: if (($major eq '' && $minor eq '') ||
18086: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18087: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18088: my $switchlcrev =
18089: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18090: $userdomserver);
18091: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18092: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18093: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18094: my $cdom = $env{'course.'.$courseid.'.domain'};
18095: if ($cdom ne $env{'user.domain'}) {
18096: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18097: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18098: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18099: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18100: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18101: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18102: my $canhost =
18103: &Apache::lonnet::can_host_session($env{'user.domain'},
18104: $coursedomserver,
18105: $remoterev,
18106: $udomdefaults{'remotesessions'},
18107: $defdomdefaults{'hostedsessions'});
18108:
18109: if ($canhost) {
18110: $otherserver = $coursedomserver;
18111: } else {
18112: $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.");
18113: }
18114: } else {
18115: $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).");
18116: }
18117: } else {
18118: $otherserver = $userdomserver;
18119: }
18120: }
18121: if ($otherserver ne '') {
18122: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
18123: }
18124: }
18125: }
18126: return ($switchserver,$warning);
18127: }
18128:
18129: =pod
18130:
18131: =item * &check_release_result()
18132:
18133: Inputs:
18134:
18135: $switchwarning - Warning message if no suitable server found to host session.
18136:
18137: $switchserver - query string to append to /adm/switchserver containing lonHostID
18138: and current role.
18139:
18140: Returns: HTML to display with information about requirement to switch server.
18141: Either displaying warning with link to Roles/Courses screen or
18142: display link to switchserver.
18143:
18144: =cut
18145:
18146: sub check_release_result {
18147: my ($switchwarning,$switchserver) = @_;
18148: my $output = &start_page('Selected course unavailable on this server').
18149: '<p class="LC_warning">';
18150: if ($switchwarning) {
18151: $output .= $switchwarning.'<br /><a href="/adm/roles">';
18152: if (&show_course()) {
18153: $output .= &mt('Display courses');
18154: } else {
18155: $output .= &mt('Display roles');
18156: }
18157: $output .= '</a>';
18158: } elsif ($switchserver) {
18159: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18160: '<br />'.
18161: '<a href="/adm/switchserver?'.$switchserver.'">'.
18162: &mt('Switch Server').
18163: '</a>';
18164: }
18165: $output .= '</p>'.&end_page();
18166: return $output;
18167: }
18168:
18169: =pod
18170:
18171: =item * &needs_coursereinit()
18172:
18173: Determine if course contents stored for user's session needs to be
18174: refreshed, because content has changed since "Big Hash" last tied.
18175:
18176: Check for change is made if time last checked is more than 10 minutes ago
18177: (by default).
18178:
18179: Inputs:
18180:
18181: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18182:
18183: $interval (optional) - Time which may elapse (in s) between last check for content
18184: change in current course. (default: 600 s).
18185:
18186: Returns: an array; first element is:
18187:
18188: =over 4
18189:
18190: 'switch' - if content updates mean user's session
18191: needs to be switched to a server running a newer LON-CAPA version
18192:
18193: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18194: on current server hosting user's session
18195:
18196: '' - if no action required.
18197:
18198: =back
18199:
18200: If first item element is 'switch':
18201:
18202: second item is $switchwarning - Warning message if no suitable server found to host session.
18203:
18204: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18205: and current role.
18206:
18207: otherwise: no other elements returned.
18208:
18209: =back
18210:
18211: =cut
18212:
18213: sub needs_coursereinit {
18214: my ($loncaparev,$interval) = @_;
18215: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18216: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18217: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18218: my $now = time;
18219: if ($interval eq '') {
18220: $interval = 600;
18221: }
18222: if (($now-$env{'request.course.timechecked'})>$interval) {
18223: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18224: my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18225: if ($blocked) {
18226: return ();
18227: }
18228: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18229: if ($lastchange > $env{'request.course.tied'}) {
18230: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18231: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18232: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18233: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18234: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18235: $curr_reqd_hash{'internal.releaserequired'}});
18236: my ($switchserver,$switchwarning) =
18237: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18238: $curr_reqd_hash{'internal.releaserequired'});
18239: if ($switchwarning ne '' || $switchserver ne '') {
18240: return ('switch',$switchwarning,$switchserver);
18241: }
18242: }
18243: }
18244: return ('update');
18245: }
18246: }
18247: return ();
18248: }
18249:
18250: sub update_content_constraints {
18251: my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
18252: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18253: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18254: my (%checkresponsetypes,%checkcrsrestypes);
18255: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18256: my ($item,$name,$value) = split(/:/,$key);
18257: if ($item eq 'resourcetag') {
18258: if ($name eq 'responsetype') {
18259: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18260: }
18261: } elsif ($item eq 'course') {
18262: if ($name eq 'courserestype') {
18263: $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18264: }
18265: }
18266: }
18267: my $navmap = Apache::lonnavmaps::navmap->new();
18268: if (defined($navmap)) {
18269: my (%allresponses,%allcrsrestypes);
18270: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18271: if ($res->is_tool()) {
18272: if ($allcrsrestypes{'exttool'}) {
18273: $allcrsrestypes{'exttool'} ++;
18274: } else {
18275: $allcrsrestypes{'exttool'} = 1;
18276: }
18277: next;
18278: }
18279: my %responses = $res->responseTypes();
18280: foreach my $key (keys(%responses)) {
18281: next unless(exists($checkresponsetypes{$key}));
18282: $allresponses{$key} += $responses{$key};
18283: }
18284: }
18285: foreach my $key (keys(%allresponses)) {
18286: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18287: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18288: ($reqdmajor,$reqdminor) = ($major,$minor);
18289: }
18290: }
18291: foreach my $key (keys(%allcrsrestypes)) {
18292: my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18293: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18294: ($reqdmajor,$reqdminor) = ($major,$minor);
18295: }
18296: }
18297: undef($navmap);
18298: }
18299: my (@resources,@order,@resparms,@zombies);
18300: if ($keeporder) {
18301: use LONCAPA::map;
18302: @resources = @LONCAPA::map::resources;
18303: @order = @LONCAPA::map::order;
18304: @resparms = @LONCAPA::map::resparms;
18305: @zombies = @LONCAPA::map::zombies;
18306: }
18307: my $suppmap = 'supplemental.sequence';
18308: my ($suppcount,$supptools,$errors) = (0,0,0);
18309: ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
18310: $suppcount,$supptools,$errors);
18311: if ($keeporder) {
18312: @LONCAPA::map::resources = @resources;
18313: @LONCAPA::map::order = @order;
18314: @LONCAPA::map::resparms = @resparms;
18315: @LONCAPA::map::zombies = @zombies;
18316: }
18317: if ($supptools) {
18318: my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18319: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18320: ($reqdmajor,$reqdminor) = ($major,$minor);
18321: }
18322: }
18323: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18324: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18325: }
18326: return;
18327: }
18328:
18329: sub allmaps_incourse {
18330: my ($cdom,$cnum,$chome,$cid) = @_;
18331: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18332: $cid = $env{'request.course.id'};
18333: $cdom = $env{'course.'.$cid.'.domain'};
18334: $cnum = $env{'course.'.$cid.'.num'};
18335: $chome = $env{'course.'.$cid.'.home'};
18336: }
18337: my %allmaps = ();
18338: my $lastchange =
18339: &Apache::lonnet::get_coursechange($cdom,$cnum);
18340: if ($lastchange > $env{'request.course.tied'}) {
18341: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18342: unless ($ferr) {
18343: &update_content_constraints($cdom,$cnum,$chome,$cid,1);
18344: }
18345: }
18346: my $navmap = Apache::lonnavmaps::navmap->new();
18347: if (defined($navmap)) {
18348: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18349: $allmaps{$res->src()} = 1;
18350: }
18351: }
18352: return \%allmaps;
18353: }
18354:
18355: sub parse_supplemental_title {
18356: my ($title) = @_;
18357:
18358: my ($foldertitle,$renametitle);
18359: if ($title =~ /&&&/) {
18360: $title = &HTML::Entites::decode($title);
18361: }
18362: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18363: $renametitle=$4;
18364: my ($time,$uname,$udom) = ($1,$2,$3);
18365: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18366: my $name = &plainname($uname,$udom);
18367: $name = &HTML::Entities::encode($name,'"<>&\'');
18368: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18369: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
18370: $name.': <br />'.$foldertitle;
18371: }
18372: if (wantarray) {
18373: return ($title,$foldertitle,$renametitle);
18374: }
18375: return $title;
18376: }
18377:
18378: sub recurse_supplemental {
18379: my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
18380: if ($suppmap) {
18381: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18382: if ($fatal) {
18383: $errors ++;
18384: } else {
18385: if ($#LONCAPA::map::resources > 0) {
18386: foreach my $res (@LONCAPA::map::resources) {
18387: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
18388: if (($src ne '') && ($status eq 'res')) {
18389: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18390: ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
18391: $numfiles,$numexttools,$errors);
18392: } else {
18393: if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
18394: $numexttools ++;
18395: }
18396: $numfiles ++;
18397: }
18398: }
18399: }
18400: }
18401: }
18402: }
18403: return ($numfiles,$numexttools,$errors);
18404: }
18405:
18406: sub symb_to_docspath {
18407: my ($symb,$navmapref) = @_;
18408: return unless ($symb && ref($navmapref));
18409: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18410: if ($resurl=~/\.(sequence|page)$/) {
18411: $mapurl=$resurl;
18412: } elsif ($resurl eq 'adm/navmaps') {
18413: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18414: }
18415: my $mapresobj;
18416: unless (ref($$navmapref)) {
18417: $$navmapref = Apache::lonnavmaps::navmap->new();
18418: }
18419: if (ref($$navmapref)) {
18420: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18421: }
18422: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18423: my $type=$2;
18424: my $path;
18425: if (ref($mapresobj)) {
18426: my $pcslist = $mapresobj->map_hierarchy();
18427: if ($pcslist ne '') {
18428: foreach my $pc (split(/,/,$pcslist)) {
18429: next if ($pc <= 1);
18430: my $res = $$navmapref->getByMapPc($pc);
18431: if (ref($res)) {
18432: my $thisurl = $res->src();
18433: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18434: my $thistitle = $res->title();
18435: $path .= '&'.
18436: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18437: &escape($thistitle).
18438: ':'.$res->randompick().
18439: ':'.$res->randomout().
18440: ':'.$res->encrypted().
18441: ':'.$res->randomorder().
18442: ':'.$res->is_page();
18443: }
18444: }
18445: }
18446: $path =~ s/^\&//;
18447: my $maptitle = $mapresobj->title();
18448: if ($mapurl eq 'default') {
18449: $maptitle = 'Main Content';
18450: }
18451: $path .= (($path ne '')? '&' : '').
18452: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18453: &escape($maptitle).
18454: ':'.$mapresobj->randompick().
18455: ':'.$mapresobj->randomout().
18456: ':'.$mapresobj->encrypted().
18457: ':'.$mapresobj->randomorder().
18458: ':'.$mapresobj->is_page();
18459: } else {
18460: my $maptitle = &Apache::lonnet::gettitle($mapurl);
18461: my $ispage = (($type eq 'page')? 1 : '');
18462: if ($mapurl eq 'default') {
18463: $maptitle = 'Main Content';
18464: }
18465: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18466: &escape($maptitle).':::::'.$ispage;
18467: }
18468: unless ($mapurl eq 'default') {
18469: $path = 'default&'.
18470: &escape('Main Content').
18471: ':::::&'.$path;
18472: }
18473: return $path;
18474: }
18475:
18476: sub captcha_display {
18477: my ($context,$lonhost,$defdom) = @_;
18478: my ($output,$error);
18479: my ($captcha,$pubkey,$privkey,$version) =
18480: &get_captcha_config($context,$lonhost,$defdom);
18481: if ($captcha eq 'original') {
18482: $output = &create_captcha();
18483: unless ($output) {
18484: $error = 'captcha';
18485: }
18486: } elsif ($captcha eq 'recaptcha') {
18487: $output = &create_recaptcha($pubkey,$version);
18488: unless ($output) {
18489: $error = 'recaptcha';
18490: }
18491: }
18492: return ($output,$error,$captcha,$version);
18493: }
18494:
18495: sub captcha_response {
18496: my ($context,$lonhost,$defdom) = @_;
18497: my ($captcha_chk,$captcha_error);
18498: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
18499: if ($captcha eq 'original') {
18500: ($captcha_chk,$captcha_error) = &check_captcha();
18501: } elsif ($captcha eq 'recaptcha') {
18502: $captcha_chk = &check_recaptcha($privkey,$version);
18503: } else {
18504: $captcha_chk = 1;
18505: }
18506: return ($captcha_chk,$captcha_error);
18507: }
18508:
18509: sub get_captcha_config {
18510: my ($context,$lonhost,$dom_in_effect) = @_;
18511: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
18512: my $hostname = &Apache::lonnet::hostname($lonhost);
18513: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
18514: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18515: if ($context eq 'usercreation') {
18516: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
18517: if (ref($domconfig{$context}) eq 'HASH') {
18518: $hashtocheck = $domconfig{$context}{'cancreate'};
18519: if (ref($hashtocheck) eq 'HASH') {
18520: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
18521: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
18522: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
18523: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
18524: }
18525: if ($privkey && $pubkey) {
18526: $captcha = 'recaptcha';
18527: $version = $hashtocheck->{'recaptchaversion'};
18528: if ($version ne '2') {
18529: $version = 1;
18530: }
18531: } else {
18532: $captcha = 'original';
18533: }
18534: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
18535: $captcha = 'original';
18536: }
18537: }
18538: } else {
18539: $captcha = 'captcha';
18540: }
18541: } elsif ($context eq 'login') {
18542: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
18543: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
18544: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
18545: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
18546: if ($privkey && $pubkey) {
18547: $captcha = 'recaptcha';
18548: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
18549: if ($version ne '2') {
18550: $version = 1;
18551: }
18552: } else {
18553: $captcha = 'original';
18554: }
18555: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
18556: $captcha = 'original';
18557: }
18558: } elsif ($context eq 'passwords') {
18559: if ($dom_in_effect) {
18560: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
18561: if ($passwdconf{'captcha'} eq 'recaptcha') {
18562: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
18563: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
18564: $privkey = $passwdconf{'recaptchakeys'}{'private'};
18565: }
18566: if ($privkey && $pubkey) {
18567: $captcha = 'recaptcha';
18568: $version = $passwdconf{'recaptchaversion'};
18569: if ($version ne '2') {
18570: $version = 1;
18571: }
18572: } else {
18573: $captcha = 'original';
18574: }
18575: } elsif ($passwdconf{'captcha'} ne 'notused') {
18576: $captcha = 'original';
18577: }
18578: }
18579: }
18580: return ($captcha,$pubkey,$privkey,$version);
18581: }
18582:
18583: sub create_captcha {
18584: my %captcha_params = &captcha_settings();
18585: my ($output,$maxtries,$tries) = ('',10,0);
18586: while ($tries < $maxtries) {
18587: $tries ++;
18588: my $captcha = Authen::Captcha->new (
18589: output_folder => $captcha_params{'output_dir'},
18590: data_folder => $captcha_params{'db_dir'},
18591: );
18592: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
18593:
18594: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
18595: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
18596: '<span class="LC_nobreak">'.
18597: &mt('Type in the letters/numbers shown below').' '.
18598: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
18599: '</span><br />'.
18600: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
18601: last;
18602: }
18603: }
18604: if ($output eq '') {
18605: &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
18606: }
18607: return $output;
18608: }
18609:
18610: sub captcha_settings {
18611: my %captcha_params = (
18612: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
18613: www_output_dir => "/captchaspool",
18614: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
18615: numchars => '5',
18616: );
18617: return %captcha_params;
18618: }
18619:
18620: sub check_captcha {
18621: my ($captcha_chk,$captcha_error);
18622: my $code = $env{'form.code'};
18623: my $md5sum = $env{'form.crypt'};
18624: my %captcha_params = &captcha_settings();
18625: my $captcha = Authen::Captcha->new(
18626: output_folder => $captcha_params{'output_dir'},
18627: data_folder => $captcha_params{'db_dir'},
18628: );
18629: $captcha_chk = $captcha->check_code($code,$md5sum);
18630: my %captcha_hash = (
18631: 0 => 'Code not checked (file error)',
18632: -1 => 'Failed: code expired',
18633: -2 => 'Failed: invalid code (not in database)',
18634: -3 => 'Failed: invalid code (code does not match crypt)',
18635: );
18636: if ($captcha_chk != 1) {
18637: $captcha_error = $captcha_hash{$captcha_chk}
18638: }
18639: return ($captcha_chk,$captcha_error);
18640: }
18641:
18642: sub create_recaptcha {
18643: my ($pubkey,$version) = @_;
18644: if ($version >= 2) {
18645: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
18646: '<div style="padding:0;clear:both;margin:0;border:0"></div>';
18647: } else {
18648: my $use_ssl;
18649: if ($ENV{'SERVER_PORT'} == 443) {
18650: $use_ssl = 1;
18651: }
18652: my $captcha = Captcha::reCAPTCHA->new;
18653: return $captcha->get_options_setter({theme => 'white'})."\n".
18654: $captcha->get_html($pubkey,undef,$use_ssl).
18655: &mt('If the text is hard to read, [_1] will replace them.',
18656: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
18657: '<br /><br />';
18658: }
18659: }
18660:
18661: sub check_recaptcha {
18662: my ($privkey,$version) = @_;
18663: my $captcha_chk;
18664: my $ip = &Apache::lonnet::get_requestor_ip();
18665: if ($version >= 2) {
18666: my %info = (
18667: secret => $privkey,
18668: response => $env{'form.g-recaptcha-response'},
18669: remoteip => $ip,
18670: );
18671: my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
18672: $request->content(join('&',map {
18673: my $name = escape($_);
18674: "$name=" . ( ref($info{$_}) eq 'ARRAY'
18675: ? join("&$name=", map {escape($_) } @{$info{$_}})
18676: : &escape($info{$_}) );
18677: } keys(%info)));
18678: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
18679: if ($response->is_success) {
18680: my $data = JSON::DWIW->from_json($response->decoded_content);
18681: if (ref($data) eq 'HASH') {
18682: if ($data->{'success'}) {
18683: $captcha_chk = 1;
18684: }
18685: }
18686: }
18687: } else {
18688: my $captcha = Captcha::reCAPTCHA->new;
18689: my $captcha_result =
18690: $captcha->check_answer(
18691: $privkey,
18692: $ip,
18693: $env{'form.recaptcha_challenge_field'},
18694: $env{'form.recaptcha_response_field'},
18695: );
18696: if ($captcha_result->{is_valid}) {
18697: $captcha_chk = 1;
18698: }
18699: }
18700: return $captcha_chk;
18701: }
18702:
18703: sub emailusername_info {
18704: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
18705: my %titles = &Apache::lonlocal::texthash (
18706: lastname => 'Last Name',
18707: firstname => 'First Name',
18708: institution => 'School/college/university',
18709: location => "School's city, state/province, country",
18710: web => "School's web address",
18711: officialemail => 'E-mail address at institution (if different)',
18712: id => 'Student/Employee ID',
18713: );
18714: return (\@fields,\%titles);
18715: }
18716:
18717: sub cleanup_html {
18718: my ($incoming) = @_;
18719: my $outgoing;
18720: if ($incoming ne '') {
18721: $outgoing = $incoming;
18722: $outgoing =~ s/;/;/g;
18723: $outgoing =~ s/\#/#/g;
18724: $outgoing =~ s/\&/&/g;
18725: $outgoing =~ s/</</g;
18726: $outgoing =~ s/>/>/g;
18727: $outgoing =~ s/\(/(/g;
18728: $outgoing =~ s/\)/)/g;
18729: $outgoing =~ s/"/"/g;
18730: $outgoing =~ s/'/'/g;
18731: $outgoing =~ s/\$/$/g;
18732: $outgoing =~ s{/}{/}g;
18733: $outgoing =~ s/=/=/g;
18734: $outgoing =~ s/\\/\/g
18735: }
18736: return $outgoing;
18737: }
18738:
18739: # Checks for critical messages and returns a redirect url if one exists.
18740: # $interval indicates how often to check for messages.
18741: # $context is the calling context -- roles, grades, contents, menu or flip.
18742: sub critical_redirect {
18743: my ($interval,$context) = @_;
18744: unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18745: return ();
18746: }
18747: if ((time-$env{'user.criticalcheck.time'})>$interval) {
18748: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18749: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18750: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18751: my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18752: if ($blocked) {
18753: my $checkrole = "cm./$cdom/$cnum";
18754: if ($env{'request.course.sec'} ne '') {
18755: $checkrole .= "/$env{'request.course.sec'}";
18756: }
18757: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18758: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18759: return;
18760: }
18761: }
18762: }
18763: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18764: $env{'user.name'});
18765: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18766: my $redirecturl;
18767: if ($what[0]) {
18768: if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18769: $redirecturl='/adm/email?critical=display';
18770: my $url=&Apache::lonnet::absolute_url().$redirecturl;
18771: return (1, $url);
18772: }
18773: }
18774: }
18775: return ();
18776: }
18777:
18778: # Use:
18779: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18780: #
18781: ##################################################
18782: # password associated functions #
18783: ##################################################
18784: sub des_keys {
18785: # Make a new key for DES encryption.
18786: # Each key has two parts which are returned separately.
18787: # Please note: Each key must be passed through the &hex function
18788: # before it is output to the web browser. The hex versions cannot
18789: # be used to decrypt.
18790: my @hexstr=('0','1','2','3','4','5','6','7',
18791: '8','9','a','b','c','d','e','f');
18792: my $lkey='';
18793: for (0..7) {
18794: $lkey.=$hexstr[rand(15)];
18795: }
18796: my $ukey='';
18797: for (0..7) {
18798: $ukey.=$hexstr[rand(15)];
18799: }
18800: return ($lkey,$ukey);
18801: }
18802:
18803: sub des_decrypt {
18804: my ($key,$cyphertext) = @_;
18805: my $keybin=pack("H16",$key);
18806: my $cypher;
18807: if ($Crypt::DES::VERSION>=2.03) {
18808: $cypher=new Crypt::DES $keybin;
18809: } else {
18810: $cypher=new DES $keybin;
18811: }
18812: my $plaintext='';
18813: my $cypherlength = length($cyphertext);
18814: my $numchunks = int($cypherlength/32);
18815: for (my $j=0; $j<$numchunks; $j++) {
18816: my $start = $j*32;
18817: my $cypherblock = substr($cyphertext,$start,32);
18818: my $chunk =
18819: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18820: $chunk .=
18821: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18822: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18823: $plaintext .= $chunk;
18824: }
18825: return $plaintext;
18826: }
18827:
18828: sub get_requested_shorturls {
18829: my ($cdom,$cnum,$navmap) = @_;
18830: return unless (ref($navmap));
18831: my ($numnew,$errors);
18832: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18833: if (@toshorten) {
18834: my (%maps,%resources,%titles);
18835: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18836: 'shorturls',$cdom,$cnum);
18837: if (keys(%resources)) {
18838: my %tocreate;
18839: foreach my $item (sort {$a <=> $b} (@toshorten)) {
18840: my $symb = $resources{$item};
18841: if ($symb) {
18842: $tocreate{$cnum.'&'.$symb} = 1;
18843: }
18844: }
18845: if (keys(%tocreate)) {
18846: ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18847: \%tocreate);
18848: }
18849: }
18850: }
18851: return ($numnew,$errors);
18852: }
18853:
18854: sub make_short_symbs {
18855: my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18856: my ($numnew,@errors);
18857: if (ref($tocreateref) eq 'HASH') {
18858: my %tocreate = %{$tocreateref};
18859: if (keys(%tocreate)) {
18860: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18861: my $su = Short::URL->new(no_vowels => 1);
18862: my $init = '';
18863: my (%newunique,%addcourse,%courseonly,%failed);
18864: # get lock on tiny db
18865: my $now = time;
18866: if ($lockuser eq '') {
18867: $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18868: }
18869: my $lockhash = {
18870: "lock\0$now" => $lockuser,
18871: };
18872: my $tries = 0;
18873: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18874: my ($code,$error);
18875: while (($gotlock ne 'ok') && ($tries<3)) {
18876: $tries ++;
18877: sleep 1;
18878: $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18879: }
18880: if ($gotlock eq 'ok') {
18881: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18882: \%addcourse,\%courseonly,\%failed);
18883: if (keys(%failed)) {
18884: my $numfailed = scalar(keys(%failed));
18885: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18886: }
18887: if (keys(%newunique)) {
18888: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18889: if ($putres eq 'ok') {
18890: $numnew = scalar(keys(%newunique));
18891: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18892: unless ($newputres eq 'ok') {
18893: push(@errors,&mt('error: could not store course look-up of short URLs'));
18894: }
18895: } else {
18896: push(@errors,&mt('error: could not store unique six character URLs'));
18897: }
18898: }
18899: my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18900: unless ($dellockres eq 'ok') {
18901: push(@errors,&mt('error: could not release lockfile'));
18902: }
18903: } else {
18904: push(@errors,&mt('error: could not obtain lockfile'));
18905: }
18906: if (keys(%courseonly)) {
18907: my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18908: if ($result ne 'ok') {
18909: push(@errors,&mt('error: could not update course look-up of short URLs'));
18910: }
18911: }
18912: }
18913: }
18914: return ($numnew,\@errors);
18915: }
18916:
18917: sub shorten_symbs {
18918: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18919: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18920: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18921: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18922: my (%possibles,%collisions);
18923: foreach my $key (keys(%{$tocreate})) {
18924: my $num = String::CRC32::crc32($key);
18925: my $tiny = $su->encode($num,$init);
18926: if ($tiny) {
18927: $possibles{$tiny} = $key;
18928: }
18929: }
18930: if (!$init) {
18931: $init = 1;
18932: } else {
18933: $init ++;
18934: }
18935: if (keys(%possibles)) {
18936: my @posstiny = keys(%possibles);
18937: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18938: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18939: if (keys(%currtiny)) {
18940: foreach my $key (keys(%currtiny)) {
18941: next if ($currtiny{$key} eq '');
18942: if ($currtiny{$key} eq $possibles{$key}) {
18943: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18944: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18945: $courseonly->{$tsymb} = $key;
18946: }
18947: } else {
18948: $collisions{$possibles{$key}} = 1;
18949: }
18950: delete($possibles{$key});
18951: }
18952: }
18953: foreach my $key (keys(%possibles)) {
18954: $newunique->{$key} = $possibles{$key};
18955: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18956: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18957: $addcourse->{$tsymb} = $key;
18958: }
18959: }
18960: }
18961: if (keys(%collisions)) {
18962: if ($init <5) {
18963: if (!$init) {
18964: $init = 1;
18965: } else {
18966: $init ++;
18967: }
18968: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18969: $newunique,$addcourse,$courseonly,$failed);
18970: } else {
18971: foreach my $key (keys(%collisions)) {
18972: $failed->{$key} = 1;
18973: }
18974: }
18975: }
18976: return $init;
18977: }
18978:
18979: sub is_nonframeable {
18980: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18981: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18982: return if (($remprotocol eq '') || ($remhost eq ''));
18983:
18984: $remprotocol = lc($remprotocol);
18985: $remhost = lc($remhost);
18986: my $remport = 80;
18987: if ($remprotocol eq 'https') {
18988: $remport = 443;
18989: }
18990: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18991: if ($cached) {
18992: unless ($nocache) {
18993: if ($result) {
18994: return 1;
18995: } else {
18996: return 0;
18997: }
18998: }
18999: }
19000: my $uselink;
19001: my $request = new HTTP::Request('HEAD',$url);
19002: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19003: if ($response->is_success()) {
19004: my $secpolicy = lc($response->header('content-security-policy'));
19005: my $xframeop = lc($response->header('x-frame-options'));
19006: $secpolicy =~ s/^\s+|\s+$//g;
19007: $xframeop =~ s/^\s+|\s+$//g;
19008: if (($secpolicy ne '') || ($xframeop ne '')) {
19009: my $remotehost = $remprotocol.'://'.$remhost;
19010: my ($origin,$protocol,$port);
19011: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19012: $port = $ENV{'SERVER_PORT'};
19013: } else {
19014: $port = 80;
19015: }
19016: if ($absolute eq '') {
19017: $protocol = 'http:';
19018: if ($port == 443) {
19019: $protocol = 'https:';
19020: }
19021: $origin = $protocol.'//'.lc($hostname);
19022: } else {
19023: $origin = lc($absolute);
19024: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19025: }
19026: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19027: my $framepolicy = $1;
19028: $framepolicy =~ s/^\s+|\s+$//g;
19029: my @policies = split(/\s+/,$framepolicy);
19030: if (@policies) {
19031: if (grep(/^\Q'none'\E$/,@policies)) {
19032: $uselink = 1;
19033: } else {
19034: $uselink = 1;
19035: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19036: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19037: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19038: undef($uselink);
19039: }
19040: if ($uselink) {
19041: if (grep(/^\Q'self'\E$/,@policies)) {
19042: if (($origin ne '') && ($remotehost eq $origin)) {
19043: undef($uselink);
19044: }
19045: }
19046: }
19047: if ($uselink) {
19048: my @possok;
19049: if ($ip ne '') {
19050: push(@possok,$ip);
19051: }
19052: my $hoststr = '';
19053: foreach my $part (reverse(split(/\./,$hostname))) {
19054: if ($hoststr eq '') {
19055: $hoststr = $part;
19056: } else {
19057: $hoststr = "$part.$hoststr";
19058: }
19059: if ($hoststr eq $hostname) {
19060: push(@possok,$hostname);
19061: } else {
19062: push(@possok,"*.$hoststr");
19063: }
19064: }
19065: if (@possok) {
19066: foreach my $poss (@possok) {
19067: last if (!$uselink);
19068: foreach my $policy (@policies) {
19069: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19070: undef($uselink);
19071: last;
19072: }
19073: }
19074: }
19075: }
19076: }
19077: }
19078: }
19079: } elsif ($xframeop ne '') {
19080: $uselink = 1;
19081: my @policies = split(/\s*,\s*/,$xframeop);
19082: if (@policies) {
19083: unless (grep(/^deny$/,@policies)) {
19084: if ($origin ne '') {
19085: if (grep(/^sameorigin$/,@policies)) {
19086: if ($remotehost eq $origin) {
19087: undef($uselink);
19088: }
19089: }
19090: if ($uselink) {
19091: foreach my $policy (@policies) {
19092: if ($policy =~ /^allow-from\s*(.+)$/) {
19093: my $allowfrom = $1;
19094: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19095: undef($uselink);
19096: last;
19097: }
19098: }
19099: }
19100: }
19101: }
19102: }
19103: }
19104: }
19105: }
19106: }
19107: if ($nocache) {
19108: if ($cached) {
19109: my $devalidate;
19110: if ($uselink && !$result) {
19111: $devalidate = 1;
19112: } elsif (!$uselink && $result) {
19113: $devalidate = 1;
19114: }
19115: if ($devalidate) {
19116: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19117: }
19118: }
19119: } else {
19120: if ($uselink) {
19121: $result = 1;
19122: } else {
19123: $result = 0;
19124: }
19125: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19126: }
19127: return $uselink;
19128: }
19129:
19130: sub page_menu {
19131: my ($menucolls,$menunum) = @_;
19132: my %menu;
19133: foreach my $item (split(/;/,$menucolls)) {
19134: my ($num,$value) = split(/\%/,$item);
19135: if ($num eq $menunum) {
19136: my @entries = split(/\&/,$value);
19137: foreach my $entry (@entries) {
19138: my ($name,$fields) = split(/=/,$entry);
19139: if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19140: $menu{$name} = $fields;
19141: } else {
19142: my @shown;
19143: if ($fields =~ /,/) {
19144: @shown = split(/,/,$fields);
19145: } else {
19146: @shown = ($fields);
19147: }
19148: if (@shown) {
19149: foreach my $field (@shown) {
19150: next if ($field eq '');
19151: $menu{$field} = 1;
19152: }
19153: }
19154: }
19155: }
19156: }
19157: }
19158: return %menu;
19159: }
19160:
19161: 1;
19162: __END__;
19163:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>