1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1416 2023/11/11 18:50:51 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnavmaps();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use LONCAPA::ltiutils;
75: use LONCAPA::LWPReq;
76: use LONCAPA::map();
77: use HTTP::Request;
78: use DateTime::TimeZone;
79: use DateTime::Locale;
80: use Encode();
81: use Text::Aspell;
82: use Authen::Captcha;
83: use Captcha::reCAPTCHA;
84: use JSON::DWIW;
85: use Crypt::DES;
86: use DynaLoader; # for Crypt::DES version
87: use MIME::Lite;
88: use MIME::Types;
89: use File::Copy();
90: use File::Path();
91: use String::CRC32();
92: use Short::URL();
93:
94: # ---------------------------------------------- Designs
95: use vars qw(%defaultdesign);
96:
97: my $readit;
98:
99:
100: ##
101: ## Global Variables
102: ##
103:
104:
105: # ----------------------------------------------- SSI with retries:
106: #
107:
108: =pod
109:
110: =head1 Server Side include with retries:
111:
112: =over 4
113:
114: =item * &ssi_with_retries(resource,retries form)
115:
116: Performs an ssi with some number of retries. Retries continue either
117: until the result is ok or until the retry count supplied by the
118: caller is exhausted.
119:
120: Inputs:
121:
122: =over 4
123:
124: resource - Identifies the resource to insert.
125:
126: retries - Count of the number of retries allowed.
127:
128: form - Hash that identifies the rendering options.
129:
130: =back
131:
132: Returns:
133:
134: =over 4
135:
136: content - The content of the response. If retries were exhausted this is empty.
137:
138: response - The response from the last attempt (which may or may not have been successful.
139:
140: =back
141:
142: =back
143:
144: =cut
145:
146: sub ssi_with_retries {
147: my ($resource, $retries, %form) = @_;
148:
149:
150: my $ok = 0; # True if we got a good response.
151: my $content;
152: my $response;
153:
154: # Try to get the ssi done. within the retries count:
155:
156: do {
157: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
158: $ok = $response->is_success;
159: if (!$ok) {
160: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
161: }
162: $retries--;
163: } while (!$ok && ($retries > 0));
164:
165: if (!$ok) {
166: $content = ''; # On error return an empty content.
167: }
168: return ($content, $response);
169:
170: }
171:
172:
173:
174: # ----------------------------------------------- Filetypes/Languages/Copyright
175: my %language;
176: my %supported_language;
177: my %supported_codes;
178: my %latex_language; # For choosing hyphenation in <transl..>
179: my %latex_language_bykey; # for choosing hyphenation from metadata
180: my %cprtag;
181: my %scprtag;
182: my %fe; my %fd; my %fm;
183: my %category_extensions;
184:
185: # ---------------------------------------------- Thesaurus variables
186: #
187: # %Keywords:
188: # A hash used by &keyword to determine if a word is considered a keyword.
189: # $thesaurus_db_file
190: # Scalar containing the full path to the thesaurus database.
191:
192: my %Keywords;
193: my $thesaurus_db_file;
194:
195: #
196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
197: # thesaurus.tab, and filecategories.tab.
198: #
199: BEGIN {
200: # Variable initialization
201: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
202: #
203: unless ($readit) {
204: # ------------------------------------------------------------------- languages
205: {
206: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
207: '/language.tab';
208: if ( open(my $fh,'<',$langtabfile) ) {
209: while (my $line = <$fh>) {
210: next if ($line=~/^\#/);
211: chomp($line);
212: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
213: $language{$key}=$val.' - '.$enc;
214: if ($sup) {
215: $supported_language{$key}=$sup;
216: $supported_codes{$key} = $code;
217: }
218: if ($latex) {
219: $latex_language_bykey{$key} = $latex;
220: $latex_language{$code} = $latex;
221: }
222: }
223: close($fh);
224: }
225: }
226: # ------------------------------------------------------------------ copyrights
227: {
228: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
229: '/copyright.tab';
230: if ( open (my $fh,'<',$copyrightfile) ) {
231: while (my $line = <$fh>) {
232: next if ($line=~/^\#/);
233: chomp($line);
234: my ($key,$val)=(split(/\s+/,$line,2));
235: $cprtag{$key}=$val;
236: }
237: close($fh);
238: }
239: }
240: # ----------------------------------------------------------- source copyrights
241: {
242: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
243: '/source_copyright.tab';
244: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
245: while (my $line = <$fh>) {
246: next if ($line =~ /^\#/);
247: chomp($line);
248: my ($key,$val)=(split(/\s+/,$line,2));
249: $scprtag{$key}=$val;
250: }
251: close($fh);
252: }
253: }
254:
255: # -------------------------------------------------------------- default domain designs
256: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
257: my $designfile = $designdir.'/default.tab';
258: if ( open (my $fh,'<',$designfile) ) {
259: while (my $line = <$fh>) {
260: next if ($line =~ /^\#/);
261: chomp($line);
262: my ($key,$val)=(split(/\=/,$line));
263: if ($val) { $defaultdesign{$key}=$val; }
264: }
265: close($fh);
266: }
267:
268: # ------------------------------------------------------------- file categories
269: {
270: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
271: '/filecategories.tab';
272: if ( open (my $fh,'<',$categoryfile) ) {
273: while (my $line = <$fh>) {
274: next if ($line =~ /^\#/);
275: chomp($line);
276: my ($extension,$category)=(split(/\s+/,$line,2));
277: push(@{$category_extensions{lc($category)}},$extension);
278: }
279: close($fh);
280: }
281:
282: }
283: # ------------------------------------------------------------------ file types
284: {
285: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
286: '/filetypes.tab';
287: if ( open (my $fh,'<',$typesfile) ) {
288: while (my $line = <$fh>) {
289: next if ($line =~ /^\#/);
290: chomp($line);
291: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
292: if ($descr ne '') {
293: $fe{$ending}=lc($emb);
294: $fd{$ending}=$descr;
295: if ($mime ne 'unk') { $fm{$ending}=$mime; }
296: }
297: }
298: close($fh);
299: }
300: }
301: &Apache::lonnet::logthis(
302: "<span style='color:yellow;'>INFO: Read file types</span>");
303: $readit=1;
304: } # end of unless($readit)
305:
306: }
307:
308: ###############################################################
309: ## HTML and Javascript Helper Functions ##
310: ###############################################################
311:
312: =pod
313:
314: =head1 HTML and Javascript Functions
315:
316: =over 4
317:
318: =item * &browser_and_searcher_javascript()
319:
320: X<browsing, javascript>X<searching, javascript>Returns a string
321: containing javascript with two functions, C<openbrowser> and
322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
323: tags.
324:
325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
326:
327: inputs: formname, elementname, only, omit
328:
329: formname and elementname indicate the name of the html form and name of
330: the element that the results of the browsing selection are to be placed in.
331:
332: Specifying 'only' will restrict the browser to displaying only files
333: with the given extension. Can be a comma separated list.
334:
335: Specifying 'omit' will restrict the browser to NOT displaying files
336: with the given extension. Can be a comma separated list.
337:
338: =item * &opensearcher(formname,elementname) [javascript]
339:
340: Inputs: formname, elementname
341:
342: formname and elementname specify the name of the html form and the name
343: of the element the selection from the search results will be placed in.
344:
345: =cut
346:
347: sub browser_and_searcher_javascript {
348: my ($mode)=@_;
349: if (!defined($mode)) { $mode='edit'; }
350: my $resurl=&escape_single(&lastresurl());
351: return <<END;
352: // <!-- BEGIN LON-CAPA Internal
353: var editbrowser = null;
354: function openbrowser(formname,elementname,only,omit,titleelement) {
355: var url = '$resurl/?';
356: if (editbrowser == null) {
357: url += 'launch=1&';
358: }
359: url += 'catalogmode=interactive&';
360: url += 'mode=$mode&';
361: url += 'inhibitmenu=yes&';
362: url += 'form=' + formname + '&';
363: if (only != null) {
364: url += 'only=' + only + '&';
365: } else {
366: url += 'only=&';
367: }
368: if (omit != null) {
369: url += 'omit=' + omit + '&';
370: } else {
371: url += 'omit=&';
372: }
373: if (titleelement != null) {
374: url += 'titleelement=' + titleelement + '&';
375: } else {
376: url += 'titleelement=&';
377: }
378: url += 'element=' + elementname + '';
379: var title = 'Browser';
380: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
381: options += ',width=700,height=600';
382: editbrowser = open(url,title,options,'1');
383: editbrowser.focus();
384: }
385: var editsearcher;
386: function opensearcher(formname,elementname,titleelement) {
387: var url = '/adm/searchcat?';
388: if (editsearcher == null) {
389: url += 'launch=1&';
390: }
391: url += 'catalogmode=interactive&';
392: url += 'mode=$mode&';
393: url += 'form=' + formname + '&';
394: if (titleelement != null) {
395: url += 'titleelement=' + titleelement + '&';
396: } else {
397: url += 'titleelement=&';
398: }
399: url += 'element=' + elementname + '';
400: var title = 'Search';
401: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
402: options += ',width=700,height=600';
403: editsearcher = open(url,title,options,'1');
404: editsearcher.focus();
405: }
406: // END LON-CAPA Internal -->
407: END
408: }
409:
410: sub lastresurl {
411: if ($env{'environment.lastresurl'}) {
412: return $env{'environment.lastresurl'}
413: } else {
414: return '/res';
415: }
416: }
417:
418: sub storeresurl {
419: my $resurl=&Apache::lonnet::clutter(shift);
420: unless ($resurl=~/^\/res/) { return 0; }
421: $resurl=~s/\/$//;
422: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
423: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
424: return 1;
425: }
426:
427: sub studentbrowser_javascript {
428: unless (
429: (($env{'request.course.id'}) &&
430: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
431: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
432: '/'.$env{'request.course.sec'})
433: ))
434: || ($env{'request.role'}=~/^(au|dc|su)/)
435: ) { return ''; }
436: return (<<'ENDSTDBRW');
437: <script type="text/javascript" language="Javascript">
438: // <![CDATA[
439: var stdeditbrowser;
440: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
441: var url = '/adm/pickstudent?';
442: var filter;
443: if (!ignorefilter) {
444: eval('filter=document.'+formname+'.'+uname+'.value;');
445: }
446: if (filter != null) {
447: if (filter != '') {
448: url += 'filter='+filter+'&';
449: }
450: }
451: url += 'form=' + formname + '&unameelement='+uname+
452: '&udomelement='+udom+
453: '&clicker='+clicker;
454: if (roleflag) { url+="&roles=1"; }
455: if (courseadv == 'condition') {
456: if (document.getElementById('courseadv')) {
457: courseadv = document.getElementById('courseadv').value;
458: }
459: }
460: if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
461: if (uident !== '') { url+="&identelement="+uident; }
462: var title = 'Student_Browser';
463: var options = 'scrollbars=1,resizable=1,menubar=0';
464: options += ',width=700,height=600';
465: stdeditbrowser = open(url,title,options,'1');
466: stdeditbrowser.focus();
467: }
468: // ]]>
469: </script>
470: ENDSTDBRW
471: }
472:
473: sub resourcebrowser_javascript {
474: unless ($env{'request.course.id'}) { return ''; }
475: return (<<'ENDRESBRW');
476: <script type="text/javascript" language="Javascript">
477: // <![CDATA[
478: var reseditbrowser;
479: function openresbrowser(formname,reslink) {
480: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
481: var title = 'Resource_Browser';
482: var options = 'scrollbars=1,resizable=1,menubar=0';
483: options += ',width=700,height=500';
484: reseditbrowser = open(url,title,options,'1');
485: reseditbrowser.focus();
486: }
487: // ]]>
488: </script>
489: ENDRESBRW
490: }
491:
492: sub selectstudent_link {
493: my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
494: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
495: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
496: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
497: if ($env{'request.course.id'}) {
498: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
499: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
500: '/'.$env{'request.course.sec'})) {
501: return '';
502: }
503: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
504: if ($courseadv eq 'only') {
505: $callargs .= ",'',1,'$courseadv'";
506: } elsif ($courseadv eq 'none') {
507: $callargs .= ",'','','$courseadv'";
508: } elsif ($courseadv eq 'condition') {
509: $callargs .= ",'','','$courseadv'";
510: } elsif ($identelem ne '') {
511: $callargs .= ",'','',''";
512: }
513: if ($identelem ne '') {
514: $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
515: }
516: return '<span class="LC_nobreak">'.
517: '<a href="javascript:openstdbrowser('.$callargs.');">'.
518: &mt('Select User').'</a></span>';
519: }
520: if ($env{'request.role'}=~/^(au|dc|su)/) {
521: $callargs .= ",'',1";
522: return '<span class="LC_nobreak">'.
523: '<a href="javascript:openstdbrowser('.$callargs.');">'.
524: &mt('Select User').'</a></span>';
525: }
526: return '';
527: }
528:
529: sub selectresource_link {
530: my ($form,$reslink,$arg)=@_;
531:
532: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
533: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
534: unless ($env{'request.course.id'}) { return $arg; }
535: return '<span class="LC_nobreak">'.
536: '<a href="javascript:openresbrowser('.$callargs.');">'.
537: $arg.'</a></span>';
538: }
539:
540:
541:
542: sub authorbrowser_javascript {
543: return <<"ENDAUTHORBRW";
544: <script type="text/javascript" language="JavaScript">
545: // <![CDATA[
546: var stdeditbrowser;
547:
548: function openauthorbrowser(formname,udom) {
549: var url = '/adm/pickauthor?';
550: url += 'form='+formname+'&roledom='+udom;
551: var title = 'Author_Browser';
552: var options = 'scrollbars=1,resizable=1,menubar=0';
553: options += ',width=700,height=600';
554: stdeditbrowser = open(url,title,options,'1');
555: stdeditbrowser.focus();
556: }
557:
558: // ]]>
559: </script>
560: ENDAUTHORBRW
561: }
562:
563: sub coursebrowser_javascript {
564: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
565: $credits_element,$instcode) = @_;
566: my $wintitle = 'Course_Browser';
567: if ($crstype eq 'Community') {
568: $wintitle = 'Community_Browser';
569: }
570: my $id_functions = &javascript_index_functions();
571: my $output = '
572: <script type="text/javascript" language="JavaScript">
573: // <![CDATA[
574: var stdeditbrowser;'."\n";
575:
576: $output .= <<"ENDSTDBRW";
577: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
578: var url = '/adm/pickcourse?';
579: var formid = getFormIdByName(formname);
580: var domainfilter = getDomainFromSelectbox(formname,udom);
581: if (domainfilter != null) {
582: if (domainfilter != '') {
583: url += 'domainfilter='+domainfilter+'&';
584: }
585: }
586: url += 'form=' + formname + '&cnumelement='+uname+
587: '&cdomelement='+udom+
588: '&cnameelement='+desc;
589: if (extra_element !=null && extra_element != '') {
590: if (formname == 'rolechoice' || formname == 'studentform') {
591: url += '&roleelement='+extra_element;
592: if (domainfilter == null || domainfilter == '') {
593: url += '&domainfilter='+extra_element;
594: }
595: }
596: else {
597: if (formname == 'portform') {
598: url += '&setroles='+extra_element;
599: } else {
600: if (formname == 'rules') {
601: url += '&fixeddom='+extra_element;
602: }
603: }
604: }
605: }
606: if (type != null && type != '') {
607: url += '&type='+type;
608: }
609: if (type_elem != null && type_elem != '') {
610: url += '&typeelement='+type_elem;
611: }
612: if (formname == 'ccrs') {
613: var ownername = document.forms[formid].ccuname.value;
614: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
615: url += '&cloner='+ownername+':'+ownerdom;
616: if (type == 'Course') {
617: url += '&crscode='+document.forms[formid].crscode.value;
618: }
619: }
620: if (formname == 'requestcrs') {
621: url += '&crsdom=$domainfilter&crscode=$instcode';
622: }
623: if (multflag !=null && multflag != '') {
624: url += '&multiple='+multflag;
625: }
626: var title = '$wintitle';
627: var options = 'scrollbars=1,resizable=1,menubar=0';
628: options += ',width=700,height=600';
629: stdeditbrowser = open(url,title,options,'1');
630: stdeditbrowser.focus();
631: }
632: $id_functions
633: ENDSTDBRW
634: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
635: $output .= &setsec_javascript($sec_element,$formname,$role_element,
636: $credits_element);
637: }
638: $output .= '
639: // ]]>
640: </script>';
641: return $output;
642: }
643:
644: sub javascript_index_functions {
645: return <<"ENDJS";
646:
647: function getFormIdByName(formname) {
648: for (var i=0;i<document.forms.length;i++) {
649: if (document.forms[i].name == formname) {
650: return i;
651: }
652: }
653: return -1;
654: }
655:
656: function getIndexByName(formid,item) {
657: for (var i=0;i<document.forms[formid].elements.length;i++) {
658: if (document.forms[formid].elements[i].name == item) {
659: return i;
660: }
661: }
662: return -1;
663: }
664:
665: function getDomainFromSelectbox(formname,udom) {
666: var userdom;
667: var formid = getFormIdByName(formname);
668: if (formid > -1) {
669: var domid = getIndexByName(formid,udom);
670: if (domid > -1) {
671: if (document.forms[formid].elements[domid].type == 'select-one') {
672: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
673: }
674: if (document.forms[formid].elements[domid].type == 'hidden') {
675: userdom=document.forms[formid].elements[domid].value;
676: }
677: }
678: }
679: return userdom;
680: }
681:
682: ENDJS
683:
684: }
685:
686: sub javascript_array_indexof {
687: return <<ENDJS;
688: <script type="text/javascript" language="JavaScript">
689: // <![CDATA[
690:
691: if (!Array.prototype.indexOf) {
692: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
693: "use strict";
694: if (this === void 0 || this === null) {
695: throw new TypeError();
696: }
697: var t = Object(this);
698: var len = t.length >>> 0;
699: if (len === 0) {
700: return -1;
701: }
702: var n = 0;
703: if (arguments.length > 0) {
704: n = Number(arguments[1]);
705: if (n !== n) { // shortcut for verifying if it is NaN
706: n = 0;
707: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
708: n = (n > 0 || -1) * Math.floor(Math.abs(n));
709: }
710: }
711: if (n >= len) {
712: return -1;
713: }
714: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
715: for (; k < len; k++) {
716: if (k in t && t[k] === searchElement) {
717: return k;
718: }
719: }
720: return -1;
721: }
722: }
723:
724: // ]]>
725: </script>
726:
727: ENDJS
728:
729: }
730:
731: sub userbrowser_javascript {
732: my $id_functions = &javascript_index_functions();
733: return <<"ENDUSERBRW";
734:
735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
736: var url = '/adm/pickuser?';
737: var userdom = getDomainFromSelectbox(formname,udom);
738: if (userdom != null) {
739: if (userdom != '') {
740: url += 'srchdom='+userdom+'&';
741: }
742: }
743: url += 'form=' + formname + '&unameelement='+uname+
744: '&udomelement='+udom+
745: '&ulastelement='+ulast+
746: '&ufirstelement='+ufirst+
747: '&uemailelement='+uemail+
748: '&hideudomelement='+hideudom+
749: '&coursedom='+crsdom;
750: if ((caller != null) && (caller != undefined)) {
751: url += '&caller='+caller;
752: }
753: var title = 'User_Browser';
754: var options = 'scrollbars=1,resizable=1,menubar=0';
755: options += ',width=700,height=600';
756: var stdeditbrowser = open(url,title,options,'1');
757: stdeditbrowser.focus();
758: }
759:
760: function fix_domain (formname,udom,origdom,uname) {
761: var formid = getFormIdByName(formname);
762: if (formid > -1) {
763: var unameid = getIndexByName(formid,uname);
764: var domid = getIndexByName(formid,udom);
765: var hidedomid = getIndexByName(formid,origdom);
766: if (hidedomid > -1) {
767: var fixeddom = document.forms[formid].elements[hidedomid].value;
768: var unameval = document.forms[formid].elements[unameid].value;
769: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
770: if (domid > -1) {
771: var slct = document.forms[formid].elements[domid];
772: if (slct.type == 'select-one') {
773: var i;
774: for (i=0;i<slct.length;i++) {
775: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
776: }
777: }
778: if (slct.type == 'hidden') {
779: slct.value = fixeddom;
780: }
781: }
782: }
783: }
784: }
785: return;
786: }
787:
788: $id_functions
789: ENDUSERBRW
790: }
791:
792: sub setsec_javascript {
793: my ($sec_element,$formname,$role_element,$credits_element) = @_;
794: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
795: $communityrolestr);
796: if ($role_element ne '') {
797: my @allroles = ('st','ta','ep','in','ad');
798: foreach my $crstype ('Course','Community') {
799: if ($crstype eq 'Community') {
800: foreach my $role (@allroles) {
801: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
802: }
803: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
804: } else {
805: foreach my $role (@allroles) {
806: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
807: }
808: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
809: }
810: }
811: $rolestr = '"'.join('","',@allroles).'"';
812: $courserolestr = '"'.join('","',@courserolenames).'"';
813: $communityrolestr = '"'.join('","',@communityrolenames).'"';
814: }
815: my $setsections = qq|
816: function setSect(sectionlist) {
817: var sectionsArray = new Array();
818: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
819: sectionsArray = sectionlist.split(",");
820: }
821: var numSections = sectionsArray.length;
822: document.$formname.$sec_element.length = 0;
823: if (numSections == 0) {
824: document.$formname.$sec_element.multiple=false;
825: document.$formname.$sec_element.size=1;
826: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
827: } else {
828: if (numSections == 1) {
829: document.$formname.$sec_element.multiple=false;
830: document.$formname.$sec_element.size=1;
831: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
832: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
833: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
834: } else {
835: for (var i=0; i<numSections; i++) {
836: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
837: }
838: document.$formname.$sec_element.multiple=true
839: if (numSections < 3) {
840: document.$formname.$sec_element.size=numSections;
841: } else {
842: document.$formname.$sec_element.size=3;
843: }
844: document.$formname.$sec_element.options[0].selected = false
845: }
846: }
847: }
848:
849: function setRole(crstype) {
850: |;
851: if ($role_element eq '') {
852: $setsections .= ' return;
853: }
854: ';
855: } else {
856: $setsections .= qq|
857: var elementLength = document.$formname.$role_element.length;
858: var allroles = Array($rolestr);
859: var courserolenames = Array($courserolestr);
860: var communityrolenames = Array($communityrolestr);
861: if (elementLength != undefined) {
862: if (document.$formname.$role_element.options[5].value == 'cc') {
863: if (crstype == 'Course') {
864: return;
865: } else {
866: allroles[5] = 'co';
867: for (var i=0; i<6; i++) {
868: document.$formname.$role_element.options[i].value = allroles[i];
869: document.$formname.$role_element.options[i].text = communityrolenames[i];
870: }
871: }
872: } else {
873: if (crstype == 'Community') {
874: return;
875: } else {
876: allroles[5] = 'cc';
877: for (var i=0; i<6; i++) {
878: document.$formname.$role_element.options[i].value = allroles[i];
879: document.$formname.$role_element.options[i].text = courserolenames[i];
880: }
881: }
882: }
883: }
884: return;
885: }
886: |;
887: }
888: if ($credits_element) {
889: $setsections .= qq|
890: function setCredits(defaultcredits) {
891: document.$formname.$credits_element.value = defaultcredits;
892: return;
893: }
894: |;
895: }
896: return $setsections;
897: }
898:
899: sub selectcourse_link {
900: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
901: $typeelement) = @_;
902: my $type = $selecttype;
903: my $linktext = &mt('Select Course');
904: if ($selecttype eq 'Community') {
905: $linktext = &mt('Select Community');
906: } elsif ($selecttype eq 'Placement') {
907: $linktext = &mt('Select Placement Test');
908: } elsif ($selecttype eq 'Course/Community') {
909: $linktext = &mt('Select Course/Community');
910: $type = '';
911: } elsif ($selecttype eq 'Select') {
912: $linktext = &mt('Select');
913: $type = '';
914: }
915: return '<span class="LC_nobreak">'
916: ."<a href='"
917: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
918: .'","'.$udomele.'","'.$desc.'","'.$extra_element
919: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
920: ."'>".$linktext.'</a>'
921: .'</span>';
922: }
923:
924: sub selectauthor_link {
925: my ($form,$udom)=@_;
926: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
927: &mt('Select Author').'</a>';
928: }
929:
930: sub selectuser_link {
931: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
932: $coursedom,$linktext,$caller) = @_;
933: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
934: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
935: ');">'.$linktext.'</a>';
936: }
937:
938: sub check_uncheck_jscript {
939: my $jscript = <<"ENDSCRT";
940: function checkAll(field) {
941: if (field.length > 0) {
942: for (i = 0; i < field.length; i++) {
943: if (!field[i].disabled) {
944: field[i].checked = true;
945: }
946: }
947: } else {
948: if (!field.disabled) {
949: field.checked = true;
950: }
951: }
952: }
953:
954: function uncheckAll(field) {
955: if (field.length > 0) {
956: for (i = 0; i < field.length; i++) {
957: field[i].checked = false ;
958: }
959: } else {
960: field.checked = false ;
961: }
962: }
963: ENDSCRT
964: return $jscript;
965: }
966:
967: sub select_timezone {
968: my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
969: my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
970: if ($includeempty) {
971: $output .= '<option value=""';
972: if (($selected eq '') || ($selected eq 'local')) {
973: $output .= ' selected="selected" ';
974: }
975: $output .= '> </option>';
976: }
977: my @timezones = DateTime::TimeZone->all_names;
978: foreach my $tzone (@timezones) {
979: $output.= '<option value="'.$tzone.'"';
980: if ($tzone eq $selected) {
981: $output.=' selected="selected"';
982: }
983: $output.=">$tzone</option>\n";
984: }
985: $output.="</select>";
986: return $output;
987: }
988:
989: sub select_datelocale {
990: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
991: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
992: if ($includeempty) {
993: $output .= '<option value=""';
994: if ($selected eq '') {
995: $output .= ' selected="selected" ';
996: }
997: $output .= '> </option>';
998: }
999: my @languages = &Apache::lonlocal::preferred_languages();
1000: my (@possibles,%locale_names);
1001: my @locales = DateTime::Locale->ids();
1002: foreach my $id (@locales) {
1003: if ($id ne '') {
1004: my ($en_terr,$native_terr);
1005: my $loc = DateTime::Locale->load($id);
1006: if (ref($loc)) {
1007: $en_terr = $loc->name();
1008: $native_terr = $loc->native_name();
1009: if (grep(/^en$/,@languages) || !@languages) {
1010: if ($en_terr ne '') {
1011: $locale_names{$id} = '('.$en_terr.')';
1012: } elsif ($native_terr ne '') {
1013: $locale_names{$id} = $native_terr;
1014: }
1015: } else {
1016: if ($native_terr ne '') {
1017: $locale_names{$id} = $native_terr.' ';
1018: } elsif ($en_terr ne '') {
1019: $locale_names{$id} = '('.$en_terr.')';
1020: }
1021: }
1022: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1023: push(@possibles,$id);
1024: }
1025: }
1026: }
1027: foreach my $item (sort(@possibles)) {
1028: $output.= '<option value="'.$item.'"';
1029: if ($item eq $selected) {
1030: $output.=' selected="selected"';
1031: }
1032: $output.=">$item";
1033: if ($locale_names{$item} ne '') {
1034: $output.=' '.$locale_names{$item};
1035: }
1036: $output.="</option>\n";
1037: }
1038: $output.="</select>";
1039: return $output;
1040: }
1041:
1042: sub select_language {
1043: my ($name,$selected,$includeempty,$noedit) = @_;
1044: my %langchoices;
1045: if ($includeempty) {
1046: %langchoices = ('' => 'No language preference');
1047: }
1048: foreach my $id (&languageids()) {
1049: my $code = &supportedlanguagecode($id);
1050: if ($code) {
1051: $langchoices{$code} = &plainlanguagedescription($id);
1052: }
1053: }
1054: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1055: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1056: }
1057:
1058: =pod
1059:
1060:
1061: =item * &list_languages()
1062:
1063: Returns an array reference that is suitable for use in language prompters.
1064: Each array element is itself a two element array. The first element
1065: is the language code. The second element a descsriptiuon of the
1066: language itself. This is suitable for use in e.g.
1067: &Apache::edit::select_arg (once dereferenced that is).
1068:
1069: =cut
1070:
1071: sub list_languages {
1072: my @lang_choices;
1073:
1074: foreach my $id (&languageids()) {
1075: my $code = &supportedlanguagecode($id);
1076: if ($code) {
1077: my $selector = $supported_codes{$id};
1078: my $description = &plainlanguagedescription($id);
1079: push(@lang_choices, [$selector, $description]);
1080: }
1081: }
1082: return \@lang_choices;
1083: }
1084:
1085: =pod
1086:
1087: =item * &linked_select_forms(...)
1088:
1089: linked_select_forms returns a string containing a <script></script> block
1090: and html for two <select> menus. The select menus will be linked in that
1091: changing the value of the first menu will result in new values being placed
1092: in the second menu. The values in the select menu will appear in alphabetical
1093: order unless a defined order is provided.
1094:
1095: linked_select_forms takes the following ordered inputs:
1096:
1097: =over 4
1098:
1099: =item * $formname, the name of the <form> tag
1100:
1101: =item * $middletext, the text which appears between the <select> tags
1102:
1103: =item * $firstdefault, the default value for the first menu
1104:
1105: =item * $firstselectname, the name of the first <select> tag
1106:
1107: =item * $secondselectname, the name of the second <select> tag
1108:
1109: =item * $hashref, a reference to a hash containing the data for the menus.
1110:
1111: =item * $menuorder, the order of values in the first menu
1112:
1113: =item * $onchangefirst, additional javascript call to execute for an onchange
1114: event for the first <select> tag
1115:
1116: =item * $onchangesecond, additional javascript call to execute for an onchange
1117: event for the second <select> tag
1118:
1119: =item * $suffix, to differentiate separate uses of select2data javascript
1120: objects in a page.
1121:
1122: =back
1123:
1124: Below is an example of such a hash. Only the 'text', 'default', and
1125: 'select2' keys must appear as stated. keys(%menu) are the possible
1126: values for the first select menu. The text that coincides with the
1127: first menu value is given in $menu{$choice1}->{'text'}. The values
1128: and text for the second menu are given in the hash pointed to by
1129: $menu{$choice1}->{'select2'}.
1130:
1131: my %menu = ( A1 => { text =>"Choice A1" ,
1132: default => "B3",
1133: select2 => {
1134: B1 => "Choice B1",
1135: B2 => "Choice B2",
1136: B3 => "Choice B3",
1137: B4 => "Choice B4"
1138: },
1139: order => ['B4','B3','B1','B2'],
1140: },
1141: A2 => { text =>"Choice A2" ,
1142: default => "C2",
1143: select2 => {
1144: C1 => "Choice C1",
1145: C2 => "Choice C2",
1146: C3 => "Choice C3"
1147: },
1148: order => ['C2','C1','C3'],
1149: },
1150: A3 => { text =>"Choice A3" ,
1151: default => "D6",
1152: select2 => {
1153: D1 => "Choice D1",
1154: D2 => "Choice D2",
1155: D3 => "Choice D3",
1156: D4 => "Choice D4",
1157: D5 => "Choice D5",
1158: D6 => "Choice D6",
1159: D7 => "Choice D7"
1160: },
1161: order => ['D4','D3','D2','D1','D7','D6','D5'],
1162: }
1163: );
1164:
1165: =cut
1166:
1167: sub linked_select_forms {
1168: my ($formname,
1169: $middletext,
1170: $firstdefault,
1171: $firstselectname,
1172: $secondselectname,
1173: $hashref,
1174: $menuorder,
1175: $onchangefirst,
1176: $onchangesecond,
1177: $suffix
1178: ) = @_;
1179: my $second = "document.$formname.$secondselectname";
1180: my $first = "document.$formname.$firstselectname";
1181: # output the javascript to do the changing
1182: my $result = '';
1183: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1184: $result.="// <![CDATA[\n";
1185: $result.="var select2data${suffix} = new Object();\n";
1186: $" = '","';
1187: my $debug = '';
1188: foreach my $s1 (sort(keys(%$hashref))) {
1189: $result.="select2data${suffix}['d_$s1'] = new Object();\n";
1190: $result.="select2data${suffix}['d_$s1'].def = new String('".
1191: $hashref->{$s1}->{'default'}."');\n";
1192: $result.="select2data${suffix}['d_$s1'].values = new Array(";
1193: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1194: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1195: @s2values = @{$hashref->{$s1}->{'order'}};
1196: }
1197: $result.="\"@s2values\");\n";
1198: $result.="select2data${suffix}['d_$s1'].texts = new Array(";
1199: my @s2texts;
1200: foreach my $value (@s2values) {
1201: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1202: }
1203: $result.="\"@s2texts\");\n";
1204: }
1205: $"=' ';
1206: $result.= <<"END";
1207:
1208: function select1${suffix}_changed() {
1209: // Determine new choice
1210: var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1211: // update select2
1212: var values = select2data${suffix}[newvalue].values;
1213: var texts = select2data${suffix}[newvalue].texts;
1214: var select2def = select2data${suffix}[newvalue].def;
1215: var i;
1216: // out with the old
1217: $second.options.length = 0;
1218: // in with the new
1219: for (i=0;i<values.length; i++) {
1220: $second.options[i] = new Option(values[i]);
1221: $second.options[i].value = values[i];
1222: $second.options[i].text = texts[i];
1223: if (values[i] == select2def) {
1224: $second.options[i].selected = true;
1225: }
1226: }
1227: }
1228: // ]]>
1229: </script>
1230: END
1231: # output the initial values for the selection lists
1232: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1233: my @order = sort(keys(%{$hashref}));
1234: if (ref($menuorder) eq 'ARRAY') {
1235: @order = @{$menuorder};
1236: }
1237: foreach my $value (@order) {
1238: $result.=" <option value=\"$value\" ";
1239: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1240: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1241: }
1242: $result .= "</select>\n";
1243: my %select2;
1244: if (ref($hashref->{$firstdefault}) eq 'HASH') {
1245: if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
1246: %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1247: }
1248: }
1249: $result .= $middletext;
1250: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1251: if ($onchangesecond) {
1252: $result .= ' onchange="'.$onchangesecond.'"';
1253: }
1254: $result .= ">\n";
1255: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1256:
1257: my @secondorder = sort(keys(%select2));
1258: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1259: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1260: }
1261: foreach my $value (@secondorder) {
1262: $result.=" <option value=\"$value\" ";
1263: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1264: $result.=">".&mt($select2{$value})."</option>\n";
1265: }
1266: $result .= "</select>\n";
1267: # return $debug;
1268: return $result;
1269: } # end of sub linked_select_forms {
1270:
1271: =pod
1272:
1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1274:
1275: Returns a string corresponding to an HTML link to the given help
1276: $topic, where $topic corresponds to the name of a .tex file in
1277: /home/httpd/html/adm/help/tex, with underscores replaced by
1278: spaces.
1279:
1280: $text will optionally be linked to the same topic, allowing you to
1281: link text in addition to the graphic. If you do not want to link
1282: text, but wish to specify one of the later parameters, pass an
1283: empty string.
1284:
1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
1286: the link will not open a new window. If false, the link will open
1287: a new window using Javascript. (Default is false.)
1288:
1289: $width and $height are optional numerical parameters that will
1290: override the width and height of the popped up window, which may
1291: be useful for certain help topics with big pictures included.
1292:
1293: $imgid is the id of the img tag used for the help icon. This may be
1294: used in a javascript call to switch the image src. See
1295: lonhtmlcommon::htmlareaselectactive() for an example.
1296:
1297: $links_target will optionally be set to a target (_top, _parent or _self).
1298:
1299: =cut
1300:
1301: sub help_open_topic {
1302: my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1303: $text = "" if (not defined $text);
1304: $stayOnPage = 0 if (not defined $stayOnPage);
1305: $width = 500 if (not defined $width);
1306: $height = 400 if (not defined $height);
1307: my $filename = $topic;
1308: $filename =~ s/ /_/g;
1309:
1310: my $template = "";
1311: my $link;
1312:
1313: $topic=~s/\W/\_/g;
1314:
1315: if (!$stayOnPage) {
1316: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1317: } elsif ($stayOnPage eq 'popup') {
1318: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1319: } else {
1320: $link = "/adm/help/${filename}.hlp";
1321: }
1322:
1323: # Add the text
1324: my $target = ' target="_top"';
1325: if ($links_target) {
1326: $target = ' target="'.$links_target.'"';
1327: } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1328: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1329: $target = '';
1330: }
1331: if ($text ne "") {
1332: $template.='<span class="LC_help_open_topic">'
1333: .'<a'.$target.' href="'.$link.'">'
1334: .$text.'</a>';
1335: }
1336:
1337: # (Always) Add the graphic
1338: my $title = &mt('Online Help');
1339: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1340: if ($imgid ne '') {
1341: $imgid = ' id="'.$imgid.'"';
1342: }
1343: $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1344: .'<img src="'.$helpicon.'" border="0"'
1345: .' alt="'.&mt('Help: [_1]',$topic).'"'
1346: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1347: .' /></a>';
1348: if ($text ne "") {
1349: $template.='</span>';
1350: }
1351: return $template;
1352:
1353: }
1354:
1355: # This is a quicky function for Latex cheatsheet editing, since it
1356: # appears in at least four places
1357: sub helpLatexCheatsheet {
1358: my ($topic,$text,$not_author,$stayOnPage) = @_;
1359: my $out;
1360: my $addOther = '';
1361: if ($topic) {
1362: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1363: }
1364: $out = '<span>' # Start cheatsheet
1365: .$addOther
1366: .'<span>'
1367: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1368: .'</span> <span>'
1369: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1370: .'</span>';
1371: unless ($not_author) {
1372: $out .= '<span>'
1373: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1374: .'</span> <span>'
1375: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1376: .'</span>';
1377: }
1378: $out .= '</span>'; # End cheatsheet
1379: return $out;
1380: }
1381:
1382: sub general_help {
1383: my $helptopic='Student_Intro';
1384: if ($env{'request.role'}=~/^(ca|au)/) {
1385: $helptopic='Authoring_Intro';
1386: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1387: $helptopic='Course_Coordination_Intro';
1388: } elsif ($env{'request.role'}=~/^dc/) {
1389: $helptopic='Domain_Coordination_Intro';
1390: }
1391: return $helptopic;
1392: }
1393:
1394: sub update_help_link {
1395: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1396: my $origurl = $ENV{'REQUEST_URI'};
1397: $origurl=~s|^/~|/priv/|;
1398: my $timestamp = time;
1399: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1400: $$datum = &escape($$datum);
1401: }
1402:
1403: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1404: my $output .= <<"ENDOUTPUT";
1405: <script type="text/javascript">
1406: // <![CDATA[
1407: banner_link = '$banner_link';
1408: // ]]>
1409: </script>
1410: ENDOUTPUT
1411: return $output;
1412: }
1413:
1414: # now just updates the help link and generates a blue icon
1415: sub help_open_menu {
1416: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target)
1417: = @_;
1418: $stayOnPage = 1;
1419: my $output;
1420: if ($component_help) {
1421: if (!$text) {
1422: $output=&help_open_topic($component_help,undef,$stayOnPage,
1423: $width,$height,'',$links_target);
1424: } else {
1425: my $help_text;
1426: $help_text=&unescape($topic);
1427: $output='<table><tr><td>'.
1428: &help_open_topic($component_help,$help_text,$stayOnPage,
1429: $width,$height,'',$links_target).'</td></tr></table>';
1430: }
1431: }
1432: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1433: return $output.$banner_link;
1434: }
1435:
1436: sub top_nav_help {
1437: my ($text,$linkattr) = @_;
1438: $text = &mt($text);
1439: my $stay_on_page = 1;
1440:
1441: my ($link,$banner_link);
1442: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1443: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1444: : "javascript:helpMenu('open')";
1445: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1446: }
1447: my $title = &mt('Get help');
1448: if ($link) {
1449: return <<"END";
1450: $banner_link
1451: <a href="$link" title="$title" $linkattr>$text</a>
1452: END
1453: } else {
1454: return ' '.$text.' ';
1455: }
1456: }
1457:
1458: sub help_menu_js {
1459: my ($httphost) = @_;
1460: my $stayOnPage = 1;
1461: my $width = 620;
1462: my $height = 600;
1463: my $helptopic=&general_help();
1464: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1465: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1466: my $start_page =
1467: &Apache::loncommon::start_page('Help Menu', undef,
1468: {'frameset' => 1,
1469: 'js_ready' => 1,
1470: 'use_absolute' => $httphost,
1471: 'add_entries' => {
1472: 'border' => '0',
1473: 'rows' => "110,*",},});
1474: my $end_page =
1475: &Apache::loncommon::end_page({'frameset' => 1,
1476: 'js_ready' => 1,});
1477:
1478: my $template .= <<"ENDTEMPLATE";
1479: <script type="text/javascript">
1480: // <![CDATA[
1481: // <!-- BEGIN LON-CAPA Internal
1482: var banner_link = '';
1483: function helpMenu(target) {
1484: var caller = this;
1485: if (target == 'open') {
1486: var newWindow = null;
1487: try {
1488: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1489: }
1490: catch(error) {
1491: writeHelp(caller);
1492: return;
1493: }
1494: if (newWindow) {
1495: caller = newWindow;
1496: }
1497: }
1498: writeHelp(caller);
1499: return;
1500: }
1501: function writeHelp(caller) {
1502: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1503: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1504: caller.document.close();
1505: caller.focus();
1506: }
1507: // END LON-CAPA Internal -->
1508: // ]]>
1509: </script>
1510: ENDTEMPLATE
1511: return $template;
1512: }
1513:
1514: sub help_open_bug {
1515: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1516: unless ($env{'user.adv'}) { return ''; }
1517: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1518: $text = "" if (not defined $text);
1519: $stayOnPage=1;
1520: $width = 600 if (not defined $width);
1521: $height = 600 if (not defined $height);
1522:
1523: $topic=~s/\W+/\+/g;
1524: my $link='';
1525: my $template='';
1526: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1527: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1528: if (!$stayOnPage)
1529: {
1530: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1531: }
1532: else
1533: {
1534: $link = $url;
1535: }
1536:
1537: my $target = '_top';
1538: if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
1539: (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
1540: $target = '_blank';
1541: }
1542:
1543: # Add the text
1544: if ($text ne "")
1545: {
1546: $template .=
1547: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1548: "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1549: }
1550:
1551: # Add the graphic
1552: my $title = &mt('Report a Bug');
1553: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1554: $template .= <<"ENDTEMPLATE";
1555: <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1556: ENDTEMPLATE
1557: if ($text ne '') { $template.='</td></tr></table>' };
1558: return $template;
1559:
1560: }
1561:
1562: sub help_open_faq {
1563: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1564: unless ($env{'user.adv'}) { return ''; }
1565: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1566: $text = "" if (not defined $text);
1567: $stayOnPage=1;
1568: $width = 350 if (not defined $width);
1569: $height = 400 if (not defined $height);
1570:
1571: $topic=~s/\W+/\+/g;
1572: my $link='';
1573: my $template='';
1574: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1575: if (!$stayOnPage)
1576: {
1577: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1578: }
1579: else
1580: {
1581: $link = $url;
1582: }
1583:
1584: # Add the text
1585: if ($text ne "")
1586: {
1587: $template .=
1588: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1589: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1590: }
1591:
1592: # Add the graphic
1593: my $title = &mt('View the FAQ');
1594: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1595: $template .= <<"ENDTEMPLATE";
1596: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1597: ENDTEMPLATE
1598: if ($text ne '') { $template.='</td></tr></table>' };
1599: return $template;
1600:
1601: }
1602:
1603: ###############################################################
1604: ###############################################################
1605:
1606: =pod
1607:
1608: =item * &change_content_javascript():
1609:
1610: This and the next function allow you to create small sections of an
1611: otherwise static HTML page that you can update on the fly with
1612: Javascript, even in Netscape 4.
1613:
1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1615: must be written to the HTML page once. It will prove the Javascript
1616: function "change(name, content)". Calling the change function with the
1617: name of the section
1618: you want to update, matching the name passed to C<changable_area>, and
1619: the new content you want to put in there, will put the content into
1620: that area.
1621:
1622: B<Note>: Netscape 4 only reserves enough space for the changable area
1623: to contain room for the original contents. You need to "make space"
1624: for whatever changes you wish to make, and be B<sure> to check your
1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1626: it's adequate for updating a one-line status display, but little more.
1627: This script will set the space to 100% width, so you only need to
1628: worry about height in Netscape 4.
1629:
1630: Modern browsers are much less limiting, and if you can commit to the
1631: user not using Netscape 4, this feature may be used freely with
1632: pretty much any HTML.
1633:
1634: =cut
1635:
1636: sub change_content_javascript {
1637: # If we're on Netscape 4, we need to use Layer-based code
1638: if ($env{'browser.type'} eq 'netscape' &&
1639: $env{'browser.version'} =~ /^4\./) {
1640: return (<<NETSCAPE4);
1641: function change(name, content) {
1642: doc = document.layers[name+"___escape"].layers[0].document;
1643: doc.open();
1644: doc.write(content);
1645: doc.close();
1646: }
1647: NETSCAPE4
1648: } else {
1649: # Otherwise, we need to use semi-standards-compliant code
1650: # (technically, "innerHTML" isn't standard but the equivalent
1651: # is really scary, and every useful browser supports it
1652: return (<<DOMBASED);
1653: function change(name, content) {
1654: element = document.getElementById(name);
1655: element.innerHTML = content;
1656: }
1657: DOMBASED
1658: }
1659: }
1660:
1661: =pod
1662:
1663: =item * &changable_area($name,$origContent):
1664:
1665: This provides a "changable area" that can be modified on the fly via
1666: the Javascript code provided in C<change_content_javascript>. $name is
1667: the name you will use to reference the area later; do not repeat the
1668: same name on a given HTML page more then once. $origContent is what
1669: the area will originally contain, which can be left blank.
1670:
1671: =cut
1672:
1673: sub changable_area {
1674: my ($name, $origContent) = @_;
1675:
1676: if ($env{'browser.type'} eq 'netscape' &&
1677: $env{'browser.version'} =~ /^4\./) {
1678: # If this is netscape 4, we need to use the Layer tag
1679: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1680: } else {
1681: return "<span id='$name'>$origContent</span>";
1682: }
1683: }
1684:
1685: =pod
1686:
1687: =item * &viewport_geometry_js
1688:
1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1690:
1691: =cut
1692:
1693:
1694: sub viewport_geometry_js {
1695: return <<"GEOMETRY";
1696: var Geometry = {};
1697: function init_geometry() {
1698: if (Geometry.init) { return };
1699: Geometry.init=1;
1700: if (window.innerHeight) {
1701: Geometry.getViewportHeight = function() { return window.innerHeight; };
1702: Geometry.getViewportWidth = function() { return window.innerWidth; };
1703: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1704: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1705: }
1706: else if (document.documentElement && document.documentElement.clientHeight) {
1707: Geometry.getViewportHeight =
1708: function() { return document.documentElement.clientHeight; };
1709: Geometry.getViewportWidth =
1710: function() { return document.documentElement.clientWidth; };
1711:
1712: Geometry.getHorizontalScroll =
1713: function() { return document.documentElement.scrollLeft; };
1714: Geometry.getVerticalScroll =
1715: function() { return document.documentElement.scrollTop; };
1716: }
1717: else if (document.body.clientHeight) {
1718: Geometry.getViewportHeight =
1719: function() { return document.body.clientHeight; };
1720: Geometry.getViewportWidth =
1721: function() { return document.body.clientWidth; };
1722: Geometry.getHorizontalScroll =
1723: function() { return document.body.scrollLeft; };
1724: Geometry.getVerticalScroll =
1725: function() { return document.body.scrollTop; };
1726: }
1727: }
1728:
1729: GEOMETRY
1730: }
1731:
1732: =pod
1733:
1734: =item * &viewport_size_js()
1735:
1736: 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.
1737:
1738: =cut
1739:
1740: sub viewport_size_js {
1741: my $geometry = &viewport_geometry_js();
1742: return <<"DIMS";
1743:
1744: $geometry
1745:
1746: function getViewportDims(width,height) {
1747: init_geometry();
1748: width.value = Geometry.getViewportWidth();
1749: height.value = Geometry.getViewportHeight();
1750: return;
1751: }
1752:
1753: DIMS
1754: }
1755:
1756: =pod
1757:
1758: =item * &resize_textarea_js()
1759:
1760: emits the needed javascript to resize a textarea to be as big as possible
1761:
1762: creates a function resize_textrea that takes two IDs first should be
1763: the id of the element to resize, second should be the id of a div that
1764: surrounds everything that comes after the textarea, this routine needs
1765: to be attached to the <body> for the onload and onresize events.
1766:
1767: =back
1768:
1769: =cut
1770:
1771: sub resize_textarea_js {
1772: my $geometry = &viewport_geometry_js();
1773: return <<"RESIZE";
1774: <script type="text/javascript">
1775: // <![CDATA[
1776: $geometry
1777:
1778: function getX(element) {
1779: var x = 0;
1780: while (element) {
1781: x += element.offsetLeft;
1782: element = element.offsetParent;
1783: }
1784: return x;
1785: }
1786: function getY(element) {
1787: var y = 0;
1788: while (element) {
1789: y += element.offsetTop;
1790: element = element.offsetParent;
1791: }
1792: return y;
1793: }
1794:
1795:
1796: function resize_textarea(textarea_id,bottom_id) {
1797: init_geometry();
1798: var textarea = document.getElementById(textarea_id);
1799: //alert(textarea);
1800:
1801: var textarea_top = getY(textarea);
1802: var textarea_height = textarea.offsetHeight;
1803: var bottom = document.getElementById(bottom_id);
1804: var bottom_top = getY(bottom);
1805: var bottom_height = bottom.offsetHeight;
1806: var window_height = Geometry.getViewportHeight();
1807: var fudge = 23;
1808: var new_height = window_height-fudge-textarea_top-bottom_height;
1809: if (new_height < 300) {
1810: new_height = 300;
1811: }
1812: textarea.style.height=new_height+'px';
1813: }
1814: // ]]>
1815: </script>
1816: RESIZE
1817:
1818: }
1819:
1820: sub colorfuleditor_js {
1821: my $browse_or_search;
1822: my $respath;
1823: my ($cnum,$cdom) = &crsauthor_url();
1824: if ($cnum) {
1825: $respath = "/res/$cdom/$cnum/";
1826: my %js_lt = &Apache::lonlocal::texthash(
1827: sunm => 'Sub-directory name',
1828: save => 'Save page to make this permanent',
1829: );
1830: &js_escape(\%js_lt);
1831: my $showfile_js = &show_crsfiles_js();
1832: $browse_or_search = <<"END";
1833:
1834: $showfile_js
1835:
1836: function toggleChooser(form,element,titleid,only,search) {
1837: var disp = 'none';
1838: if (document.getElementById('chooser_'+element)) {
1839: var curr = document.getElementById('chooser_'+element).style.display;
1840: if (curr == 'none') {
1841: disp='inline';
1842: if (form.elements['chooser_'+element].length) {
1843: for (var i=0; i<form.elements['chooser_'+element].length; i++) {
1844: form.elements['chooser_'+element][i].checked = false;
1845: }
1846: }
1847: toggleResImport(form,element);
1848: }
1849: document.getElementById('chooser_'+element).style.display = disp;
1850: var dirsel = '';
1851: var filesel = '';
1852: if (document.getElementById('chooser_'+element+'_crsres')) {
1853: var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
1854: if (currcrsres == 'none') {
1855: dirsel = 'coursepath_'+element;
1856: var filesel = 'coursefile_'+element;
1857: var include;
1858: if (document.getElementById('crsres_include_'+element)) {
1859: include = document.getElementById('crsres_include_'+element).value;
1860: }
1861: populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1862: }
1863: }
1864: if (document.getElementById('chooser_'+element+'_upload')) {
1865: var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
1866: if (currcrsupload == 'none') {
1867: dirsel = 'crsauthorpath_'+element;
1868: filesel = '';
1869: populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1870: }
1871: }
1872: }
1873: }
1874:
1875: function toggleCrsFile(form,element) {
1876: if (document.getElementById('chooser_'+element+'_crsres')) {
1877: var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
1878: if (curr == 'none') {
1879: if (document.getElementById('coursepath_'+element)) {
1880: var numdirs;
1881: if (document.getElementById('coursepath_'+element).length) {
1882: numdirs = document.getElementById('coursepath_'+element).length;
1883: }
1884: if ((document.getElementById('hascrsres_'+element)) &&
1885: (document.getElementById('nocrsres_'+element))) {
1886: if (numdirs) {
1887: document.getElementById('hascrsres_'+element).style.display='inline-block';
1888: document.getElementById('nocrsres_'+element).style.display='none';
1889: } else {
1890: document.getElementById('hascrsres_'+element).style.display='none';
1891: document.getElementById('nocrsres_'+element).style.display='inline-block';
1892: }
1893: }
1894: form.elements['coursepath_'+element].selectedIndex = 0;
1895: if (numdirs > 1) {
1896: var selelem = form.elements['coursefile_'+element];
1897: var i, len = selelem.options.length -1;
1898: if (len >=0) {
1899: for (i = len; i >= 0; i--) {
1900: selelem.remove(i);
1901: }
1902: selelem.options[0] = new Option('','');
1903: }
1904: }
1905: }
1906: }
1907: document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
1908: }
1909: if (document.getElementById('chooser_'+element+'_upload')) {
1910: document.getElementById('chooser_'+element+'_upload').style.display = 'none';
1911: if (document.getElementById('uploadcrsres_'+element)) {
1912: document.getElementById('uploadcrsres_'+element).value = '';
1913: }
1914: }
1915: return;
1916: }
1917:
1918: function toggleCrsUpload(form,element) {
1919: if (document.getElementById('chooser_'+element+'_crsres')) {
1920: document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
1921: }
1922: if (document.getElementById('chooser_'+element+'_upload')) {
1923: var curr = document.getElementById('chooser_'+element+'_upload').style.display;
1924: if (curr == 'none') {
1925: form.elements['newsubdir_'+element][0].checked = true;
1926: toggleNewsubdir(form,element);
1927: document.getElementById('chooser_'+element+'_upload').style.display = 'block';
1928: if (document.getElementById('uploadcrsres_'+element)) {
1929: document.getElementById('uploadcrsres_'+element).value = '';
1930: }
1931: }
1932: }
1933: return;
1934: }
1935:
1936: function toggleResImport(form,element) {
1937: var choices = new Array('crsres','upload');
1938: for (var i=0; i<choices.length; i++) {
1939: if (document.getElementById('chooser_'+element+'_'+choices[i])) {
1940: document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
1941: }
1942: }
1943: }
1944:
1945: function toggleNewsubdir(form,element) {
1946: var newsub = form.elements['newsubdir_'+element];
1947: if (newsub) {
1948: if (newsub.length) {
1949: for (var j=0; j<newsub.length; j++) {
1950: if (newsub[j].checked) {
1951: if (document.getElementById('newsubdirname_'+element)) {
1952: if (newsub[j].value == '1') {
1953: document.getElementById('newsubdirname_'+element).type = "text";
1954: if (document.getElementById('newsubdir_'+element)) {
1955: document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
1956: }
1957: } else {
1958: document.getElementById('newsubdirname_'+element).type = "hidden";
1959: document.getElementById('newsubdirname_'+element).value = "";
1960: document.getElementById('newsubdir_'+element).innerHTML = "";
1961: }
1962: }
1963: break;
1964: }
1965: }
1966: }
1967: }
1968: }
1969:
1970: function updateCrsFile(form,element) {
1971: var directory = form.elements['coursepath_'+element];
1972: var filename = form.elements['coursefile_'+element];
1973: var path = directory.options[directory.selectedIndex].value;
1974: var file = filename.options[filename.selectedIndex].value;
1975: if (file != '') {
1976: form.elements[element].value = '$respath';
1977: if (path == '/') {
1978: form.elements[element].value += file;
1979: } else {
1980: form.elements[element].value += path+'/'+file;
1981: }
1982: unClean();
1983: if (document.getElementById('previewimg_'+element)) {
1984: document.getElementById('previewimg_'+element).src = form.elements[element].value;
1985: var newsrc = document.getElementById('previewimg_'+element).src;
1986: }
1987: if (document.getElementById('showimg_'+element)) {
1988: document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
1989: }
1990: }
1991: toggleChooser(form,element);
1992: return;
1993: }
1994:
1995: function uploadDone(suffix,name) {
1996: if (name) {
1997: document.forms["lonhomework"].elements[suffix].value = name;
1998: unClean();
1999: toggleChooser(document.forms["lonhomework"],suffix);
2000: }
2001: }
2002:
2003: \$(document).ready(function(){
2004:
2005: \$(document).delegate('form :submit', 'click', function( event ) {
2006: if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
2007: var buttonId = this.id;
2008: var suffix = buttonId.toString();
2009: suffix = suffix.replace(/^crsupload_/,'');
2010: event.preventDefault();
2011: document.lonhomework.target = 'crsupload_target_'+suffix;
2012: document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
2013: \$(this.form).submit();
2014: document.lonhomework.target = '';
2015: if (document.getElementById('crsuploadto_'+suffix)) {
2016: document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
2017: }
2018: return false;
2019: }
2020: });
2021: });
2022: END
2023: }
2024: return <<"COLORFULEDIT"
2025: <script type="text/javascript">
2026: // <![CDATA[>
2027: function fold_box(curDepth, lastresource){
2028:
2029: // we need a list because there can be several blocks you need to fold in one tag
2030: var block = document.getElementsByName('foldblock_'+curDepth);
2031: // but there is only one folding button per tag
2032: var foldbutton = document.getElementById('folding_btn_'+curDepth);
2033:
2034: if(block.item(0).style.display == 'none'){
2035:
2036: foldbutton.value = '@{[&mt("Hide")]}';
2037: for (i = 0; i < block.length; i++){
2038: block.item(i).style.display = '';
2039: }
2040: }else{
2041:
2042: foldbutton.value = '@{[&mt("Show")]}';
2043: for (i = 0; i < block.length; i++){
2044: // block.item(i).style.visibility = 'collapse';
2045: block.item(i).style.display = 'none';
2046: }
2047: };
2048: saveState(lastresource);
2049: }
2050:
2051: function saveState (lastresource) {
2052:
2053: var tag_list = getTagList();
2054: if(tag_list != null){
2055: var timestamp = new Date().getTime();
2056: var key = lastresource;
2057:
2058: // the value pattern is: 'time;key1,value1;key2,value2; ... '
2059: // starting with timestamp
2060: var value = timestamp+';';
2061:
2062: // building the list of key-value pairs
2063: for(var i = 0; i < tag_list.length; i++){
2064: value += tag_list[i]+',';
2065: value += document.getElementsByName(tag_list[i])[0].style.display+';';
2066: }
2067:
2068: // only iterate whole storage if nothing to override
2069: if(localStorage.getItem(key) == null){
2070:
2071: // prevent storage from growing large
2072: if(localStorage.length > 50){
2073: var regex_getTimestamp = /^(?:\d)+;/;
2074: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
2075: var oldest_key;
2076:
2077: for(var i = 1; i < localStorage.length; i++){
2078: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
2079: oldest_key = localStorage.key(i);
2080: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
2081: }
2082: }
2083: localStorage.removeItem(oldest_key);
2084: }
2085: }
2086: localStorage.setItem(key,value);
2087: }
2088: }
2089:
2090: // restore folding status of blocks (on page load)
2091: function restoreState (lastresource) {
2092: if(localStorage.getItem(lastresource) != null){
2093: var key = lastresource;
2094: var value = localStorage.getItem(key);
2095: var regex_delTimestamp = /^\d+;/;
2096:
2097: value.replace(regex_delTimestamp, '');
2098:
2099: var valueArr = value.split(';');
2100: var pairs;
2101: var elements;
2102: for (var i = 0; i < valueArr.length; i++){
2103: pairs = valueArr[i].split(',');
2104: elements = document.getElementsByName(pairs[0]);
2105:
2106: for (var j = 0; j < elements.length; j++){
2107: elements[j].style.display = pairs[1];
2108: if (pairs[1] == "none"){
2109: var regex_id = /([_\\d]+)\$/;
2110: regex_id.exec(pairs[0]);
2111: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
2112: }
2113: }
2114: }
2115: }
2116: }
2117:
2118: function getTagList () {
2119:
2120: var stringToSearch = document.lonhomework.innerHTML;
2121:
2122: var ret = new Array();
2123: var regex_findBlock = /(foldblock_.*?)"/g;
2124: var tag_list = stringToSearch.match(regex_findBlock);
2125:
2126: if(tag_list != null){
2127: for(var i = 0; i < tag_list.length; i++){
2128: ret.push(tag_list[i].replace(/"/, ''));
2129: }
2130: }
2131: return ret;
2132: }
2133:
2134: function saveScrollPosition (resource) {
2135: var tag_list = getTagList();
2136:
2137: // we dont always want to jump to the first block
2138: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
2139: if(\$(window).scrollTop() > 170){
2140: if(tag_list != null){
2141: var result;
2142: for(var i = 0; i < tag_list.length; i++){
2143: if(isElementInViewport(tag_list[i])){
2144: result += tag_list[i]+';';
2145: }
2146: }
2147: sessionStorage.setItem('anchor_'+resource, result);
2148: }
2149: } else {
2150: // we dont need to save zero, just delete the item to leave everything tidy
2151: sessionStorage.removeItem('anchor_'+resource);
2152: }
2153: }
2154:
2155: function restoreScrollPosition(resource){
2156:
2157: var elem = sessionStorage.getItem('anchor_'+resource);
2158: if(elem != null){
2159: var tag_list = elem.split(';');
2160: var elem_list;
2161:
2162: for(var i = 0; i < tag_list.length; i++){
2163: elem_list = document.getElementsByName(tag_list[i]);
2164:
2165: if(elem_list.length > 0){
2166: elem = elem_list[0];
2167: break;
2168: }
2169: }
2170: elem.scrollIntoView();
2171: }
2172: }
2173:
2174: function isElementInViewport(el) {
2175:
2176: // change to last element instead of first
2177: var elem = document.getElementsByName(el);
2178: var rect = elem[0].getBoundingClientRect();
2179:
2180: return (
2181: rect.top >= 0 &&
2182: rect.left >= 0 &&
2183: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
2184: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
2185: );
2186: }
2187:
2188: function autosize(depth){
2189: var cmInst = window['cm'+depth];
2190: var fitsizeButton = document.getElementById('fitsize'+depth);
2191:
2192: // is fixed size, switching to dynamic
2193: if (sessionStorage.getItem("autosized_"+depth) == null) {
2194: cmInst.setSize("","auto");
2195: fitsizeButton.value = "@{[&mt('Fixed size')]}";
2196: sessionStorage.setItem("autosized_"+depth, "yes");
2197:
2198: // is dynamic size, switching to fixed
2199: } else {
2200: cmInst.setSize("","300px");
2201: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
2202: sessionStorage.removeItem("autosized_"+depth);
2203: }
2204: }
2205:
2206: $browse_or_search
2207:
2208: // ]]>
2209: </script>
2210: COLORFULEDIT
2211: }
2212:
2213: sub xmleditor_js {
2214: return <<XMLEDIT
2215: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
2216: <script type="text/javascript">
2217: // <![CDATA[>
2218:
2219: function saveScrollPosition (resource) {
2220:
2221: var scrollPos = \$(window).scrollTop();
2222: sessionStorage.setItem(resource,scrollPos);
2223: }
2224:
2225: function restoreScrollPosition(resource){
2226:
2227: var scrollPos = sessionStorage.getItem(resource);
2228: \$(window).scrollTop(scrollPos);
2229: }
2230:
2231: // unless internet explorer
2232: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
2233:
2234: \$(document).ready(function() {
2235: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
2236: });
2237: }
2238:
2239: // inserts text at cursor position into codemirror (xml editor only)
2240: function insertText(text){
2241: cm.focus();
2242: var curPos = cm.getCursor();
2243: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2244: }
2245: // ]]>
2246: </script>
2247: XMLEDIT
2248: }
2249:
2250: sub insert_folding_button {
2251: my $curDepth = $Apache::lonxml::curdepth;
2252: my $lastresource = $env{'request.ambiguous'};
2253:
2254: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2255: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2256: }
2257:
2258: sub crsauthor_url {
2259: my ($url) = @_;
2260: if ($url eq '') {
2261: $url = $ENV{'REQUEST_URI'};
2262: }
2263: my ($cnum,$cdom);
2264: if ($env{'request.course.id'}) {
2265: my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
2266: if ($audom ne '' && $auname ne '') {
2267: if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
2268: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
2269: $cnum = $auname;
2270: $cdom = $audom;
2271: }
2272: }
2273: }
2274: return ($cnum,$cdom);
2275: }
2276:
2277: sub import_crsauthor_form {
2278: my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
2279: return (0) unless ($env{'request.course.id'});
2280: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2281: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2282: my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
2283: return (0) unless (($cnum ne '') && ($cdom ne ''));
2284: my @ids=&Apache::lonnet::current_machine_ids();
2285: my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
2286:
2287: if (grep(/^\Q$crshome\E$/,@ids)) {
2288: $is_home = 1;
2289: }
2290: $toppath = "/priv/$cdom/$cnum";
2291: my $nonemptydir = 1;
2292: my $js_only;
2293: if ($only) {
2294: map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
2295: $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
2296: }
2297: $exclude = &Apache::lonnet::priv_exclude();
2298: &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
2299: my $numdirs = scalar(keys(%files));
2300: my %lt = &Apache::lonlocal::texthash (
2301: fnam => 'Filename',
2302: dire => 'Directory',
2303: se => 'Select',
2304: );
2305: $output = $lt{'dire'}.': '.
2306: '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
2307: 'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
2308: '<option value="" selected="selected">'.$lt{'se'}.'</option>';
2309: if ($files{'/'}) {
2310: $output .= '<option value="/">/</option>'."\n";
2311: }
2312: foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
2313: next if ($key eq '/');
2314: $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
2315: }
2316: $output .= '</select><br />'."\n".
2317: $lt{'fnam'}.': <select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
2318: '<option value="" selected="selected"></option>'."\n".
2319: '</select>'."\n".
2320: '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
2321: return ($numdirs,$output);
2322: }
2323:
2324: sub show_crsfiles_js {
2325: my $excluderef = &Apache::lonnet::priv_exclude();
2326: my $se = &js_escape(&mt('Select'));
2327: my $exclude;
2328: if (ref($excluderef) eq 'HASH') {
2329: $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
2330: }
2331: my $js = <<"END";
2332:
2333:
2334: function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
2335: var relpath = '';
2336: if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
2337: var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
2338: if (currdir == '') {
2339: if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2340: selelem = form.elements[filesel];
2341: var j, numfiles = selelem.options.length -1;
2342: if (numfiles >=0) {
2343: for (j = numfiles; j >= 0; j--) {
2344: selelem.remove(j);
2345: }
2346: }
2347: if (selelem.options.length == 0) {
2348: selelem.options[selelem.options.length] = new Option('','');
2349: selelem.selectedIndex = 0;
2350: }
2351: }
2352: return;
2353: } else {
2354: relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
2355: }
2356: }
2357: var http = new XMLHttpRequest();
2358: var url = "/adm/courseauthor";
2359: var crsrole = "$env{'request.role'}";
2360: var exclude = '';
2361: if (exc) {
2362: exclude = '$exclude';
2363: }
2364: var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
2365: http.open("POST", url, true);
2366: http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
2367: http.onreadystatechange = function() {
2368: if (http.readyState == 4 && http.status == 200) {
2369: var data = JSON.parse(http.responseText);
2370: var selelem;
2371: if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
2372: if (Array.isArray(data.dirs)) {
2373: selelem = form.elements[dirsel];
2374: var i, numdirs = selelem.options.length -1;
2375: if (numdirs >=0) {
2376: for (i = numdirs; i >= 0; i--) {
2377: selelem.remove(i);
2378: }
2379: }
2380: var len = data.dirs.length;
2381: if (len) {
2382: selelem.options[selelem.options.length] = new Option('$se','');
2383: var j;
2384: for (j = 0; j < len; j++) {
2385: selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
2386: }
2387: selelem.selectedIndex = 0;
2388: }
2389: if (!setfile) {
2390: if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2391: selelem = form.elements[filesel];
2392: var j, numfiles = selelem.options.length -1;
2393: if (numfiles >=0) {
2394: for (j = numfiles; j >= 0; j--) {
2395: selelem.remove(j);
2396: }
2397: }
2398: if (selelem.options.length == 0) {
2399: selelem.options[selelem.options.length] = new Option('','');
2400: selelem.selectedIndex = 0;
2401: }
2402: }
2403: }
2404: }
2405: }
2406: if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
2407: selelem = form.elements[filesel];
2408: var i, numfiles = selelem.options.length -1;
2409: if (numfiles >=0) {
2410: for (i = numfiles; i >= 0; i--) {
2411: selelem.remove(i);
2412: }
2413: }
2414: var x;
2415: for (x in data.files) {
2416: if (Array.isArray(data.files[x])) {
2417: if (data.files[x].length > 1) {
2418: selelem.options[selelem.options.length] = new Option('$se','');
2419: }
2420: var len = data.files[x].length;
2421: if (len) {
2422: var k;
2423: for (k = 0; k < len; k++) {
2424: selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
2425: }
2426: selelem.selectedIndex = 0;
2427: }
2428: }
2429: }
2430: if (selelem.options.length == 0) {
2431: selelem.options[selelem.options.length] = new Option('','');
2432: selelem.selectedIndex = 0;
2433: }
2434: }
2435: }
2436: }
2437: http.send(params);
2438: }
2439: END
2440: }
2441:
2442: =pod
2443:
2444: =head1 Excel and CSV file utility routines
2445:
2446: =cut
2447:
2448: ###############################################################
2449: ###############################################################
2450:
2451: =pod
2452:
2453: =over 4
2454:
2455: =item * &csv_translate($text)
2456:
2457: Translate $text to allow it to be output as a 'comma separated values'
2458: format.
2459:
2460: =cut
2461:
2462: ###############################################################
2463: ###############################################################
2464: sub csv_translate {
2465: my $text = shift;
2466: $text =~ s/\"/\"\"/g;
2467: $text =~ s/\n/ /g;
2468: return $text;
2469: }
2470:
2471: ###############################################################
2472: ###############################################################
2473:
2474: =pod
2475:
2476: =item * &define_excel_formats()
2477:
2478: Define some commonly used Excel cell formats.
2479:
2480: Currently supported formats:
2481:
2482: =over 4
2483:
2484: =item header
2485:
2486: =item bold
2487:
2488: =item h1
2489:
2490: =item h2
2491:
2492: =item h3
2493:
2494: =item h4
2495:
2496: =item i
2497:
2498: =item date
2499:
2500: =back
2501:
2502: Inputs: $workbook
2503:
2504: Returns: $format, a hash reference.
2505:
2506:
2507: =cut
2508:
2509: ###############################################################
2510: ###############################################################
2511: sub define_excel_formats {
2512: my ($workbook) = @_;
2513: my $format;
2514: $format->{'header'} = $workbook->add_format(bold => 1,
2515: bottom => 1,
2516: align => 'center');
2517: $format->{'bold'} = $workbook->add_format(bold=>1);
2518: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2519: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2520: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2521: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2522: $format->{'i'} = $workbook->add_format(italic=>1);
2523: $format->{'date'} = $workbook->add_format(num_format=>
2524: 'mm/dd/yyyy hh:mm:ss');
2525: return $format;
2526: }
2527:
2528: ###############################################################
2529: ###############################################################
2530:
2531: =pod
2532:
2533: =item * &create_workbook()
2534:
2535: Create an Excel worksheet. If it fails, output message on the
2536: request object and return undefs.
2537:
2538: Inputs: Apache request object
2539:
2540: Returns (undef) on failure,
2541: Excel worksheet object, scalar with filename, and formats
2542: from &Apache::loncommon::define_excel_formats on success
2543:
2544: =cut
2545:
2546: ###############################################################
2547: ###############################################################
2548: sub create_workbook {
2549: my ($r) = @_;
2550: #
2551: # Create the excel spreadsheet
2552: my $filename = '/prtspool/'.
2553: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2554: time.'_'.rand(1000000000).'.xls';
2555: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2556: if (! defined($workbook)) {
2557: $r->log_error("Error creating excel spreadsheet $filename: $!");
2558: $r->print(
2559: '<p class="LC_error">'
2560: .&mt('Problems occurred in creating the new Excel file.')
2561: .' '.&mt('This error has been logged.')
2562: .' '.&mt('Please alert your LON-CAPA administrator.')
2563: .'</p>'
2564: );
2565: return (undef);
2566: }
2567: #
2568: $workbook->set_tempdir(LONCAPA::tempdir());
2569: #
2570: my $format = &Apache::loncommon::define_excel_formats($workbook);
2571: return ($workbook,$filename,$format);
2572: }
2573:
2574: ###############################################################
2575: ###############################################################
2576:
2577: =pod
2578:
2579: =item * &create_text_file()
2580:
2581: Create a file to write to and eventually make available to the user.
2582: If file creation fails, outputs an error message on the request object and
2583: return undefs.
2584:
2585: Inputs: Apache request object, and file suffix
2586:
2587: Returns (undef) on failure,
2588: Filehandle and filename on success.
2589:
2590: =cut
2591:
2592: ###############################################################
2593: ###############################################################
2594: sub create_text_file {
2595: my ($r,$suffix) = @_;
2596: if (! defined($suffix)) { $suffix = 'txt'; };
2597: my $fh;
2598: my $filename = '/prtspool/'.
2599: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2600: time.'_'.rand(1000000000).'.'.$suffix;
2601: $fh = Apache::File->new('>/home/httpd'.$filename);
2602: if (! defined($fh)) {
2603: $r->log_error("Couldn't open $filename for output $!");
2604: $r->print(
2605: '<p class="LC_error">'
2606: .&mt('Problems occurred in creating the output file.')
2607: .' '.&mt('This error has been logged.')
2608: .' '.&mt('Please alert your LON-CAPA administrator.')
2609: .'</p>'
2610: );
2611: }
2612: return ($fh,$filename)
2613: }
2614:
2615:
2616: =pod
2617:
2618: =back
2619:
2620: =cut
2621:
2622: ###############################################################
2623: ## Home server <option> list generating code ##
2624: ###############################################################
2625:
2626: # ------------------------------------------
2627:
2628: sub domain_select {
2629: my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
2630: my @possdoms;
2631: if (ref($incdoms) eq 'ARRAY') {
2632: @possdoms = @{$incdoms};
2633: } else {
2634: @possdoms = &Apache::lonnet::all_domains();
2635: }
2636:
2637: my %domains=map {
2638: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2639: } @possdoms;
2640:
2641: if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
2642: foreach my $dom (@{$excdoms}) {
2643: delete($domains{$dom});
2644: }
2645: }
2646:
2647: if ($multiple) {
2648: $domains{''}=&mt('Any domain');
2649: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2650: return &multiple_select_form($name,$value,4,\%domains);
2651: } else {
2652: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2653: return &select_form($name,$value,\%domains);
2654: }
2655: }
2656:
2657: #-------------------------------------------
2658:
2659: =pod
2660:
2661: =head1 Routines for form select boxes
2662:
2663: =over 4
2664:
2665: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2666:
2667: Returns a string containing a <select> element int multiple mode
2668:
2669:
2670: Args:
2671: $name - name of the <select> element
2672: $value - scalar or array ref of values that should already be selected
2673: $size - number of rows long the select element is
2674: $hash - the elements should be 'option' => 'shown text'
2675: (shown text should already have been &mt())
2676: $order - (optional) array ref of the order to show the elements in
2677:
2678: =cut
2679:
2680: #-------------------------------------------
2681: sub multiple_select_form {
2682: my ($name,$value,$size,$hash,$order)=@_;
2683: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2684: my $output='';
2685: if (! defined($size)) {
2686: $size = 4;
2687: if (scalar(keys(%$hash))<4) {
2688: $size = scalar(keys(%$hash));
2689: }
2690: }
2691: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2692: my @order;
2693: if (ref($order) eq 'ARRAY') {
2694: @order = @{$order};
2695: } else {
2696: @order = sort(keys(%$hash));
2697: }
2698: if (exists($$hash{'select_form_order'})) {
2699: @order = @{$$hash{'select_form_order'}};
2700: }
2701:
2702: foreach my $key (@order) {
2703: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2704: $output.='selected="selected" ' if ($selected{$key});
2705: $output.='>'.$hash->{$key}."</option>\n";
2706: }
2707: $output.="</select>\n";
2708: return $output;
2709: }
2710:
2711: #-------------------------------------------
2712:
2713: =pod
2714:
2715: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2716:
2717: Returns a string containing a <select name='$name' size='1'> form to
2718: allow a user to select options from a ref to a hash containing:
2719: option_name => displayed text. An optional $onchange can include
2720: a javascript onchange item, e.g., onchange="this.form.submit();".
2721: An optional arg -- $readonly -- if true will cause the select form
2722: to be disabled, e.g., for the case where an instructor has a section-
2723: specific role, and is viewing/modifying parameters.
2724:
2725: See lonrights.pm for an example invocation and use.
2726:
2727: =cut
2728:
2729: #-------------------------------------------
2730: sub select_form {
2731: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2732: return unless (ref($hashref) eq 'HASH');
2733: if ($onchange) {
2734: $onchange = ' onchange="'.$onchange.'"';
2735: }
2736: my $disabled;
2737: if ($readonly) {
2738: $disabled = ' disabled="disabled"';
2739: }
2740: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2741: my @keys;
2742: if (exists($hashref->{'select_form_order'})) {
2743: @keys=@{$hashref->{'select_form_order'}};
2744: } else {
2745: @keys=sort(keys(%{$hashref}));
2746: }
2747: foreach my $key (@keys) {
2748: $selectform.=
2749: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2750: ($key eq $def ? 'selected="selected" ' : '').
2751: ">".$hashref->{$key}."</option>\n";
2752: }
2753: $selectform.="</select>";
2754: return $selectform;
2755: }
2756:
2757: # For display filters
2758:
2759: sub display_filter {
2760: my ($context) = @_;
2761: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2762: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2763: my $phraseinput = 'hidden';
2764: my $includeinput = 'hidden';
2765: my ($checked,$includetypestext);
2766: if ($env{'form.displayfilter'} eq 'containing') {
2767: $phraseinput = 'text';
2768: if ($context eq 'parmslog') {
2769: $includeinput = 'checkbox';
2770: if ($env{'form.includetypes'}) {
2771: $checked = ' checked="checked"';
2772: }
2773: $includetypestext = &mt('Include parameter types');
2774: }
2775: } else {
2776: $includetypestext = ' ';
2777: }
2778: my ($additional,$secondid,$thirdid);
2779: if ($context eq 'parmslog') {
2780: $additional =
2781: '<label><input type="'.$includeinput.'" name="includetypes"'.
2782: $checked.' name="includetypes" value="1" id="includetypes" />'.
2783: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2784: '</label>';
2785: $secondid = 'includetypes';
2786: $thirdid = 'includetypestext';
2787: }
2788: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2789: '$secondid','$thirdid')";
2790: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2791: &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
2792: (&mt('all'),10,20,50,100,1000,10000))).
2793: '</label></span> <span class="LC_nobreak">'.
2794: &mt('Filter: [_1]',
2795: &select_form($env{'form.displayfilter'},
2796: 'displayfilter',
2797: {'currentfolder' => 'Current folder/page',
2798: 'containing' => 'Containing phrase',
2799: 'none' => 'None'},$onchange)).' '.
2800: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2801: &HTML::Entities::encode($env{'form.containingphrase'}).
2802: '" />'.$additional;
2803: }
2804:
2805: sub display_filter_js {
2806: my $includetext = &mt('Include parameter types');
2807: return <<"ENDJS";
2808:
2809: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2810: var firstType = 'hidden';
2811: if (setter.options[setter.selectedIndex].value == 'containing') {
2812: firstType = 'text';
2813: }
2814: firstObject = document.getElementById(firstid);
2815: if (typeof(firstObject) == 'object') {
2816: if (firstObject.type != firstType) {
2817: changeInputType(firstObject,firstType);
2818: }
2819: }
2820: if (context == 'parmslog') {
2821: var secondType = 'hidden';
2822: if (firstType == 'text') {
2823: secondType = 'checkbox';
2824: }
2825: secondObject = document.getElementById(secondid);
2826: if (typeof(secondObject) == 'object') {
2827: if (secondObject.type != secondType) {
2828: changeInputType(secondObject,secondType);
2829: }
2830: }
2831: var textItem = document.getElementById(thirdid);
2832: var currtext = textItem.innerHTML;
2833: var newtext;
2834: if (firstType == 'text') {
2835: newtext = '$includetext';
2836: } else {
2837: newtext = ' ';
2838: }
2839: if (currtext != newtext) {
2840: textItem.innerHTML = newtext;
2841: }
2842: }
2843: return;
2844: }
2845:
2846: function changeInputType(oldObject,newType) {
2847: var newObject = document.createElement('input');
2848: newObject.type = newType;
2849: if (oldObject.size) {
2850: newObject.size = oldObject.size;
2851: }
2852: if (oldObject.value) {
2853: newObject.value = oldObject.value;
2854: }
2855: if (oldObject.name) {
2856: newObject.name = oldObject.name;
2857: }
2858: if (oldObject.id) {
2859: newObject.id = oldObject.id;
2860: }
2861: oldObject.parentNode.replaceChild(newObject,oldObject);
2862: return;
2863: }
2864:
2865: ENDJS
2866: }
2867:
2868: sub gradeleveldescription {
2869: my $gradelevel=shift;
2870: my %gradelevels=(0 => 'Not specified',
2871: 1 => 'Grade 1',
2872: 2 => 'Grade 2',
2873: 3 => 'Grade 3',
2874: 4 => 'Grade 4',
2875: 5 => 'Grade 5',
2876: 6 => 'Grade 6',
2877: 7 => 'Grade 7',
2878: 8 => 'Grade 8',
2879: 9 => 'Grade 9',
2880: 10 => 'Grade 10',
2881: 11 => 'Grade 11',
2882: 12 => 'Grade 12',
2883: 13 => 'Grade 13',
2884: 14 => '100 Level',
2885: 15 => '200 Level',
2886: 16 => '300 Level',
2887: 17 => '400 Level',
2888: 18 => 'Graduate Level');
2889: return &mt($gradelevels{$gradelevel});
2890: }
2891:
2892: sub select_level_form {
2893: my ($deflevel,$name)=@_;
2894: unless ($deflevel) { $deflevel=0; }
2895: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2896: for (my $i=0; $i<=18; $i++) {
2897: $selectform.="<option value=\"$i\" ".
2898: ($i==$deflevel ? 'selected="selected" ' : '').
2899: ">".&gradeleveldescription($i)."</option>\n";
2900: }
2901: $selectform.="</select>";
2902: return $selectform;
2903: }
2904:
2905: #-------------------------------------------
2906:
2907: =pod
2908:
2909: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2910:
2911: Returns a string containing a <select name='$name' size='1'> form to
2912: allow a user to select the domain to preform an operation in.
2913: See loncreateuser.pm for an example invocation and use.
2914:
2915: If the $includeempty flag is set, it also includes an empty choice ("no domain
2916: selected");
2917:
2918: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2919:
2920: 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.
2921:
2922: The optional $incdoms is a reference to an array of domains which will be the only available options.
2923:
2924: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2925:
2926: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2927:
2928: =cut
2929:
2930: #-------------------------------------------
2931: sub select_dom_form {
2932: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2933: if ($onchange) {
2934: $onchange = ' onchange="'.$onchange.'"';
2935: }
2936: if ($disabled) {
2937: $disabled = ' disabled="disabled"';
2938: }
2939: my (@domains,%exclude);
2940: if (ref($incdoms) eq 'ARRAY') {
2941: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2942: } else {
2943: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2944: }
2945: if ($includeempty) { @domains=('',@domains); }
2946: if (ref($excdoms) eq 'ARRAY') {
2947: map { $exclude{$_} = 1; } @{$excdoms};
2948: }
2949: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2950: foreach my $dom (@domains) {
2951: next if ($exclude{$dom});
2952: $selectdomain.="<option value=\"$dom\" ".
2953: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2954: if ($showdomdesc) {
2955: if ($dom ne '') {
2956: my $domdesc = &Apache::lonnet::domain($dom,'description');
2957: if ($domdesc ne '') {
2958: $selectdomain .= ' ('.$domdesc.')';
2959: }
2960: }
2961: }
2962: $selectdomain .= "</option>\n";
2963: }
2964: $selectdomain.="</select>";
2965: return $selectdomain;
2966: }
2967:
2968: #-------------------------------------------
2969:
2970: =pod
2971:
2972: =item * &home_server_form_item($domain,$name,$defaultflag)
2973:
2974: input: 4 arguments (two required, two optional) -
2975: $domain - domain of new user
2976: $name - name of form element
2977: $default - Value of 'default' causes a default item to be first
2978: option, and selected by default.
2979: $hide - Value of 'hide' causes hiding of the name of the server,
2980: if 1 server found, or default, if 0 found.
2981: output: returns 2 items:
2982: (a) form element which contains either:
2983: (i) <select name="$name">
2984: <option value="$hostid1">$hostid $servers{$hostid}</option>
2985: <option value="$hostid2">$hostid $servers{$hostid}</option>
2986: </select>
2987: form item if there are multiple library servers in $domain, or
2988: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2989: if there is only one library server in $domain.
2990:
2991: (b) number of library servers found.
2992:
2993: See loncreateuser.pm for example of use.
2994:
2995: =cut
2996:
2997: #-------------------------------------------
2998: sub home_server_form_item {
2999: my ($domain,$name,$default,$hide) = @_;
3000: my %servers = &Apache::lonnet::get_servers($domain,'library');
3001: my $result;
3002: my $numlib = keys(%servers);
3003: if ($numlib > 1) {
3004: $result .= '<select name="'.$name.'" />'."\n";
3005: if ($default) {
3006: $result .= '<option value="default" selected="selected">'.&mt('default').
3007: '</option>'."\n";
3008: }
3009: foreach my $hostid (sort(keys(%servers))) {
3010: $result.= '<option value="'.$hostid.'">'.
3011: $hostid.' '.$servers{$hostid}."</option>\n";
3012: }
3013: $result .= '</select>'."\n";
3014: } elsif ($numlib == 1) {
3015: my $hostid;
3016: foreach my $item (keys(%servers)) {
3017: $hostid = $item;
3018: }
3019: $result .= '<input type="hidden" name="'.$name.'" value="'.
3020: $hostid.'" />';
3021: if (!$hide) {
3022: $result .= $hostid.' '.$servers{$hostid};
3023: }
3024: $result .= "\n";
3025: } elsif ($default) {
3026: $result .= '<input type="hidden" name="'.$name.
3027: '" value="default" />';
3028: if (!$hide) {
3029: $result .= &mt('default');
3030: }
3031: $result .= "\n";
3032: }
3033: return ($result,$numlib);
3034: }
3035:
3036: =pod
3037:
3038: =back
3039:
3040: =cut
3041:
3042: ###############################################################
3043: ## Decoding User Agent ##
3044: ###############################################################
3045:
3046: =pod
3047:
3048: =head1 Decoding the User Agent
3049:
3050: =over 4
3051:
3052: =item * &decode_user_agent()
3053:
3054: Inputs: $r
3055:
3056: Outputs:
3057:
3058: =over 4
3059:
3060: =item * $httpbrowser
3061:
3062: =item * $clientbrowser
3063:
3064: =item * $clientversion
3065:
3066: =item * $clientmathml
3067:
3068: =item * $clientunicode
3069:
3070: =item * $clientos
3071:
3072: =item * $clientmobile
3073:
3074: =item * $clientinfo
3075:
3076: =item * $clientosversion
3077:
3078: =back
3079:
3080: =back
3081:
3082: =cut
3083:
3084: ###############################################################
3085: ###############################################################
3086: sub decode_user_agent {
3087: my ($r)=@_;
3088: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
3089: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
3090: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
3091: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
3092: my $clientbrowser='unknown';
3093: my $clientversion='0';
3094: my $clientmathml='';
3095: my $clientunicode='0';
3096: my $clientmobile=0;
3097: my $clientosversion='';
3098: for (my $i=0;$i<=$#browsertype;$i++) {
3099: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
3100: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
3101: $clientbrowser=$bname;
3102: $httpbrowser=~/$vreg/i;
3103: $clientversion=$1;
3104: $clientmathml=($clientversion>=$minv);
3105: $clientunicode=($clientversion>=$univ);
3106: }
3107: }
3108: my $clientos='unknown';
3109: my $clientinfo;
3110: if (($httpbrowser=~/linux/i) ||
3111: ($httpbrowser=~/unix/i) ||
3112: ($httpbrowser=~/ux/i) ||
3113: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
3114: if (($httpbrowser=~/vax/i) ||
3115: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
3116: if ($httpbrowser=~/next/i) { $clientos='next'; }
3117: if (($httpbrowser=~/mac/i) ||
3118: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
3119: if ($httpbrowser=~/win/i) {
3120: $clientos='win';
3121: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
3122: $clientosversion = $1;
3123: }
3124: }
3125: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
3126: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
3127: $clientmobile=lc($1);
3128: }
3129: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
3130: $clientinfo = 'firefox-'.$1;
3131: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
3132: $clientinfo = 'chromeframe-'.$1;
3133: }
3134: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
3135: $clientunicode,$clientos,$clientmobile,$clientinfo,
3136: $clientosversion);
3137: }
3138:
3139: ###############################################################
3140: ## Authentication changing form generation subroutines ##
3141: ###############################################################
3142: ##
3143: ## All of the authform_xxxxxxx subroutines take their inputs in a
3144: ## hash, and have reasonable default values.
3145: ##
3146: ## formname = the name given in the <form> tag.
3147: #-------------------------------------------
3148:
3149: =pod
3150:
3151: =head1 Authentication Routines
3152:
3153: =over 4
3154:
3155: =item * &authform_xxxxxx()
3156:
3157: The authform_xxxxxx subroutines provide javascript and html forms which
3158: handle some of the conveniences required for authentication forms.
3159: This is not an optimal method, but it works.
3160:
3161: =over 4
3162:
3163: =item * authform_header
3164:
3165: =item * authform_authorwarning
3166:
3167: =item * authform_nochange
3168:
3169: =item * authform_kerberos
3170:
3171: =item * authform_internal
3172:
3173: =item * authform_filesystem
3174:
3175: =item * authform_lti
3176:
3177: =back
3178:
3179: See loncreateuser.pm for invocation and use examples.
3180:
3181: =cut
3182:
3183: #-------------------------------------------
3184: sub authform_header{
3185: my %in = (
3186: formname => 'cu',
3187: kerb_def_dom => '',
3188: @_,
3189: );
3190: $in{'formname'} = 'document.' . $in{'formname'};
3191: my $result='';
3192:
3193: #---------------------------------------------- Code for upper case translation
3194: my $Javascript_toUpperCase;
3195: unless ($in{kerb_def_dom}) {
3196: $Javascript_toUpperCase =<<"END";
3197: switch (choice) {
3198: case 'krb': currentform.elements[choicearg].value =
3199: currentform.elements[choicearg].value.toUpperCase();
3200: break;
3201: default:
3202: }
3203: END
3204: } else {
3205: $Javascript_toUpperCase = "";
3206: }
3207:
3208: my $radioval = "'nochange'";
3209: if (defined($in{'curr_authtype'})) {
3210: if ($in{'curr_authtype'} ne '') {
3211: $radioval = "'".$in{'curr_authtype'}."arg'";
3212: }
3213: }
3214: my $argfield = 'null';
3215: if (defined($in{'mode'})) {
3216: if ($in{'mode'} eq 'modifycourse') {
3217: if (defined($in{'curr_autharg'})) {
3218: if ($in{'curr_autharg'} ne '') {
3219: $argfield = "'$in{'curr_autharg'}'";
3220: }
3221: }
3222: }
3223: }
3224:
3225: $result.=<<"END";
3226: var current = new Object();
3227: current.radiovalue = $radioval;
3228: current.argfield = $argfield;
3229:
3230: function changed_radio(choice,currentform) {
3231: var choicearg = choice + 'arg';
3232: // If a radio button in changed, we need to change the argfield
3233: if (current.radiovalue != choice) {
3234: current.radiovalue = choice;
3235: if (current.argfield != null) {
3236: currentform.elements[current.argfield].value = '';
3237: }
3238: if (choice == 'nochange') {
3239: current.argfield = null;
3240: } else {
3241: current.argfield = choicearg;
3242: switch(choice) {
3243: case 'krb':
3244: currentform.elements[current.argfield].value =
3245: "$in{'kerb_def_dom'}";
3246: break;
3247: default:
3248: break;
3249: }
3250: }
3251: }
3252: return;
3253: }
3254:
3255: function changed_text(choice,currentform) {
3256: var choicearg = choice + 'arg';
3257: if (currentform.elements[choicearg].value !='') {
3258: $Javascript_toUpperCase
3259: // clear old field
3260: if ((current.argfield != choicearg) && (current.argfield != null)) {
3261: currentform.elements[current.argfield].value = '';
3262: }
3263: current.argfield = choicearg;
3264: }
3265: set_auth_radio_buttons(choice,currentform);
3266: return;
3267: }
3268:
3269: function set_auth_radio_buttons(newvalue,currentform) {
3270: var numauthchoices = currentform.login.length;
3271: if (typeof numauthchoices == "undefined") {
3272: return;
3273: }
3274: var i=0;
3275: while (i < numauthchoices) {
3276: if (currentform.login[i].value == newvalue) { break; }
3277: i++;
3278: }
3279: if (i == numauthchoices) {
3280: return;
3281: }
3282: current.radiovalue = newvalue;
3283: currentform.login[i].checked = true;
3284: return;
3285: }
3286: END
3287: return $result;
3288: }
3289:
3290: sub authform_authorwarning {
3291: my $result='';
3292: $result='<i>'.
3293: &mt('As a general rule, only authors or co-authors should be '.
3294: 'filesystem authenticated '.
3295: '(which allows access to the server filesystem).')."</i>\n";
3296: return $result;
3297: }
3298:
3299: sub authform_nochange {
3300: my %in = (
3301: formname => 'document.cu',
3302: kerb_def_dom => 'MSU.EDU',
3303: @_,
3304: );
3305: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3306: my $result;
3307: if (!$authnum) {
3308: $result = &mt('Under your current role you are not permitted to change login settings for this user');
3309: } else {
3310: $result = '<label>'.&mt('[_1] Do not change login data',
3311: '<input type="radio" name="login" value="nochange" '.
3312: 'checked="checked" onclick="'.
3313: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
3314: '</label>';
3315: }
3316: return $result;
3317: }
3318:
3319: sub authform_kerberos {
3320: my %in = (
3321: formname => 'document.cu',
3322: kerb_def_dom => 'MSU.EDU',
3323: kerb_def_auth => 'krb4',
3324: @_,
3325: );
3326: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
3327: $autharg,$jscall,$disabled);
3328: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3329: if ($in{'kerb_def_auth'} eq 'krb5') {
3330: $check5 = ' checked="checked"';
3331: } else {
3332: $check4 = ' checked="checked"';
3333: }
3334: if ($in{'readonly'}) {
3335: $disabled = ' disabled="disabled"';
3336: }
3337: $krbarg = $in{'kerb_def_dom'};
3338: if (defined($in{'curr_authtype'})) {
3339: if ($in{'curr_authtype'} eq 'krb') {
3340: $krbcheck = ' checked="checked"';
3341: if (defined($in{'mode'})) {
3342: if ($in{'mode'} eq 'modifyuser') {
3343: $krbcheck = '';
3344: }
3345: }
3346: if (defined($in{'curr_kerb_ver'})) {
3347: if ($in{'curr_krb_ver'} eq '5') {
3348: $check5 = ' checked="checked"';
3349: $check4 = '';
3350: } else {
3351: $check4 = ' checked="checked"';
3352: $check5 = '';
3353: }
3354: }
3355: if (defined($in{'curr_autharg'})) {
3356: $krbarg = $in{'curr_autharg'};
3357: }
3358: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3359: if (defined($in{'curr_autharg'})) {
3360: $result =
3361: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3362: $in{'curr_autharg'},$krbver);
3363: } else {
3364: $result =
3365: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3366: }
3367: return $result;
3368: }
3369: }
3370: } else {
3371: if ($authnum == 1) {
3372: $authtype = '<input type="hidden" name="login" value="krb" />';
3373: }
3374: }
3375: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3376: return;
3377: } elsif ($authtype eq '') {
3378: if (defined($in{'mode'})) {
3379: if ($in{'mode'} eq 'modifycourse') {
3380: if ($authnum == 1) {
3381: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
3382: }
3383: }
3384: }
3385: }
3386: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3387: if ($authtype eq '') {
3388: $authtype = '<input type="radio" name="login" value="krb" '.
3389: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3390: $krbcheck.$disabled.' />';
3391: }
3392: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3393: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3394: $in{'curr_authtype'} eq 'krb5') ||
3395: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3396: $in{'curr_authtype'} eq 'krb4')) {
3397: $result .= &mt
3398: ('[_1] Kerberos authenticated with domain [_2] '.
3399: '[_3] Version 4 [_4] Version 5 [_5]',
3400: '<label>'.$authtype,
3401: '</label><input type="text" size="10" name="krbarg" '.
3402: 'value="'.$krbarg.'" '.
3403: 'onchange="'.$jscall.'"'.$disabled.' />',
3404: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
3405: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
3406: '</label>');
3407: } elsif ($can_assign{'krb4'}) {
3408: $result .= &mt
3409: ('[_1] Kerberos authenticated with domain [_2] '.
3410: '[_3] Version 4 [_4]',
3411: '<label>'.$authtype,
3412: '</label><input type="text" size="10" name="krbarg" '.
3413: 'value="'.$krbarg.'" '.
3414: 'onchange="'.$jscall.'"'.$disabled.' />',
3415: '<label><input type="hidden" name="krbver" value="4" />',
3416: '</label>');
3417: } elsif ($can_assign{'krb5'}) {
3418: $result .= &mt
3419: ('[_1] Kerberos authenticated with domain [_2] '.
3420: '[_3] Version 5 [_4]',
3421: '<label>'.$authtype,
3422: '</label><input type="text" size="10" name="krbarg" '.
3423: 'value="'.$krbarg.'" '.
3424: 'onchange="'.$jscall.'"'.$disabled.' />',
3425: '<label><input type="hidden" name="krbver" value="5" />',
3426: '</label>');
3427: }
3428: return $result;
3429: }
3430:
3431: sub authform_internal {
3432: my %in = (
3433: formname => 'document.cu',
3434: kerb_def_dom => 'MSU.EDU',
3435: @_,
3436: );
3437: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
3438: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3439: if ($in{'readonly'}) {
3440: $disabled = ' disabled="disabled"';
3441: }
3442: if (defined($in{'curr_authtype'})) {
3443: if ($in{'curr_authtype'} eq 'int') {
3444: if ($can_assign{'int'}) {
3445: $intcheck = 'checked="checked" ';
3446: if (defined($in{'mode'})) {
3447: if ($in{'mode'} eq 'modifyuser') {
3448: $intcheck = '';
3449: }
3450: }
3451: if (defined($in{'curr_autharg'})) {
3452: $intarg = $in{'curr_autharg'};
3453: }
3454: } else {
3455: $result = &mt('Currently internally authenticated.');
3456: return $result;
3457: }
3458: }
3459: } else {
3460: if ($authnum == 1) {
3461: $authtype = '<input type="hidden" name="login" value="int" />';
3462: }
3463: }
3464: if (!$can_assign{'int'}) {
3465: return;
3466: } elsif ($authtype eq '') {
3467: if (defined($in{'mode'})) {
3468: if ($in{'mode'} eq 'modifycourse') {
3469: if ($authnum == 1) {
3470: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3471: }
3472: }
3473: }
3474: }
3475: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3476: if ($authtype eq '') {
3477: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3478: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3479: }
3480: $autharg = '<input type="password" size="10" name="intarg" value="'.
3481: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3482: $result = &mt
3483: ('[_1] Internally authenticated (with initial password [_2])',
3484: '<label>'.$authtype,'</label>'.$autharg);
3485: $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>';
3486: return $result;
3487: }
3488:
3489: sub authform_local {
3490: my %in = (
3491: formname => 'document.cu',
3492: kerb_def_dom => 'MSU.EDU',
3493: @_,
3494: );
3495: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3496: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3497: if ($in{'readonly'}) {
3498: $disabled = ' disabled="disabled"';
3499: }
3500: if (defined($in{'curr_authtype'})) {
3501: if ($in{'curr_authtype'} eq 'loc') {
3502: if ($can_assign{'loc'}) {
3503: $loccheck = 'checked="checked" ';
3504: if (defined($in{'mode'})) {
3505: if ($in{'mode'} eq 'modifyuser') {
3506: $loccheck = '';
3507: }
3508: }
3509: if (defined($in{'curr_autharg'})) {
3510: $locarg = $in{'curr_autharg'};
3511: }
3512: } else {
3513: $result = &mt('Currently using local (institutional) authentication.');
3514: return $result;
3515: }
3516: }
3517: } else {
3518: if ($authnum == 1) {
3519: $authtype = '<input type="hidden" name="login" value="loc" />';
3520: }
3521: }
3522: if (!$can_assign{'loc'}) {
3523: return;
3524: } elsif ($authtype eq '') {
3525: if (defined($in{'mode'})) {
3526: if ($in{'mode'} eq 'modifycourse') {
3527: if ($authnum == 1) {
3528: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3529: }
3530: }
3531: }
3532: }
3533: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3534: if ($authtype eq '') {
3535: $authtype = '<input type="radio" name="login" value="loc" '.
3536: $loccheck.' onchange="'.$jscall.'" onclick="'.
3537: $jscall.'"'.$disabled.' />';
3538: }
3539: $autharg = '<input type="text" size="10" name="locarg" value="'.
3540: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3541: $result = &mt('[_1] Local Authentication with argument [_2]',
3542: '<label>'.$authtype,'</label>'.$autharg);
3543: return $result;
3544: }
3545:
3546: sub authform_filesystem {
3547: my %in = (
3548: formname => 'document.cu',
3549: kerb_def_dom => 'MSU.EDU',
3550: @_,
3551: );
3552: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3553: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3554: if ($in{'readonly'}) {
3555: $disabled = ' disabled="disabled"';
3556: }
3557: if (defined($in{'curr_authtype'})) {
3558: if ($in{'curr_authtype'} eq 'fsys') {
3559: if ($can_assign{'fsys'}) {
3560: $fsyscheck = 'checked="checked" ';
3561: if (defined($in{'mode'})) {
3562: if ($in{'mode'} eq 'modifyuser') {
3563: $fsyscheck = '';
3564: }
3565: }
3566: } else {
3567: $result = &mt('Currently Filesystem Authenticated.');
3568: return $result;
3569: }
3570: }
3571: } else {
3572: if ($authnum == 1) {
3573: $authtype = '<input type="hidden" name="login" value="fsys" />';
3574: }
3575: }
3576: if (!$can_assign{'fsys'}) {
3577: return;
3578: } elsif ($authtype eq '') {
3579: if (defined($in{'mode'})) {
3580: if ($in{'mode'} eq 'modifycourse') {
3581: if ($authnum == 1) {
3582: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3583: }
3584: }
3585: }
3586: }
3587: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3588: if ($authtype eq '') {
3589: $authtype = '<input type="radio" name="login" value="fsys" '.
3590: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3591: $jscall.'"'.$disabled.' />';
3592: }
3593: $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
3594: ' onchange="'.$jscall.'"'.$disabled.' />';
3595: $result = &mt
3596: ('[_1] Filesystem Authenticated (with initial password [_2])',
3597: '<label>'.$authtype,'</label>'.$autharg);
3598: return $result;
3599: }
3600:
3601: sub authform_lti {
3602: my %in = (
3603: formname => 'document.cu',
3604: kerb_def_dom => 'MSU.EDU',
3605: @_,
3606: );
3607: my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
3608: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3609: if ($in{'readonly'}) {
3610: $disabled = ' disabled="disabled"';
3611: }
3612: if (defined($in{'curr_authtype'})) {
3613: if ($in{'curr_authtype'} eq 'lti') {
3614: if ($can_assign{'lti'}) {
3615: $lticheck = 'checked="checked" ';
3616: if (defined($in{'mode'})) {
3617: if ($in{'mode'} eq 'modifyuser') {
3618: $lticheck = '';
3619: }
3620: }
3621: } else {
3622: $result = &mt('Currently LTI Authenticated.');
3623: return $result;
3624: }
3625: }
3626: } else {
3627: if ($authnum == 1) {
3628: $authtype = '<input type="hidden" name="login" value="lti" />';
3629: }
3630: }
3631: if (!$can_assign{'lti'}) {
3632: return;
3633: } elsif ($authtype eq '') {
3634: if (defined($in{'mode'})) {
3635: if ($in{'mode'} eq 'modifycourse') {
3636: if ($authnum == 1) {
3637: $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
3638: }
3639: }
3640: }
3641: }
3642: $jscall = "javascript:changed_radio('lti',$in{'formname'});";
3643: if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
3644: $authtype = '<input type="radio" name="login" value="lti" '.
3645: $lticheck.' onchange="'.$jscall.'" onclick="'.
3646: $jscall.'"'.$disabled.' />';
3647: }
3648: $autharg = '<input type="hidden" name="ltiarg" value="" />';
3649: if ($authtype) {
3650: $result = &mt('[_1] LTI Authenticated',
3651: '<label>'.$authtype.'</label>'.$autharg);
3652: } else {
3653: $result = '<b>'.&mt('LTI Authenticated').'</b>'.
3654: $autharg;
3655: }
3656: return $result;
3657: }
3658:
3659: sub get_assignable_auth {
3660: my ($dom) = @_;
3661: if ($dom eq '') {
3662: $dom = $env{'request.role.domain'};
3663: }
3664: my %can_assign = (
3665: krb4 => 1,
3666: krb5 => 1,
3667: int => 1,
3668: loc => 1,
3669: lti => 1,
3670: );
3671: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3672: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3673: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3674: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3675: my $context;
3676: if ($env{'request.role'} =~ /^au/) {
3677: $context = 'author';
3678: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3679: $context = 'domain';
3680: } elsif ($env{'request.course.id'}) {
3681: $context = 'course';
3682: }
3683: if ($context) {
3684: if (ref($authhash->{$context}) eq 'HASH') {
3685: %can_assign = %{$authhash->{$context}};
3686: }
3687: }
3688: }
3689: }
3690: my $authnum = 0;
3691: foreach my $key (keys(%can_assign)) {
3692: if ($can_assign{$key}) {
3693: $authnum ++;
3694: }
3695: }
3696: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3697: $authnum --;
3698: }
3699: return ($authnum,%can_assign);
3700: }
3701:
3702: sub check_passwd_rules {
3703: my ($domain,$plainpass) = @_;
3704: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3705: my ($min,$max,@chars,@brokerule,$warning);
3706: $min = $Apache::lonnet::passwdmin;
3707: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3708: if ($passwdconf{'min'} =~ /^\d+$/) {
3709: if ($passwdconf{'min'} > $min) {
3710: $min = $passwdconf{'min'};
3711: }
3712: }
3713: if ($passwdconf{'max'} =~ /^\d+$/) {
3714: $max = $passwdconf{'max'};
3715: }
3716: @chars = @{$passwdconf{'chars'}};
3717: }
3718: if (($min) && (length($plainpass) < $min)) {
3719: push(@brokerule,'min');
3720: }
3721: if (($max) && (length($plainpass) > $max)) {
3722: push(@brokerule,'max');
3723: }
3724: if (@chars) {
3725: my %rules;
3726: map { $rules{$_} = 1; } @chars;
3727: if ($rules{'uc'}) {
3728: unless ($plainpass =~ /[A-Z]/) {
3729: push(@brokerule,'uc');
3730: }
3731: }
3732: if ($rules{'lc'}) {
3733: unless ($plainpass =~ /[a-z]/) {
3734: push(@brokerule,'lc');
3735: }
3736: }
3737: if ($rules{'num'}) {
3738: unless ($plainpass =~ /\d/) {
3739: push(@brokerule,'num');
3740: }
3741: }
3742: if ($rules{'spec'}) {
3743: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3744: push(@brokerule,'spec');
3745: }
3746: }
3747: }
3748: if (@brokerule) {
3749: my %rulenames = &Apache::lonlocal::texthash(
3750: uc => 'At least one upper case letter',
3751: lc => 'At least one lower case letter',
3752: num => 'At least one number',
3753: spec => 'At least one non-alphanumeric',
3754: );
3755: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3756: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3757: $rulenames{'num'} .= ': 0123456789';
3758: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3759: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3760: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3761: $warning = &mt('Password did not satisfy the following:').'<ul>';
3762: foreach my $rule ('min','max','uc','lc','num','spec') {
3763: if (grep(/^$rule$/,@brokerule)) {
3764: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3765: }
3766: }
3767: $warning .= '</ul>';
3768: }
3769: if (wantarray) {
3770: return @brokerule;
3771: }
3772: return $warning;
3773: }
3774:
3775: sub passwd_validation_js {
3776: my ($currpasswdval,$domain,$context,$id) = @_;
3777: my (%passwdconf,$alertmsg);
3778: if ($context eq 'linkprot') {
3779: my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
3780: if (ref($domconfig{'ltisec'}) eq 'HASH') {
3781: if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
3782: %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
3783: }
3784: }
3785: if ($id eq 'add') {
3786: $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
3787: } elsif ($id =~ /^\d+$/) {
3788: my $pos = $id+1;
3789: $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
3790: } else {
3791: $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
3792: }
3793: } else {
3794: %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3795: $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
3796: }
3797: my ($min,$max,@chars,$numrules,$intargjs,%alert);
3798: $numrules = 0;
3799: $min = $Apache::lonnet::passwdmin;
3800: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3801: if ($passwdconf{'min'} =~ /^\d+$/) {
3802: if ($passwdconf{'min'} > $min) {
3803: $min = $passwdconf{'min'};
3804: }
3805: }
3806: if ($passwdconf{'max'} =~ /^\d+$/) {
3807: $max = $passwdconf{'max'};
3808: $numrules ++;
3809: }
3810: @chars = @{$passwdconf{'chars'}};
3811: if (@chars) {
3812: $numrules ++;
3813: }
3814: }
3815: if ($min > 0) {
3816: $numrules ++;
3817: }
3818: if (($min > 0) || ($max ne '') || (@chars > 0)) {
3819: if ($min) {
3820: $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
3821: }
3822: if ($max) {
3823: $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
3824: }
3825: my (@charalerts,@charrules);
3826: if (@chars) {
3827: if (grep(/^uc$/,@chars)) {
3828: push(@charalerts,&mt('contain at least one upper case letter'));
3829: push(@charrules,'uc');
3830: }
3831: if (grep(/^lc$/,@chars)) {
3832: push(@charalerts,&mt('contain at least one lower case letter'));
3833: push(@charrules,'lc');
3834: }
3835: if (grep(/^num$/,@chars)) {
3836: push(@charalerts,&mt('contain at least one number'));
3837: push(@charrules,'num');
3838: }
3839: if (grep(/^spec$/,@chars)) {
3840: push(@charalerts,&mt('contain at least one non-alphanumeric'));
3841: push(@charrules,'spec');
3842: }
3843: }
3844: $intargjs = qq| var rulesmsg = '';\n|.
3845: qq| var currpwval = $currpasswdval;\n|;
3846: if ($min) {
3847: $intargjs .= qq|
3848: if (currpwval.length < $min) {
3849: rulesmsg += ' - $alert{min}';
3850: }
3851: |;
3852: }
3853: if ($max) {
3854: $intargjs .= qq|
3855: if (currpwval.length > $max) {
3856: rulesmsg += ' - $alert{max}';
3857: }
3858: |;
3859: }
3860: if (@chars > 0) {
3861: my $charrulestr = '"'.join('","',@charrules).'"';
3862: my $charalertstr = '"'.join('","',@charalerts).'"';
3863: $intargjs .= qq| var brokerules = new Array();\n|.
3864: qq| var charrules = new Array($charrulestr);\n|.
3865: qq| var charalerts = new Array($charalertstr);\n|;
3866: my %rules;
3867: map { $rules{$_} = 1; } @chars;
3868: if ($rules{'uc'}) {
3869: $intargjs .= qq|
3870: var ucRegExp = /[A-Z]/;
3871: if (!ucRegExp.test(currpwval)) {
3872: brokerules.push('uc');
3873: }
3874: |;
3875: }
3876: if ($rules{'lc'}) {
3877: $intargjs .= qq|
3878: var lcRegExp = /[a-z]/;
3879: if (!lcRegExp.test(currpwval)) {
3880: brokerules.push('lc');
3881: }
3882: |;
3883: }
3884: if ($rules{'num'}) {
3885: $intargjs .= qq|
3886: var numRegExp = /[0-9]/;
3887: if (!numRegExp.test(currpwval)) {
3888: brokerules.push('num');
3889: }
3890: |;
3891: }
3892: if ($rules{'spec'}) {
3893: $intargjs .= q|
3894: var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
3895: if (!specRegExp.test(currpwval)) {
3896: brokerules.push('spec');
3897: }
3898: |;
3899: }
3900: $intargjs .= qq|
3901: if (brokerules.length > 0) {
3902: for (var i=0; i<brokerules.length; i++) {
3903: for (var j=0; j<charrules.length; j++) {
3904: if (brokerules[i] == charrules[j]) {
3905: rulesmsg += ' - '+charalerts[j]+'\\n';
3906: break;
3907: }
3908: }
3909: }
3910: }
3911: |;
3912: }
3913: $intargjs .= qq|
3914: if (rulesmsg != '') {
3915: rulesmsg = '$alertmsg'+rulesmsg;
3916: alert(rulesmsg);
3917: return false;
3918: }
3919: |;
3920: }
3921: return ($numrules,$intargjs);
3922: }
3923:
3924: ###############################################################
3925: ## Get Kerberos Defaults for Domain ##
3926: ###############################################################
3927: ##
3928: ## Returns default kerberos version and an associated argument
3929: ## as listed in file domain.tab. If not listed, provides
3930: ## appropriate default domain and kerberos version.
3931: ##
3932: #-------------------------------------------
3933:
3934: =pod
3935:
3936: =item * &get_kerberos_defaults()
3937:
3938: get_kerberos_defaults($target_domain) returns the default kerberos
3939: version and domain. If not found, it defaults to version 4 and the
3940: domain of the server.
3941:
3942: =over 4
3943:
3944: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3945:
3946: =back
3947:
3948: =back
3949:
3950: =cut
3951:
3952: #-------------------------------------------
3953: sub get_kerberos_defaults {
3954: my $domain=shift;
3955: my ($krbdef,$krbdefdom);
3956: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3957: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3958: $krbdef = $domdefaults{'auth_def'};
3959: $krbdefdom = $domdefaults{'auth_arg_def'};
3960: } else {
3961: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3962: my $krbdefdom=$1;
3963: $krbdefdom=~tr/a-z/A-Z/;
3964: $krbdef = "krb4";
3965: }
3966: return ($krbdef,$krbdefdom);
3967: }
3968:
3969:
3970: ###############################################################
3971: ## Thesaurus Functions ##
3972: ###############################################################
3973:
3974: =pod
3975:
3976: =head1 Thesaurus Functions
3977:
3978: =over 4
3979:
3980: =item * &initialize_keywords()
3981:
3982: Initializes the package variable %Keywords if it is empty. Uses the
3983: package variable $thesaurus_db_file.
3984:
3985: =cut
3986:
3987: ###################################################
3988:
3989: sub initialize_keywords {
3990: return 1 if (scalar keys(%Keywords));
3991: # If we are here, %Keywords is empty, so fill it up
3992: # Make sure the file we need exists...
3993: if (! -e $thesaurus_db_file) {
3994: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3995: " failed because it does not exist");
3996: return 0;
3997: }
3998: # Set up the hash as a database
3999: my %thesaurus_db;
4000: if (! tie(%thesaurus_db,'GDBM_File',
4001: $thesaurus_db_file,&GDBM_READER(),0640)){
4002: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
4003: $thesaurus_db_file);
4004: return 0;
4005: }
4006: # Get the average number of appearances of a word.
4007: my $avecount = $thesaurus_db{'average.count'};
4008: # Put keywords (those that appear > average) into %Keywords
4009: while (my ($word,$data)=each (%thesaurus_db)) {
4010: my ($count,undef) = split /:/,$data;
4011: $Keywords{$word}++ if ($count > $avecount);
4012: }
4013: untie %thesaurus_db;
4014: # Remove special values from %Keywords.
4015: foreach my $value ('total.count','average.count') {
4016: delete($Keywords{$value}) if (exists($Keywords{$value}));
4017: }
4018: return 1;
4019: }
4020:
4021: ###################################################
4022:
4023: =pod
4024:
4025: =item * &keyword($word)
4026:
4027: Returns true if $word is a keyword. A keyword is a word that appears more
4028: than the average number of times in the thesaurus database. Calls
4029: &initialize_keywords
4030:
4031: =cut
4032:
4033: ###################################################
4034:
4035: sub keyword {
4036: return if (!&initialize_keywords());
4037: my $word=lc(shift());
4038: $word=~s/\W//g;
4039: return exists($Keywords{$word});
4040: }
4041:
4042: ###############################################################
4043:
4044: =pod
4045:
4046: =item * &get_related_words()
4047:
4048: Look up a word in the thesaurus. Takes a scalar argument and returns
4049: an array of words. If the keyword is not in the thesaurus, an empty array
4050: will be returned. The order of the words returned is determined by the
4051: database which holds them.
4052:
4053: Uses global $thesaurus_db_file.
4054:
4055:
4056: =cut
4057:
4058: ###############################################################
4059: sub get_related_words {
4060: my $keyword = shift;
4061: my %thesaurus_db;
4062: if (! -e $thesaurus_db_file) {
4063: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
4064: "failed because the file does not exist");
4065: return ();
4066: }
4067: if (! tie(%thesaurus_db,'GDBM_File',
4068: $thesaurus_db_file,&GDBM_READER(),0640)){
4069: return ();
4070: }
4071: my @Words=();
4072: my $count=0;
4073: if (exists($thesaurus_db{$keyword})) {
4074: # The first element is the number of times
4075: # the word appears. We do not need it now.
4076: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
4077: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
4078: my $threshold=$mostfrequentcount/10;
4079: foreach my $possibleword (@RelatedWords) {
4080: my ($word,$wordcount)=split(/\,/,$possibleword);
4081: if ($wordcount>$threshold) {
4082: push(@Words,$word);
4083: $count++;
4084: if ($count>10) { last; }
4085: }
4086: }
4087: }
4088: untie %thesaurus_db;
4089: return @Words;
4090: }
4091: ###############################################################
4092: #
4093: # Spell checking
4094: #
4095:
4096: =pod
4097:
4098: =back
4099:
4100: =head1 Spell checking
4101:
4102: =over 4
4103:
4104: =item * &check_spelling($wordlist $language)
4105:
4106: Takes a string containing words and feeds it to an external
4107: spellcheck program via a pipeline. Returns a string containing
4108: them mis-spelled words.
4109:
4110: Parameters:
4111:
4112: =over 4
4113:
4114: =item - $wordlist
4115:
4116: String that will be fed into the spellcheck program.
4117:
4118: =item - $language
4119:
4120: Language string that specifies the language for which the spell
4121: check will be performed.
4122:
4123: =back
4124:
4125: =back
4126:
4127: Note: This sub assumes that aspell is installed.
4128:
4129:
4130: =cut
4131:
4132:
4133: sub check_spelling {
4134: my ($wordlist, $language) = @_;
4135: my @misspellings;
4136:
4137: # Generate the speller and set the langauge.
4138: # if explicitly selected:
4139:
4140: my $speller = Text::Aspell->new;
4141: if ($language) {
4142: $speller->set_option('lang', $language);
4143: }
4144:
4145: # Turn the word list into an array of words by splittingon whitespace
4146:
4147: my @words = split(/\s+/, $wordlist);
4148:
4149: foreach my $word (@words) {
4150: if(! $speller->check($word)) {
4151: push(@misspellings, $word);
4152: }
4153: }
4154: return join(' ', @misspellings);
4155:
4156: }
4157:
4158: # -------------------------------------------------------------- Plaintext name
4159: =pod
4160:
4161: =head1 User Name Functions
4162:
4163: =over 4
4164:
4165: =item * &plainname($uname,$udom,$first)
4166:
4167: Takes a users logon name and returns it as a string in
4168: "first middle last generation" form
4169: if $first is set to 'lastname' then it returns it as
4170: 'lastname generation, firstname middlename' if their is a lastname
4171:
4172: =cut
4173:
4174:
4175: ###############################################################
4176: sub plainname {
4177: my ($uname,$udom,$first)=@_;
4178: return if (!defined($uname) || !defined($udom));
4179: my %names=&getnames($uname,$udom);
4180: my $name=&Apache::lonnet::format_name($names{'firstname'},
4181: $names{'middlename'},
4182: $names{'lastname'},
4183: $names{'generation'},$first);
4184: $name=~s/^\s+//;
4185: $name=~s/\s+$//;
4186: $name=~s/\s+/ /g;
4187: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
4188: return $name;
4189: }
4190:
4191: # -------------------------------------------------------------------- Nickname
4192: =pod
4193:
4194: =item * &nickname($uname,$udom)
4195:
4196: Gets a users name and returns it as a string as
4197:
4198: ""nickname""
4199:
4200: if the user has a nickname or
4201:
4202: "first middle last generation"
4203:
4204: if the user does not
4205:
4206: =cut
4207:
4208: sub nickname {
4209: my ($uname,$udom)=@_;
4210: return if (!defined($uname) || !defined($udom));
4211: my %names=&getnames($uname,$udom);
4212: my $name=$names{'nickname'};
4213: if ($name) {
4214: $name='"'.$name.'"';
4215: } else {
4216: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
4217: $names{'lastname'}.' '.$names{'generation'};
4218: $name=~s/\s+$//;
4219: $name=~s/\s+/ /g;
4220: }
4221: return $name;
4222: }
4223:
4224: sub getnames {
4225: my ($uname,$udom)=@_;
4226: return if (!defined($uname) || !defined($udom));
4227: if ($udom eq 'public' && $uname eq 'public') {
4228: return ('lastname' => &mt('Public'));
4229: }
4230: my $id=$uname.':'.$udom;
4231: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
4232: if ($cached) {
4233: return %{$names};
4234: } else {
4235: my %loadnames=&Apache::lonnet::get('environment',
4236: ['firstname','middlename','lastname','generation','nickname'],
4237: $udom,$uname);
4238: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
4239: return %loadnames;
4240: }
4241: }
4242:
4243: # -------------------------------------------------------------------- getemails
4244:
4245: =pod
4246:
4247: =item * &getemails($uname,$udom)
4248:
4249: Gets a user's email information and returns it as a hash with keys:
4250: notification, critnotification, permanentemail
4251:
4252: For notification and critnotification, values are comma-separated lists
4253: of e-mail addresses; for permanentemail, value is a single e-mail address.
4254:
4255:
4256: =cut
4257:
4258:
4259: sub getemails {
4260: my ($uname,$udom)=@_;
4261: if ($udom eq 'public' && $uname eq 'public') {
4262: return;
4263: }
4264: if (!$udom) { $udom=$env{'user.domain'}; }
4265: if (!$uname) { $uname=$env{'user.name'}; }
4266: my $id=$uname.':'.$udom;
4267: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
4268: if ($cached) {
4269: return %{$names};
4270: } else {
4271: my %loadnames=&Apache::lonnet::get('environment',
4272: ['notification','critnotification',
4273: 'permanentemail'],
4274: $udom,$uname);
4275: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
4276: return %loadnames;
4277: }
4278: }
4279:
4280: sub flush_email_cache {
4281: my ($uname,$udom)=@_;
4282: if (!$udom) { $udom =$env{'user.domain'}; }
4283: if (!$uname) { $uname=$env{'user.name'}; }
4284: return if ($udom eq 'public' && $uname eq 'public');
4285: my $id=$uname.':'.$udom;
4286: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
4287: }
4288:
4289: # -------------------------------------------------------------------- getlangs
4290:
4291: =pod
4292:
4293: =item * &getlangs($uname,$udom)
4294:
4295: Gets a user's language preference and returns it as a hash with key:
4296: language.
4297:
4298: =cut
4299:
4300:
4301: sub getlangs {
4302: my ($uname,$udom) = @_;
4303: if (!$udom) { $udom =$env{'user.domain'}; }
4304: if (!$uname) { $uname=$env{'user.name'}; }
4305: my $id=$uname.':'.$udom;
4306: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
4307: if ($cached) {
4308: return %{$langs};
4309: } else {
4310: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
4311: $udom,$uname);
4312: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
4313: return %loadlangs;
4314: }
4315: }
4316:
4317: sub flush_langs_cache {
4318: my ($uname,$udom)=@_;
4319: if (!$udom) { $udom =$env{'user.domain'}; }
4320: if (!$uname) { $uname=$env{'user.name'}; }
4321: return if ($udom eq 'public' && $uname eq 'public');
4322: my $id=$uname.':'.$udom;
4323: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
4324: }
4325:
4326: # ------------------------------------------------------------------ Screenname
4327:
4328: =pod
4329:
4330: =item * &screenname($uname,$udom)
4331:
4332: Gets a users screenname and returns it as a string
4333:
4334: =cut
4335:
4336: sub screenname {
4337: my ($uname,$udom)=@_;
4338: if ($uname eq $env{'user.name'} &&
4339: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
4340: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
4341: return $names{'screenname'};
4342: }
4343:
4344:
4345: # ------------------------------------------------------------- Confirm Wrapper
4346: =pod
4347:
4348: =item * &confirmwrapper($message)
4349:
4350: Wrap messages about completion of operation in box
4351:
4352: =cut
4353:
4354: sub confirmwrapper {
4355: my ($message)=@_;
4356: if ($message) {
4357: return "\n".'<div class="LC_confirm_box">'."\n"
4358: .$message."\n"
4359: .'</div>'."\n";
4360: } else {
4361: return $message;
4362: }
4363: }
4364:
4365: # ------------------------------------------------------------- Message Wrapper
4366:
4367: sub messagewrapper {
4368: my ($link,$username,$domain,$subject,$text)=@_;
4369: return
4370: '<a href="/adm/email?compose=individual&'.
4371: 'recname='.$username.'&recdom='.$domain.
4372: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
4373: 'title="'.&mt('Send message').'">'.$link.'</a>';
4374: }
4375:
4376: # --------------------------------------------------------------- Notes Wrapper
4377:
4378: sub noteswrapper {
4379: my ($link,$un,$do)=@_;
4380: return
4381: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
4382: }
4383:
4384: # ------------------------------------------------------------- Aboutme Wrapper
4385:
4386: sub aboutmewrapper {
4387: my ($link,$username,$domain,$target,$class)=@_;
4388: if (!defined($username) && !defined($domain)) {
4389: return;
4390: }
4391: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
4392: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
4393: }
4394:
4395: # ------------------------------------------------------------ Syllabus Wrapper
4396:
4397: sub syllabuswrapper {
4398: my ($linktext,$coursedir,$domain)=@_;
4399: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
4400: }
4401:
4402: # -----------------------------------------------------------------------------
4403:
4404: sub aboutme_on {
4405: my ($uname,$udom)=@_;
4406: unless ($uname) { $uname=$env{'user.name'}; }
4407: unless ($udom) { $udom=$env{'user.domain'}; }
4408: return if ($udom eq 'public' && $uname eq 'public');
4409: my $hashkey=$uname.':'.$udom;
4410: my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
4411: if ($cached) {
4412: return $aboutme;
4413: }
4414: $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
4415: &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
4416: return $aboutme;
4417: }
4418:
4419: sub devalidate_aboutme_cache {
4420: my ($uname,$udom)=@_;
4421: if (!$udom) { $udom =$env{'user.domain'}; }
4422: if (!$uname) { $uname=$env{'user.name'}; }
4423: return if ($udom eq 'public' && $uname eq 'public');
4424: my $id=$uname.':'.$udom;
4425: &Apache::lonnet::devalidate_cache_new('aboutme',$id);
4426: }
4427:
4428: sub track_student_link {
4429: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
4430: my $link ="/adm/trackstudent?";
4431: my $title = 'View recent activity';
4432: if (defined($sname) && $sname !~ /^\s*$/ &&
4433: defined($sdom) && $sdom !~ /^\s*$/) {
4434: $link .= "selected_student=$sname:$sdom";
4435: $title .= ' of this student';
4436: }
4437: if (defined($target) && $target !~ /^\s*$/) {
4438: $target = qq{target="$target"};
4439: } else {
4440: $target = '';
4441: }
4442: if ($start) { $link.='&start='.$start; }
4443: if ($only_body) { $link .= '&only_body=1'; }
4444: $title = &mt($title);
4445: $linktext = &mt($linktext);
4446: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
4447: &help_open_topic('View_recent_activity');
4448: }
4449:
4450: sub slot_reservations_link {
4451: my ($linktext,$sname,$sdom,$target) = @_;
4452: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
4453: my $title = 'View slot reservation history';
4454: if (defined($sname) && $sname !~ /^\s*$/ &&
4455: defined($sdom) && $sdom !~ /^\s*$/) {
4456: $link .= "&uname=$sname&udom=$sdom";
4457: $title .= ' of this student';
4458: }
4459: if (defined($target) && $target !~ /^\s*$/) {
4460: $target = qq{target="$target"};
4461: } else {
4462: $target = '';
4463: }
4464: $title = &mt($title);
4465: $linktext = &mt($linktext);
4466: return qq{<a href="$link" title="$title" $target>$linktext</a>};
4467: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
4468:
4469: }
4470:
4471: # ===================================================== Display a student photo
4472:
4473:
4474: sub student_image_tag {
4475: my ($domain,$user)=@_;
4476: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
4477: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
4478: return '<img src="'.$imgsrc.'" align="right" />';
4479: } else {
4480: return '';
4481: }
4482: }
4483:
4484: =pod
4485:
4486: =back
4487:
4488: =head1 Access .tab File Data
4489:
4490: =over 4
4491:
4492: =item * &languageids()
4493:
4494: returns list of all language ids
4495:
4496: =cut
4497:
4498: sub languageids {
4499: return sort(keys(%language));
4500: }
4501:
4502: =pod
4503:
4504: =item * &languagedescription()
4505:
4506: returns description of a specified language id
4507:
4508: =cut
4509:
4510: sub languagedescription {
4511: my $code=shift;
4512: return ($supported_language{$code}?'* ':'').
4513: $language{$code}.
4514: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4515: }
4516:
4517: =pod
4518:
4519: =item * &plainlanguagedescription
4520:
4521: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4522: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4523:
4524: =cut
4525:
4526: sub plainlanguagedescription {
4527: my $code=shift;
4528: return $language{$code};
4529: }
4530:
4531: =pod
4532:
4533: =item * &supportedlanguagecode
4534:
4535: Returns the supported language code (e.g. sptutf maps to pt) given a language
4536: code.
4537:
4538: =cut
4539:
4540: sub supportedlanguagecode {
4541: my $code=shift;
4542: return $supported_language{$code};
4543: }
4544:
4545: =pod
4546:
4547: =item * &latexlanguage()
4548:
4549: Given a language key code returns the correspondnig language to use
4550: to select the correct hyphenation on LaTeX printouts. This is undef if there
4551: is no supported hyphenation for the language code.
4552:
4553: =cut
4554:
4555: sub latexlanguage {
4556: my $code = shift;
4557: return $latex_language{$code};
4558: }
4559:
4560: =pod
4561:
4562: =item * &latexhyphenation()
4563:
4564: Same as above but what's supplied is the language as it might be stored
4565: in the metadata.
4566:
4567: =cut
4568:
4569: sub latexhyphenation {
4570: my $key = shift;
4571: return $latex_language_bykey{$key};
4572: }
4573:
4574: =pod
4575:
4576: =item * ©rightids()
4577:
4578: returns list of all copyrights
4579:
4580: =cut
4581:
4582: sub copyrightids {
4583: return sort(keys(%cprtag));
4584: }
4585:
4586: =pod
4587:
4588: =item * ©rightdescription()
4589:
4590: returns description of a specified copyright id
4591:
4592: =cut
4593:
4594: sub copyrightdescription {
4595: return &mt($cprtag{shift(@_)});
4596: }
4597:
4598: =pod
4599:
4600: =item * &source_copyrightids()
4601:
4602: returns list of all source copyrights
4603:
4604: =cut
4605:
4606: sub source_copyrightids {
4607: return sort(keys(%scprtag));
4608: }
4609:
4610: =pod
4611:
4612: =item * &source_copyrightdescription()
4613:
4614: returns description of a specified source copyright id
4615:
4616: =cut
4617:
4618: sub source_copyrightdescription {
4619: return &mt($scprtag{shift(@_)});
4620: }
4621:
4622: =pod
4623:
4624: =item * &filecategories()
4625:
4626: returns list of all file categories
4627:
4628: =cut
4629:
4630: sub filecategories {
4631: return sort(keys(%category_extensions));
4632: }
4633:
4634: =pod
4635:
4636: =item * &filecategorytypes()
4637:
4638: returns list of file types belonging to a given file
4639: category
4640:
4641: =cut
4642:
4643: sub filecategorytypes {
4644: my ($cat) = @_;
4645: if (ref($category_extensions{lc($cat)}) eq 'ARRAY') {
4646: return @{$category_extensions{lc($cat)}};
4647: } else {
4648: return ();
4649: }
4650: }
4651:
4652: =pod
4653:
4654: =item * &fileembstyle()
4655:
4656: returns embedding style for a specified file type
4657:
4658: =cut
4659:
4660: sub fileembstyle {
4661: return $fe{lc(shift(@_))};
4662: }
4663:
4664: sub filemimetype {
4665: return $fm{lc(shift(@_))};
4666: }
4667:
4668:
4669: sub filecategoryselect {
4670: my ($name,$value)=@_;
4671: return &select_form($value,$name,
4672: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4673: }
4674:
4675: =pod
4676:
4677: =item * &filedescription()
4678:
4679: returns description for a specified file type
4680:
4681: =cut
4682:
4683: sub filedescription {
4684: my $file_description = $fd{lc(shift())};
4685: $file_description =~ s:([\[\]]):~$1:g;
4686: return &mt($file_description);
4687: }
4688:
4689: =pod
4690:
4691: =item * &filedescriptionex()
4692:
4693: returns description for a specified file type with
4694: extra formatting
4695:
4696: =cut
4697:
4698: sub filedescriptionex {
4699: my $ex=shift;
4700: my $file_description = $fd{lc($ex)};
4701: $file_description =~ s:([\[\]]):~$1:g;
4702: return '.'.$ex.' '.&mt($file_description);
4703: }
4704:
4705: # End of .tab access
4706: =pod
4707:
4708: =back
4709:
4710: =cut
4711:
4712: # ------------------------------------------------------------------ File Types
4713: sub fileextensions {
4714: return sort(keys(%fe));
4715: }
4716:
4717: # ----------------------------------------------------------- Display Languages
4718: # returns a hash with all desired display languages
4719: #
4720:
4721: sub display_languages {
4722: my %languages=();
4723: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4724: $languages{$lang}=1;
4725: }
4726: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4727: if ($env{'form.displaylanguage'}) {
4728: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4729: $languages{$lang}=1;
4730: }
4731: }
4732: return %languages;
4733: }
4734:
4735: sub languages {
4736: my ($possible_langs) = @_;
4737: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4738: if (!ref($possible_langs)) {
4739: if( wantarray ) {
4740: return @preferred_langs;
4741: } else {
4742: return $preferred_langs[0];
4743: }
4744: }
4745: my %possibilities = map { $_ => 1 } (@$possible_langs);
4746: my @preferred_possibilities;
4747: foreach my $preferred_lang (@preferred_langs) {
4748: if (exists($possibilities{$preferred_lang})) {
4749: push(@preferred_possibilities, $preferred_lang);
4750: }
4751: }
4752: if( wantarray ) {
4753: return @preferred_possibilities;
4754: }
4755: return $preferred_possibilities[0];
4756: }
4757:
4758: sub user_lang {
4759: my ($touname,$toudom,$fromcid) = @_;
4760: my @userlangs;
4761: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4762: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4763: $env{'course.'.$fromcid.'.languages'}));
4764: } else {
4765: my %langhash = &getlangs($touname,$toudom);
4766: if ($langhash{'languages'} ne '') {
4767: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4768: } else {
4769: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4770: if ($domdefs{'lang_def'} ne '') {
4771: @userlangs = ($domdefs{'lang_def'});
4772: }
4773: }
4774: }
4775: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4776: my $user_lh = Apache::localize->get_handle(@languages);
4777: return $user_lh;
4778: }
4779:
4780:
4781: ###############################################################
4782: ## Student Answer Attempts ##
4783: ###############################################################
4784:
4785: =pod
4786:
4787: =head1 Alternate Problem Views
4788:
4789: =over 4
4790:
4791: =item * &get_previous_attempt($symb, $username, $domain, $course,
4792: $getattempt, $regexp, $gradesub, $usec, $identifier)
4793:
4794: Return string with previous attempt on problem. Arguments:
4795:
4796: =over 4
4797:
4798: =item * $symb: Problem, including path
4799:
4800: =item * $username: username of the desired student
4801:
4802: =item * $domain: domain of the desired student
4803:
4804: =item * $course: Course ID
4805:
4806: =item * $getattempt: Leave blank for all attempts, otherwise put
4807: something
4808:
4809: =item * $regexp: if string matches this regexp, the string will be
4810: sent to $gradesub
4811:
4812: =item * $gradesub: routine that processes the string if it matches $regexp
4813:
4814: =item * $usec: section of the desired student
4815:
4816: =item * $identifier: counter for student (multiple students one problem) or
4817: problem (one student; whole sequence).
4818:
4819: =back
4820:
4821: The output string is a table containing all desired attempts, if any.
4822:
4823: =cut
4824:
4825: sub get_previous_attempt {
4826: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4827: my $prevattempts='';
4828: no strict 'refs';
4829: if ($symb) {
4830: my (%returnhash)=
4831: &Apache::lonnet::restore($symb,$course,$domain,$username);
4832: if ($returnhash{'version'}) {
4833: my %lasthash=();
4834: my $version;
4835: for ($version=1;$version<=$returnhash{'version'};$version++) {
4836: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4837: if ($key =~ /\.rawrndseed$/) {
4838: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4839: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4840: } else {
4841: $lasthash{$key}=$returnhash{$version.':'.$key};
4842: }
4843: }
4844: }
4845: $prevattempts=&start_data_table().&start_data_table_header_row();
4846: $prevattempts.='<th>'.&mt('History').'</th>';
4847: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4848: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4849: foreach my $key (sort(keys(%lasthash))) {
4850: my ($ign,@parts) = split(/\./,$key);
4851: if ($#parts > 0) {
4852: my $data=$parts[-1];
4853: next if ($data eq 'foilorder');
4854: pop(@parts);
4855: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4856: if ($data eq 'type') {
4857: unless ($showsurv) {
4858: my $id = join(',',@parts);
4859: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4860: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4861: $lasthidden{$ign.'.'.$id} = 1;
4862: }
4863: }
4864: if ($identifier ne '') {
4865: my $id = join(',',@parts);
4866: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4867: $domain,$username,$usec,undef,$course) =~ /^no/) {
4868: $hidestatus{$ign.'.'.$id} = 1;
4869: }
4870: }
4871: } elsif ($data eq 'regrader') {
4872: if (($identifier ne '') && (@parts)) {
4873: my $id = join(',',@parts);
4874: $regraded{$ign.'.'.$id} = 1;
4875: }
4876: }
4877: } else {
4878: if ($#parts == 0) {
4879: $prevattempts.='<th>'.$parts[0].'</th>';
4880: } else {
4881: $prevattempts.='<th>'.$ign.'</th>';
4882: }
4883: }
4884: }
4885: $prevattempts.=&end_data_table_header_row();
4886: if ($getattempt eq '') {
4887: my (%solved,%resets,%probstatus);
4888: if (($identifier ne '') && (keys(%regraded) > 0)) {
4889: for ($version=1;$version<=$returnhash{'version'};$version++) {
4890: foreach my $id (keys(%regraded)) {
4891: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4892: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4893: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4894: push(@{$resets{$id}},$version);
4895: }
4896: }
4897: }
4898: }
4899: for ($version=1;$version<=$returnhash{'version'};$version++) {
4900: my (@hidden,@unsolved);
4901: if (%typeparts) {
4902: foreach my $id (keys(%typeparts)) {
4903: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4904: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4905: push(@hidden,$id);
4906: } elsif ($identifier ne '') {
4907: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4908: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4909: ($hidestatus{$id})) {
4910: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4911: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4912: push(@{$solved{$id}},$version);
4913: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4914: (ref($solved{$id}) eq 'ARRAY')) {
4915: my $skip;
4916: if (ref($resets{$id}) eq 'ARRAY') {
4917: foreach my $reset (@{$resets{$id}}) {
4918: if ($reset > $solved{$id}[-1]) {
4919: $skip=1;
4920: last;
4921: }
4922: }
4923: }
4924: unless ($skip) {
4925: my ($ign,$partslist) = split(/\./,$id,2);
4926: push(@unsolved,$partslist);
4927: }
4928: }
4929: }
4930: }
4931: }
4932: }
4933: $prevattempts.=&start_data_table_row().
4934: '<td>'.&mt('Transaction [_1]',$version);
4935: if (@unsolved) {
4936: $prevattempts .= '<span class="LC_nobreak"><label>'.
4937: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4938: &mt('Hide').'</label></span>';
4939: }
4940: $prevattempts .= '</td>';
4941: if (@hidden) {
4942: foreach my $key (sort(keys(%lasthash))) {
4943: next if ($key =~ /\.foilorder$/);
4944: my $hide;
4945: foreach my $id (@hidden) {
4946: if ($key =~ /^\Q$id\E/) {
4947: $hide = 1;
4948: last;
4949: }
4950: }
4951: if ($hide) {
4952: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4953: if (($data eq 'award') || ($data eq 'awarddetail')) {
4954: my $value = &format_previous_attempt_value($key,
4955: $returnhash{$version.':'.$key});
4956: $prevattempts.='<td>'.$value.' </td>';
4957: } else {
4958: $prevattempts.='<td> </td>';
4959: }
4960: } else {
4961: if ($key =~ /\./) {
4962: my $value = $returnhash{$version.':'.$key};
4963: if ($key =~ /\.rndseed$/) {
4964: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4965: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4966: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4967: }
4968: }
4969: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4970: ' </td>';
4971: } else {
4972: $prevattempts.='<td> </td>';
4973: }
4974: }
4975: }
4976: } else {
4977: foreach my $key (sort(keys(%lasthash))) {
4978: next if ($key =~ /\.foilorder$/);
4979: my $value = $returnhash{$version.':'.$key};
4980: if ($key =~ /\.rndseed$/) {
4981: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4982: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4983: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4984: }
4985: }
4986: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4987: ' </td>';
4988: }
4989: }
4990: $prevattempts.=&end_data_table_row();
4991: }
4992: }
4993: my @currhidden = keys(%lasthidden);
4994: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4995: foreach my $key (sort(keys(%lasthash))) {
4996: next if ($key =~ /\.foilorder$/);
4997: if (%typeparts) {
4998: my $hidden;
4999: foreach my $id (@currhidden) {
5000: if ($key =~ /^\Q$id\E/) {
5001: $hidden = 1;
5002: last;
5003: }
5004: }
5005: if ($hidden) {
5006: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
5007: if (($data eq 'award') || ($data eq 'awarddetail')) {
5008: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5009: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5010: $value = &$gradesub($value);
5011: }
5012: $prevattempts.='<td>'. $value.' </td>';
5013: } else {
5014: $prevattempts.='<td> </td>';
5015: }
5016: } else {
5017: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5018: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5019: $value = &$gradesub($value);
5020: }
5021: $prevattempts.='<td>'.$value.' </td>';
5022: }
5023: } else {
5024: my $value = &format_previous_attempt_value($key,$lasthash{$key});
5025: if ($key =~/$regexp$/ && (defined &$gradesub)) {
5026: $value = &$gradesub($value);
5027: }
5028: $prevattempts.='<td>'.$value.' </td>';
5029: }
5030: }
5031: $prevattempts.= &end_data_table_row().&end_data_table();
5032: } else {
5033: my $msg;
5034: if ($symb =~ /ext\.tool$/) {
5035: $msg = &mt('No grade passed back.');
5036: } else {
5037: $msg = &mt('Nothing submitted - no attempts.');
5038: }
5039: $prevattempts=
5040: &start_data_table().&start_data_table_row().
5041: '<td>'.$msg.'</td>'.
5042: &end_data_table_row().&end_data_table();
5043: }
5044: } else {
5045: $prevattempts=
5046: &start_data_table().&start_data_table_row().
5047: '<td>'.&mt('No data.').'</td>'.
5048: &end_data_table_row().&end_data_table();
5049: }
5050: }
5051:
5052: sub format_previous_attempt_value {
5053: my ($key,$value) = @_;
5054: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
5055: $value = &Apache::lonlocal::locallocaltime($value);
5056: } elsif (ref($value) eq 'ARRAY') {
5057: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
5058: } elsif ($key =~ /answerstring$/) {
5059: my %answers = &Apache::lonnet::str2hash($value);
5060: my @answer = %answers;
5061: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
5062: my @anskeys = sort(keys(%answers));
5063: if (@anskeys == 1) {
5064: my $answer = $answers{$anskeys[0]};
5065: if ($answer =~ m{\0}) {
5066: $answer =~ s{\0}{,}g;
5067: }
5068: my $tag_internal_answer_name = 'INTERNAL';
5069: if ($anskeys[0] eq $tag_internal_answer_name) {
5070: $value = $answer;
5071: } else {
5072: $value = $anskeys[0].'='.$answer;
5073: }
5074: } else {
5075: foreach my $ans (@anskeys) {
5076: my $answer = $answers{$ans};
5077: if ($answer =~ m{\0}) {
5078: $answer =~ s{\0}{,}g;
5079: }
5080: $value .= $ans.'='.$answer.'<br />';;
5081: }
5082: }
5083: } else {
5084: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
5085: }
5086: return $value;
5087: }
5088:
5089:
5090: sub relative_to_absolute {
5091: my ($url,$output)=@_;
5092: my $parser=HTML::TokeParser->new(\$output);
5093: my $token;
5094: my $thisdir=$url;
5095: my @rlinks=();
5096: while ($token=$parser->get_token) {
5097: if ($token->[0] eq 'S') {
5098: if ($token->[1] eq 'a') {
5099: if ($token->[2]->{'href'}) {
5100: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
5101: }
5102: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
5103: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
5104: } elsif ($token->[1] eq 'base') {
5105: $thisdir=$token->[2]->{'href'};
5106: }
5107: }
5108: }
5109: $thisdir=~s-/[^/]*$--;
5110: foreach my $link (@rlinks) {
5111: unless (($link=~/^https?\:\/\//i) ||
5112: ($link=~/^\//) ||
5113: ($link=~/^javascript:/i) ||
5114: ($link=~/^mailto:/i) ||
5115: ($link=~/^\#/)) {
5116: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
5117: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
5118: }
5119: }
5120: # -------------------------------------------------- Deal with Applet codebases
5121: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
5122: return $output;
5123: }
5124:
5125: =pod
5126:
5127: =item * &get_student_view()
5128:
5129: show a snapshot of what student was looking at
5130:
5131: =cut
5132:
5133: sub get_student_view {
5134: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
5135: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
5136: my (%form);
5137: my @elements=('symb','courseid','domain','username');
5138: foreach my $element (@elements) {
5139: $form{'grade_'.$element}=eval '$'.$element #'
5140: }
5141: if (defined($moreenv)) {
5142: %form=(%form,%{$moreenv});
5143: }
5144: if (defined($target)) { $form{'grade_target'} = $target; }
5145: $feedurl=&Apache::lonnet::clutter($feedurl);
5146: if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
5147: $feedurl =~ s{^/adm/wrapper}{};
5148: }
5149: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
5150: $userview=~s/\<body[^\>]*\>//gi;
5151: $userview=~s/\<\/body\>//gi;
5152: $userview=~s/\<html\>//gi;
5153: $userview=~s/\<\/html\>//gi;
5154: $userview=~s/\<head\>//gi;
5155: $userview=~s/\<\/head\>//gi;
5156: $userview=~s/action\s*\=/would_be_action\=/gi;
5157: $userview=&relative_to_absolute($feedurl,$userview);
5158: if (wantarray) {
5159: return ($userview,$response);
5160: } else {
5161: return $userview;
5162: }
5163: }
5164:
5165: sub get_student_view_with_retries {
5166: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
5167:
5168: my $ok = 0; # True if we got a good response.
5169: my $content;
5170: my $response;
5171:
5172: # Try to get the student_view done. within the retries count:
5173:
5174: do {
5175: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
5176: $ok = $response->is_success;
5177: if (!$ok) {
5178: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
5179: }
5180: $retries--;
5181: } while (!$ok && ($retries > 0));
5182:
5183: if (!$ok) {
5184: $content = ''; # On error return an empty content.
5185: }
5186: if (wantarray) {
5187: return ($content, $response);
5188: } else {
5189: return $content;
5190: }
5191: }
5192:
5193: sub css_links {
5194: my ($currsymb,$level) = @_;
5195: my ($links,@symbs,%cssrefs,%httpref);
5196: if ($level eq 'map') {
5197: my $navmap = Apache::lonnavmaps::navmap->new();
5198: if (ref($navmap)) {
5199: my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
5200: my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
5201: foreach my $res (@resources) {
5202: if (ref($res) && $res->symb()) {
5203: push(@symbs,$res->symb());
5204: }
5205: }
5206: }
5207: } else {
5208: @symbs = ($currsymb);
5209: }
5210: foreach my $symb (@symbs) {
5211: my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
5212: if ($css_href =~ /\S/) {
5213: unless ($css_href =~ m{https?://}) {
5214: my $url = (&Apache::lonnet::decode_symb($symb))[-1];
5215: my $proburl = &Apache::lonnet::clutter($url);
5216: my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
5217: unless ($css_href =~ m{^/}) {
5218: $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
5219: }
5220: if ($css_href =~ m{^/(res|uploaded)/}) {
5221: unless (($httpref{'httpref.'.$css_href}) ||
5222: (&Apache::lonnet::is_on_map($css_href))) {
5223: my $thisurl = $proburl;
5224: if ($env{'httpref.'.$proburl}) {
5225: $thisurl = $env{'httpref.'.$proburl};
5226: }
5227: $httpref{'httpref.'.$css_href} = $thisurl;
5228: }
5229: }
5230: }
5231: $cssrefs{$css_href} = 1;
5232: }
5233: }
5234: if (keys(%httpref)) {
5235: &Apache::lonnet::appenv(\%httpref);
5236: }
5237: if (keys(%cssrefs)) {
5238: foreach my $css_href (keys(%cssrefs)) {
5239: next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
5240: $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
5241: }
5242: }
5243: return $links;
5244: }
5245:
5246: =pod
5247:
5248: =item * &get_student_answers()
5249:
5250: show a snapshot of how student was answering problem
5251:
5252: =cut
5253:
5254: sub get_student_answers {
5255: my ($symb,$username,$domain,$courseid,%form) = @_;
5256: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
5257: my (%moreenv);
5258: my @elements=('symb','courseid','domain','username');
5259: foreach my $element (@elements) {
5260: $moreenv{'grade_'.$element}=eval '$'.$element #'
5261: }
5262: $moreenv{'grade_target'}='answer';
5263: %moreenv=(%form,%moreenv);
5264: $feedurl = &Apache::lonnet::clutter($feedurl);
5265: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
5266: return $userview;
5267: }
5268:
5269: =pod
5270:
5271: =item * &submlink()
5272:
5273: Inputs: $text $uname $udom $symb $target
5274:
5275: Returns: A link to grades.pm such as to see the SUBM view of a student
5276:
5277: =cut
5278:
5279: ###############################################
5280: sub submlink {
5281: my ($text,$uname,$udom,$symb,$target)=@_;
5282: if (!($uname && $udom)) {
5283: (my $cursymb, my $courseid,$udom,$uname)=
5284: &Apache::lonnet::whichuser($symb);
5285: if (!$symb) { $symb=$cursymb; }
5286: }
5287: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5288: $symb=&escape($symb);
5289: if ($target) { $target=" target=\"$target\""; }
5290: return
5291: '<a href="/adm/grades?command=submission'.
5292: '&symb='.$symb.
5293: '&student='.$uname.
5294: '&userdom='.$udom.'"'.
5295: $target.'>'.$text.'</a>';
5296: }
5297: ##############################################
5298:
5299: =pod
5300:
5301: =item * &pgrdlink()
5302:
5303: Inputs: $text $uname $udom $symb $target
5304:
5305: Returns: A link to grades.pm such as to see the PGRD view of a student
5306:
5307: =cut
5308:
5309: ###############################################
5310: sub pgrdlink {
5311: my $link=&submlink(@_);
5312: $link=~s/(&command=submission)/$1&showgrading=yes/;
5313: return $link;
5314: }
5315: ##############################################
5316:
5317: =pod
5318:
5319: =item * &pprmlink()
5320:
5321: Inputs: $text $uname $udom $symb $target
5322:
5323: Returns: A link to parmset.pm such as to see the PPRM view of a
5324: student and a specific resource
5325:
5326: =cut
5327:
5328: ###############################################
5329: sub pprmlink {
5330: my ($text,$uname,$udom,$symb,$target)=@_;
5331: if (!($uname && $udom)) {
5332: (my $cursymb, my $courseid,$udom,$uname)=
5333: &Apache::lonnet::whichuser($symb);
5334: if (!$symb) { $symb=$cursymb; }
5335: }
5336: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
5337: $symb=&escape($symb);
5338: if ($target) { $target="target=\"$target\""; }
5339: return '<a href="/adm/parmset?command=set&'.
5340: 'symb='.$symb.'&uname='.$uname.
5341: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
5342: }
5343: ##############################################
5344:
5345: =pod
5346:
5347: =back
5348:
5349: =cut
5350:
5351: ###############################################
5352:
5353:
5354: sub timehash {
5355: my ($thistime) = @_;
5356: my $timezone = &Apache::lonlocal::gettimezone();
5357: my $dt = DateTime->from_epoch(epoch => $thistime)
5358: ->set_time_zone($timezone);
5359: my $wday = $dt->day_of_week();
5360: if ($wday == 7) { $wday = 0; }
5361: return ( 'second' => $dt->second(),
5362: 'minute' => $dt->minute(),
5363: 'hour' => $dt->hour(),
5364: 'day' => $dt->day_of_month(),
5365: 'month' => $dt->month(),
5366: 'year' => $dt->year(),
5367: 'weekday' => $wday,
5368: 'dayyear' => $dt->day_of_year(),
5369: 'dlsav' => $dt->is_dst() );
5370: }
5371:
5372: sub utc_string {
5373: my ($date)=@_;
5374: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
5375: }
5376:
5377: sub maketime {
5378: my %th=@_;
5379: my ($epoch_time,$timezone,$dt);
5380: $timezone = &Apache::lonlocal::gettimezone();
5381: eval {
5382: $dt = DateTime->new( year => $th{'year'},
5383: month => $th{'month'},
5384: day => $th{'day'},
5385: hour => $th{'hour'},
5386: minute => $th{'minute'},
5387: second => $th{'second'},
5388: time_zone => $timezone,
5389: );
5390: };
5391: if (!$@) {
5392: $epoch_time = $dt->epoch;
5393: if ($epoch_time) {
5394: return $epoch_time;
5395: }
5396: }
5397: return POSIX::mktime(
5398: ($th{'seconds'},$th{'minutes'},$th{'hours'},
5399: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
5400: }
5401:
5402: #########################################
5403:
5404: sub findallcourses {
5405: my ($roles,$uname,$udom) = @_;
5406: my %roles;
5407: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
5408: my %courses;
5409: my $now=time;
5410: if (!defined($uname)) {
5411: $uname = $env{'user.name'};
5412: }
5413: if (!defined($udom)) {
5414: $udom = $env{'user.domain'};
5415: }
5416: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
5417: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
5418: if (!%roles) {
5419: %roles = (
5420: cc => 1,
5421: co => 1,
5422: in => 1,
5423: ep => 1,
5424: ta => 1,
5425: cr => 1,
5426: st => 1,
5427: );
5428: }
5429: foreach my $entry (keys(%roleshash)) {
5430: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
5431: if ($trole =~ /^cr/) {
5432: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
5433: } else {
5434: next if (!exists($roles{$trole}));
5435: }
5436: if ($tend) {
5437: next if ($tend < $now);
5438: }
5439: if ($tstart) {
5440: next if ($tstart > $now);
5441: }
5442: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
5443: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
5444: my $value = $trole.'/'.$cdom.'/';
5445: if ($secpart eq '') {
5446: ($cnum,$role) = split(/_/,$cnumpart);
5447: $sec = 'none';
5448: $value .= $cnum.'/';
5449: } else {
5450: $cnum = $cnumpart;
5451: ($sec,$role) = split(/_/,$secpart);
5452: $value .= $cnum.'/'.$sec;
5453: }
5454: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5455: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5456: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5457: }
5458: } else {
5459: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5460: }
5461: }
5462: } else {
5463: foreach my $key (keys(%env)) {
5464: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
5465: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
5466: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
5467: next if ($role eq 'ca' || $role eq 'aa');
5468: next if (%roles && !exists($roles{$role}));
5469: my ($starttime,$endtime)=split(/\./,$env{$key});
5470: my $active=1;
5471: if ($starttime) {
5472: if ($now<$starttime) { $active=0; }
5473: }
5474: if ($endtime) {
5475: if ($now>$endtime) { $active=0; }
5476: }
5477: if ($active) {
5478: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
5479: if ($sec eq '') {
5480: $sec = 'none';
5481: } else {
5482: $value .= $sec;
5483: }
5484: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5485: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5486: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5487: }
5488: } else {
5489: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5490: }
5491: }
5492: }
5493: }
5494: }
5495: return %courses;
5496: }
5497:
5498: ###############################################
5499:
5500: sub blockcheck {
5501: my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5502: unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
5503: my ($has_evb,$check_ipaccess);
5504: my $dom = $env{'user.domain'};
5505: if ($env{'request.course.id'}) {
5506: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5507: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5508: my $checkrole = "cm./$cdom/$cnum";
5509: my $sec = $env{'request.course.sec'};
5510: if ($sec ne '') {
5511: $checkrole .= "/$sec";
5512: }
5513: if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
5514: ($env{'request.role'} !~ /^st/)) {
5515: $has_evb = 1;
5516: }
5517: unless ($has_evb) {
5518: if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
5519: ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
5520: if ($udom eq $cdom) {
5521: $check_ipaccess = 1;
5522: }
5523: }
5524: }
5525: } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
5526: ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
5527: my $checkrole;
5528: if ($env{'request.role.domain'} eq '') {
5529: $checkrole = "cm./$env{'user.domain'}/";
5530: } else {
5531: $checkrole = "cm./$env{'request.role.domain'}/";
5532: }
5533: if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
5534: $has_evb = 1;
5535: }
5536: }
5537: unless ($has_evb || $check_ipaccess) {
5538: my @machinedoms = &Apache::lonnet::current_machine_domains();
5539: if (($dom eq 'public') && ($activity eq 'port')) {
5540: $dom = $udom;
5541: }
5542: if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
5543: $check_ipaccess = 1;
5544: } else {
5545: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
5546: my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
5547: my $prim = &Apache::lonnet::domain($dom,'primary');
5548: my $intdom = &Apache::lonnet::internet_dom($prim);
5549: if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
5550: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
5551: $check_ipaccess = 1;
5552: }
5553: }
5554: }
5555: }
5556: if ($check_ipaccess) {
5557: my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
5558: unless (defined($cached)) {
5559: my %domconfig =
5560: &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
5561: $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
5562: }
5563: if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
5564: foreach my $id (keys(%{$ipaccessref})) {
5565: if (ref($ipaccessref->{$id}) eq 'HASH') {
5566: my $range = $ipaccessref->{$id}->{'ip'};
5567: if ($range) {
5568: if (&Apache::lonnet::ip_match($clientip,$range)) {
5569: if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
5570: if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
5571: return ('','','',$id,$dom);
5572: last;
5573: }
5574: }
5575: }
5576: }
5577: }
5578: }
5579: }
5580: }
5581: if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5582: return ();
5583: }
5584: }
5585: if (defined($udom) && defined($uname)) {
5586: # If uname and udom are for a course, check for blocks in the course.
5587: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
5588: my ($startblock,$endblock,$triggerblock) =
5589: &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
5590: return ($startblock,$endblock,$triggerblock);
5591: }
5592: } else {
5593: $udom = $env{'user.domain'};
5594: $uname = $env{'user.name'};
5595: }
5596:
5597: my $startblock = 0;
5598: my $endblock = 0;
5599: my $triggerblock = '';
5600: my %live_courses;
5601: unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
5602: %live_courses = &findallcourses(undef,$uname,$udom);
5603: }
5604:
5605: # If uname is for a user, and activity is course-specific, i.e.,
5606: # boards, chat or groups, check for blocking in current course only.
5607:
5608: if (($activity eq 'boards' || $activity eq 'chat' ||
5609: $activity eq 'groups' || $activity eq 'printout' ||
5610: $activity eq 'search' || $activity eq 'reinit' ||
5611: $activity eq 'alert') &&
5612: ($env{'request.course.id'})) {
5613: foreach my $key (keys(%live_courses)) {
5614: if ($key ne $env{'request.course.id'}) {
5615: delete($live_courses{$key});
5616: }
5617: }
5618: }
5619:
5620: my $otheruser = 0;
5621: my %own_courses;
5622: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
5623: # Resource belongs to user other than current user.
5624: $otheruser = 1;
5625: # Gather courses for current user
5626: %own_courses =
5627: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
5628: }
5629:
5630: # Gather active course roles - course coordinator, instructor,
5631: # exam proctor, ta, student, or custom role.
5632:
5633: foreach my $course (keys(%live_courses)) {
5634: my ($cdom,$cnum);
5635: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5636: $cdom = $env{'course.'.$course.'.domain'};
5637: $cnum = $env{'course.'.$course.'.num'};
5638: } else {
5639: ($cdom,$cnum) = split(/_/,$course);
5640: }
5641: my $no_ownblock = 0;
5642: my $no_userblock = 0;
5643: if ($otheruser && $activity ne 'com') {
5644: # Check if current user has 'evb' priv for this
5645: if (defined($own_courses{$course})) {
5646: foreach my $sec (keys(%{$own_courses{$course}})) {
5647: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5648: if ($sec ne 'none') {
5649: $checkrole .= '/'.$sec;
5650: }
5651: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5652: $no_ownblock = 1;
5653: last;
5654: }
5655: }
5656: }
5657: # if they have 'evb' priv and are currently not playing student
5658: next if (($no_ownblock) &&
5659: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5660: }
5661: foreach my $sec (keys(%{$live_courses{$course}})) {
5662: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5663: if ($sec ne 'none') {
5664: $checkrole .= '/'.$sec;
5665: }
5666: if ($otheruser) {
5667: # Resource belongs to user other than current user.
5668: # Assemble privs for that user, and check for 'evb' priv.
5669: my (%allroles,%userroles);
5670: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5671: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5672: my ($trole,$tdom,$tnum,$tsec);
5673: if ($entry =~ /^cr/) {
5674: ($trole,$tdom,$tnum,$tsec) =
5675: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5676: } else {
5677: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5678: }
5679: my ($spec,$area,$trest);
5680: $area = '/'.$tdom.'/'.$tnum;
5681: $trest = $tnum;
5682: if ($tsec ne '') {
5683: $area .= '/'.$tsec;
5684: $trest .= '/'.$tsec;
5685: }
5686: $spec = $trole.'.'.$area;
5687: if ($trole =~ /^cr/) {
5688: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5689: $tdom,$spec,$trest,$area);
5690: } else {
5691: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5692: $tdom,$spec,$trest,$area);
5693: }
5694: }
5695: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5696: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5697: if ($1) {
5698: $no_userblock = 1;
5699: last;
5700: }
5701: }
5702: }
5703: } else {
5704: # Resource belongs to current user
5705: # Check for 'evb' priv via lonnet::allowed().
5706: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5707: $no_ownblock = 1;
5708: last;
5709: }
5710: }
5711: }
5712: # if they have the evb priv and are currently not playing student
5713: next if (($no_ownblock) &&
5714: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5715: next if ($no_userblock);
5716:
5717: # Retrieve blocking times and identity of blocker for course
5718: # of specified user, unless user has 'evb' privilege.
5719:
5720: my ($start,$end,$trigger) =
5721: &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
5722: if (($start != 0) &&
5723: (($startblock == 0) || ($startblock > $start))) {
5724: $startblock = $start;
5725: if ($trigger ne '') {
5726: $triggerblock = $trigger;
5727: }
5728: }
5729: if (($end != 0) &&
5730: (($endblock == 0) || ($endblock < $end))) {
5731: $endblock = $end;
5732: if ($trigger ne '') {
5733: $triggerblock = $trigger;
5734: }
5735: }
5736: }
5737: return ($startblock,$endblock,$triggerblock);
5738: }
5739:
5740: sub get_blocks {
5741: my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
5742: my $startblock = 0;
5743: my $endblock = 0;
5744: my $triggerblock = '';
5745: my $course = $cdom.'_'.$cnum;
5746: $setters->{$course} = {};
5747: $setters->{$course}{'staff'} = [];
5748: $setters->{$course}{'times'} = [];
5749: $setters->{$course}{'triggers'} = [];
5750: my (@blockers,%triggered);
5751: my $now = time;
5752: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5753: if ($activity eq 'docs') {
5754: my ($blocked,$nosymbcache,$noenccheck);
5755: if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
5756: $blocked = 1;
5757: $nosymbcache = 1;
5758: $noenccheck = 1;
5759: }
5760: @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
5761: foreach my $block (@blockers) {
5762: if ($block =~ /^firstaccess____(.+)$/) {
5763: my $item = $1;
5764: my $type = 'map';
5765: my $timersymb = $item;
5766: if ($item eq 'course') {
5767: $type = 'course';
5768: } elsif ($item =~ /___\d+___/) {
5769: $type = 'resource';
5770: } else {
5771: $timersymb = &Apache::lonnet::symbread($item);
5772: }
5773: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5774: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5775: $triggered{$block} = {
5776: start => $start,
5777: end => $end,
5778: type => $type,
5779: };
5780: }
5781: }
5782: } else {
5783: foreach my $block (keys(%commblocks)) {
5784: if ($block =~ m/^(\d+)____(\d+)$/) {
5785: my ($start,$end) = ($1,$2);
5786: if ($start <= time && $end >= time) {
5787: if (ref($commblocks{$block}) eq 'HASH') {
5788: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5789: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5790: unless(grep(/^\Q$block\E$/,@blockers)) {
5791: push(@blockers,$block);
5792: }
5793: }
5794: }
5795: }
5796: }
5797: } elsif ($block =~ /^firstaccess____(.+)$/) {
5798: my $item = $1;
5799: my $timersymb = $item;
5800: my $type = 'map';
5801: if ($item eq 'course') {
5802: $type = 'course';
5803: } elsif ($item =~ /___\d+___/) {
5804: $type = 'resource';
5805: } else {
5806: $timersymb = &Apache::lonnet::symbread($item);
5807: }
5808: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5809: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5810: if ($start && $end) {
5811: if (($start <= time) && ($end >= time)) {
5812: if (ref($commblocks{$block}) eq 'HASH') {
5813: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5814: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5815: unless(grep(/^\Q$block\E$/,@blockers)) {
5816: push(@blockers,$block);
5817: $triggered{$block} = {
5818: start => $start,
5819: end => $end,
5820: type => $type,
5821: };
5822: }
5823: }
5824: }
5825: }
5826: }
5827: }
5828: }
5829: }
5830: }
5831: foreach my $blocker (@blockers) {
5832: my ($staff_name,$staff_dom,$title,$blocks) =
5833: &parse_block_record($commblocks{$blocker});
5834: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5835: my ($start,$end,$triggertype);
5836: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5837: ($start,$end) = ($1,$2);
5838: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5839: $start = $triggered{$blocker}{'start'};
5840: $end = $triggered{$blocker}{'end'};
5841: $triggertype = $triggered{$blocker}{'type'};
5842: }
5843: if ($start) {
5844: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5845: if ($triggertype) {
5846: push(@{$$setters{$course}{'triggers'}},$triggertype);
5847: } else {
5848: push(@{$$setters{$course}{'triggers'}},0);
5849: }
5850: if ( ($startblock == 0) || ($startblock > $start) ) {
5851: $startblock = $start;
5852: if ($triggertype) {
5853: $triggerblock = $blocker;
5854: }
5855: }
5856: if ( ($endblock == 0) || ($endblock < $end) ) {
5857: $endblock = $end;
5858: if ($triggertype) {
5859: $triggerblock = $blocker;
5860: }
5861: }
5862: }
5863: }
5864: return ($startblock,$endblock,$triggerblock);
5865: }
5866:
5867: sub parse_block_record {
5868: my ($record) = @_;
5869: my ($setuname,$setudom,$title,$blocks);
5870: if (ref($record) eq 'HASH') {
5871: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5872: $title = &unescape($record->{'event'});
5873: $blocks = $record->{'blocks'};
5874: } else {
5875: my @data = split(/:/,$record,3);
5876: if (scalar(@data) eq 2) {
5877: $title = $data[1];
5878: ($setuname,$setudom) = split(/@/,$data[0]);
5879: } else {
5880: ($setuname,$setudom,$title) = @data;
5881: }
5882: $blocks = { 'com' => 'on' };
5883: }
5884: return ($setuname,$setudom,$title,$blocks);
5885: }
5886:
5887: sub blocking_status {
5888: my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
5889: my %setters;
5890:
5891: # check for active blocking
5892: if ($clientip eq '') {
5893: $clientip = &Apache::lonnet::get_requestor_ip();
5894: }
5895: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
5896: &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
5897: my $blocked = 0;
5898: if (($startblock && $endblock) || ($by_ip)) {
5899: $blocked = 1;
5900: }
5901:
5902: # caller just wants to know whether a block is active
5903: if (!wantarray) { return $blocked; }
5904:
5905: # build a link to a popup window containing the details
5906: my $querystring = "?activity=$activity";
5907: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
5908: if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
5909: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5910: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5911: } elsif ($activity eq 'docs') {
5912: my $showurl = &Apache::lonenc::check_encrypt($url);
5913: $querystring .= '&url='.&HTML::Entities::encode($showurl,'\'&"<>');
5914: if ($symb) {
5915: my $showsymb = &Apache::lonenc::check_encrypt($symb);
5916: $querystring .= '&symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
5917: }
5918: }
5919:
5920: my $output .= <<'END_MYBLOCK';
5921: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5922: var options = "width=" + w + ",height=" + h + ",";
5923: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5924: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5925: var newWin = window.open(url, wdwName, options);
5926: newWin.focus();
5927: }
5928: END_MYBLOCK
5929:
5930: $output = Apache::lonhtmlcommon::scripttag($output);
5931:
5932: my $popupUrl = "/adm/blockingstatus/$querystring";
5933: my $text = &mt('Communication Blocked');
5934: my $class = 'LC_comblock';
5935: if ($activity eq 'docs') {
5936: $text = &mt('Content Access Blocked');
5937: $class = '';
5938: } elsif ($activity eq 'printout') {
5939: $text = &mt('Printing Blocked');
5940: } elsif ($activity eq 'passwd') {
5941: $text = &mt('Password Changing Blocked');
5942: } elsif ($activity eq 'grades') {
5943: $text = &mt('Gradebook Blocked');
5944: } elsif ($activity eq 'search') {
5945: $text = &mt('Search Blocked');
5946: } elsif ($activity eq 'alert') {
5947: $text = &mt('Checking Critical Messages Blocked');
5948: } elsif ($activity eq 'reinit') {
5949: $text = &mt('Checking Course Update Blocked');
5950: } elsif ($activity eq 'about') {
5951: $text = &mt('Access to User Information Pages Blocked');
5952: } elsif ($activity eq 'wishlist') {
5953: $text = &mt('Access to Stored Links Blocked');
5954: } elsif ($activity eq 'annotate') {
5955: $text = &mt('Access to Annotations Blocked');
5956: }
5957: $output .= <<"END_BLOCK";
5958: <div class='$class'>
5959: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5960: title='$text'>
5961: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5962: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5963: title='$text'>$text</a>
5964: </div>
5965:
5966: END_BLOCK
5967:
5968: return ($blocked, $output);
5969: }
5970:
5971: ###############################################
5972:
5973: sub check_ip_acc {
5974: my ($acc,$clientip)=@_;
5975: &Apache::lonxml::debug("acc is $acc");
5976: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5977: return 1;
5978: }
5979: my ($ip,$allowed);
5980: if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
5981: ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
5982: $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
5983: } else {
5984: my $remote_ip = &Apache::lonnet::get_requestor_ip();
5985: $ip = $remote_ip || $env{'request.host'} || $clientip;
5986: }
5987:
5988: my $name;
5989: my %access = (
5990: allowfrom => 1,
5991: denyfrom => 0,
5992: );
5993: my @allows;
5994: my @denies;
5995: foreach my $item (split(',',$acc)) {
5996: $item =~ s/^\s*//;
5997: $item =~ s/\s*$//;
5998: my $pattern;
5999: if ($item =~ /^\!(.+)$/) {
6000: push(@denies,$1);
6001: } else {
6002: push(@allows,$item);
6003: }
6004: }
6005: my $numdenies = scalar(@denies);
6006: my $numallows = scalar(@allows);
6007: my $count = 0;
6008: foreach my $pattern (@denies,@allows) {
6009: $count ++;
6010: my $acctype = 'allowfrom';
6011: if ($count <= $numdenies) {
6012: $acctype = 'denyfrom';
6013: }
6014: if ($pattern =~ /\*$/) {
6015: #35.8.*
6016: $pattern=~s/\*//;
6017: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
6018: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
6019: #35.8.3.[34-56]
6020: my $low=$2;
6021: my $high=$3;
6022: $pattern=$1;
6023: if ($ip =~ /^\Q$pattern\E/) {
6024: my $last=(split(/\./,$ip))[3];
6025: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
6026: }
6027: } elsif ($pattern =~ /^\*/) {
6028: #*.msu.edu
6029: $pattern=~s/\*//;
6030: if (!defined($name)) {
6031: use Socket;
6032: my $netaddr=inet_aton($ip);
6033: ($name)=gethostbyaddr($netaddr,AF_INET);
6034: }
6035: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
6036: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
6037: #127.0.0.1
6038: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
6039: } else {
6040: #some.name.com
6041: if (!defined($name)) {
6042: use Socket;
6043: my $netaddr=inet_aton($ip);
6044: ($name)=gethostbyaddr($netaddr,AF_INET);
6045: }
6046: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
6047: }
6048: if ($allowed =~ /^(0|1)$/) { last; }
6049: }
6050: if ($allowed eq '') {
6051: if ($numdenies && !$numallows) {
6052: $allowed = 1;
6053: } else {
6054: $allowed = 0;
6055: }
6056: }
6057: return $allowed;
6058: }
6059:
6060: ###############################################
6061:
6062: =pod
6063:
6064: =head1 Domain Template Functions
6065:
6066: =over 4
6067:
6068: =item * &determinedomain()
6069:
6070: Inputs: $domain (usually will be undef)
6071:
6072: Returns: Determines which domain should be used for designs
6073:
6074: =cut
6075:
6076: ###############################################
6077: sub determinedomain {
6078: my $domain=shift;
6079: if (! $domain) {
6080: # Determine domain if we have not been given one
6081: $domain = &Apache::lonnet::default_login_domain();
6082: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
6083: if ($env{'request.role.domain'}) {
6084: $domain=$env{'request.role.domain'};
6085: }
6086: }
6087: return $domain;
6088: }
6089: ###############################################
6090:
6091: sub devalidate_domconfig_cache {
6092: my ($udom)=@_;
6093: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
6094: }
6095:
6096: # ---------------------- Get domain configuration for a domain
6097: sub get_domainconf {
6098: my ($udom) = @_;
6099: my $cachetime=1800;
6100: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
6101: if (defined($cached)) { return %{$result}; }
6102:
6103: my %domconfig = &Apache::lonnet::get_dom('configuration',
6104: ['login','rolecolors','autoenroll'],$udom);
6105: my (%designhash,%legacy);
6106: if (keys(%domconfig) > 0) {
6107: if (ref($domconfig{'login'}) eq 'HASH') {
6108: if (keys(%{$domconfig{'login'}})) {
6109: foreach my $key (keys(%{$domconfig{'login'}})) {
6110: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6111: if (($key eq 'loginvia') || ($key eq 'headtag')) {
6112: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6113: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
6114: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
6115: if ($key eq 'loginvia') {
6116: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
6117: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
6118: $designhash{$udom.'.login.loginvia'} = $server;
6119: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
6120:
6121: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
6122: } else {
6123: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
6124: }
6125: }
6126: } elsif ($key eq 'headtag') {
6127: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
6128: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
6129: }
6130: }
6131: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
6132: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
6133: }
6134: }
6135: }
6136: }
6137: } elsif ($key eq 'saml') {
6138: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
6139: foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
6140: if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
6141: $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
6142: foreach my $item ('text','img','alt','url','title','window','notsso') {
6143: $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
6144: }
6145: }
6146: }
6147: }
6148: } else {
6149: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
6150: $designhash{$udom.'.login.'.$key.'_'.$img} =
6151: $domconfig{'login'}{$key}{$img};
6152: }
6153: }
6154: } else {
6155: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
6156: }
6157: }
6158: } else {
6159: $legacy{'login'} = 1;
6160: }
6161: } else {
6162: $legacy{'login'} = 1;
6163: }
6164: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
6165: if (keys(%{$domconfig{'rolecolors'}})) {
6166: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
6167: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
6168: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
6169: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
6170: }
6171: }
6172: }
6173: } else {
6174: $legacy{'rolecolors'} = 1;
6175: }
6176: } else {
6177: $legacy{'rolecolors'} = 1;
6178: }
6179: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6180: if ($domconfig{'autoenroll'}{'co-owners'}) {
6181: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
6182: }
6183: }
6184: if (keys(%legacy) > 0) {
6185: my %legacyhash = &get_legacy_domconf($udom);
6186: foreach my $item (keys(%legacyhash)) {
6187: if ($item =~ /^\Q$udom\E\.login/) {
6188: if ($legacy{'login'}) {
6189: $designhash{$item} = $legacyhash{$item};
6190: }
6191: } else {
6192: if ($legacy{'rolecolors'}) {
6193: $designhash{$item} = $legacyhash{$item};
6194: }
6195: }
6196: }
6197: }
6198: } else {
6199: %designhash = &get_legacy_domconf($udom);
6200: }
6201: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
6202: $cachetime);
6203: return %designhash;
6204: }
6205:
6206: sub get_legacy_domconf {
6207: my ($udom) = @_;
6208: my %legacyhash;
6209: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
6210: my $designfile = $designdir.'/'.$udom.'.tab';
6211: if (-e $designfile) {
6212: if ( open (my $fh,'<',$designfile) ) {
6213: while (my $line = <$fh>) {
6214: next if ($line =~ /^\#/);
6215: chomp($line);
6216: my ($key,$val)=(split(/\=/,$line));
6217: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
6218: }
6219: close($fh);
6220: }
6221: }
6222: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
6223: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
6224: }
6225: return %legacyhash;
6226: }
6227:
6228: =pod
6229:
6230: =item * &domainlogo()
6231:
6232: Inputs: $domain (usually will be undef)
6233:
6234: Returns: A link to a domain logo, if the domain logo exists.
6235: If the domain logo does not exist, a description of the domain.
6236:
6237: =cut
6238:
6239: ###############################################
6240: sub domainlogo {
6241: my $domain = &determinedomain(shift);
6242: my %designhash = &get_domainconf($domain);
6243: # See if there is a logo
6244: if ($designhash{$domain.'.login.domlogo'} ne '') {
6245: my $imgsrc = $designhash{$domain.'.login.domlogo'};
6246: if ($imgsrc =~ m{^/(adm|res)/}) {
6247: if ($imgsrc =~ m{^/res/}) {
6248: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
6249: &Apache::lonnet::repcopy($local_name);
6250: }
6251: $imgsrc = &lonhttpdurl($imgsrc);
6252: }
6253: my $alttext = $domain;
6254: if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
6255: $alttext = $designhash{$domain.'.login.alttext_domlogo'};
6256: }
6257: return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
6258: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
6259: return &Apache::lonnet::domain($domain,'description');
6260: } else {
6261: return '';
6262: }
6263: }
6264: ##############################################
6265:
6266: =pod
6267:
6268: =item * &designparm()
6269:
6270: Inputs: $which parameter; $domain (usually will be undef)
6271:
6272: Returns: value of designparamter $which
6273:
6274: =cut
6275:
6276:
6277: ##############################################
6278: sub designparm {
6279: my ($which,$domain)=@_;
6280: if (exists($env{'environment.color.'.$which})) {
6281: return $env{'environment.color.'.$which};
6282: }
6283: $domain=&determinedomain($domain);
6284: my %domdesign;
6285: unless ($domain eq 'public') {
6286: %domdesign = &get_domainconf($domain);
6287: }
6288: my $output;
6289: if ($domdesign{$domain.'.'.$which} ne '') {
6290: $output = $domdesign{$domain.'.'.$which};
6291: } else {
6292: $output = $defaultdesign{$which};
6293: }
6294: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
6295: ($which =~ /login\.(img|logo|domlogo|login)/)) {
6296: if ($output =~ m{^/(adm|res)/}) {
6297: if ($output =~ m{^/res/}) {
6298: my $local_name = &Apache::lonnet::filelocation('',$output);
6299: &Apache::lonnet::repcopy($local_name);
6300: }
6301: $output = &lonhttpdurl($output);
6302: }
6303: }
6304: return $output;
6305: }
6306:
6307: ##############################################
6308: =pod
6309:
6310: =item * &authorspace()
6311:
6312: Inputs: $url (usually will be undef).
6313:
6314: Returns: Path to Authoring Space containing the resource or
6315: directory being viewed (or for which action is being taken).
6316: If $url is provided, and begins /priv/<domain>/<uname>
6317: the path will be that portion of the $context argument.
6318: Otherwise the path will be for the author space of the current
6319: user when the current role is author, or for that of the
6320: co-author/assistant co-author space when the current role
6321: is co-author or assistant co-author.
6322:
6323: =cut
6324:
6325: sub authorspace {
6326: my ($url) = @_;
6327: if ($url ne '') {
6328: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
6329: return $1;
6330: }
6331: }
6332: my $caname = '';
6333: my $cadom = '';
6334: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
6335: ($cadom,$caname) =
6336: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
6337: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
6338: $caname = $env{'user.name'};
6339: $cadom = $env{'user.domain'};
6340: }
6341: if (($caname ne '') && ($cadom ne '')) {
6342: return "/priv/$cadom/$caname/";
6343: }
6344: return;
6345: }
6346:
6347: ##############################################
6348: =pod
6349:
6350: =item * &head_subbox()
6351:
6352: Inputs: $content (contains HTML code with page functions, etc.)
6353:
6354: Returns: HTML div with $content
6355: To be included in page header
6356:
6357: =cut
6358:
6359: sub head_subbox {
6360: my ($content)=@_;
6361: my $output =
6362: '<div class="LC_head_subbox">'
6363: .$content
6364: .'</div>'
6365: }
6366:
6367: ##############################################
6368: =pod
6369:
6370: =item * &CSTR_pageheader()
6371:
6372: Input: (optional) filename from which breadcrumb trail is built.
6373: In most cases no input as needed, as $env{'request.filename'}
6374: is appropriate for use in building the breadcrumb trail.
6375: frameset flag
6376: If page header is being requested for use in a frameset, then
6377: the second (option) argument -- frameset will be true, and
6378: the target attribute set for links should be target="_parent".
6379: If $title is supplied as the thitd arg, that will be used to
6380: the left of the breadcrumbs tail for the current path.
6381:
6382: Returns: HTML div with CSTR path and recent box
6383: To be included on Authoring Space pages
6384:
6385: =cut
6386:
6387: sub CSTR_pageheader {
6388: my ($trailfile,$frameset,$title) = @_;
6389: if ($trailfile eq '') {
6390: $trailfile = $env{'request.filename'};
6391: }
6392:
6393: # this is for resources; directories have customtitle, and crumbs
6394: # and select recent are created in lonpubdir.pm
6395:
6396: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
6397: my ($udom,$uname,$thisdisfn)=
6398: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
6399: my $formaction = "/priv/$udom/$uname/$thisdisfn";
6400: $formaction =~ s{/+}{/}g;
6401:
6402: my $parentpath = '';
6403: my $lastitem = '';
6404: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
6405: $parentpath = $1;
6406: $lastitem = $2;
6407: } else {
6408: $lastitem = $thisdisfn;
6409: }
6410:
6411: my $crsauthor;
6412: if (($env{'request.course.id'}) &&
6413: ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
6414: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
6415: $crsauthor = 1;
6416: if ($title eq '') {
6417: $title = &mt('Course Authoring Space');
6418: }
6419: } elsif ($title eq '') {
6420: $title = &mt('Authoring Space');
6421: }
6422:
6423: my ($target,$crumbtarget) = (' target="_top"','_top');
6424: if ($frameset) {
6425: $target = ' target="_parent"';
6426: $crumbtarget = '_parent';
6427: } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
6428: $target = '';
6429: $crumbtarget = '';
6430: } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
6431: $target = ' target="'.$env{'request.deeplink.target'}.'"';
6432: $crumbtarget = $env{'request.deeplink.target'};
6433: }
6434:
6435: my $output =
6436: '<div>'
6437: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
6438: .'<b>'.$title.'</b> '
6439: .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
6440: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
6441:
6442: if ($lastitem) {
6443: $output .=
6444: '<span class="LC_filename">'
6445: .$lastitem
6446: .'</span>';
6447: }
6448:
6449: if ($crsauthor) {
6450: $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
6451: } else {
6452: $output .=
6453: '<br />'
6454: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
6455: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
6456: .'</form>'
6457: .&Apache::lonmenu::constspaceform($frameset);
6458: }
6459: $output .= '</div>';
6460:
6461: return $output;
6462: }
6463:
6464: sub nocodemirror {
6465: my $nocodem = $env{'environment.nocodemirror'};
6466: unless ($nocodem) {
6467: my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
6468: if ($domdefs{'nocodemirror'}) {
6469: $nocodem = 'yes';
6470: }
6471: }
6472: return $nocodem;
6473: }
6474:
6475: ###############################################
6476: ###############################################
6477:
6478: =pod
6479:
6480: =back
6481:
6482: =head1 HTML Helpers
6483:
6484: =over 4
6485:
6486: =item * &bodytag()
6487:
6488: Returns a uniform header for LON-CAPA web pages.
6489:
6490: Inputs:
6491:
6492: =over 4
6493:
6494: =item * $title, A title to be displayed on the page.
6495:
6496: =item * $function, the current role (can be undef).
6497:
6498: =item * $addentries, extra parameters for the <body> tag.
6499:
6500: =item * $bodyonly, if defined, only return the <body> tag.
6501:
6502: =item * $domain, if defined, force a given domain.
6503:
6504: =item * $forcereg, if page should register as content page (relevant for
6505: text interface only)
6506:
6507: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
6508: navigational links
6509:
6510: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
6511:
6512: =item * $args, optional argument valid values are
6513: no_auto_mt_title -> prevents &mt()ing the title arg
6514: use_absolute -> for external resource or syllabus, this will
6515: contain https://<hostname> if server uses
6516: https (as per hosts.tab), but request is for http
6517: hostname -> hostname, from $r->hostname().
6518:
6519: =item * $advtoolsref, optional argument, ref to an array containing
6520: inlineremote items to be added in "Functions" menu below
6521: breadcrumbs.
6522:
6523: =item * $ltiscope, optional argument, will be one of: resource, map or
6524: course, if LON-CAPA is in LTI Provider context. Value is
6525: the scope of use, i.e., launch was for access to a single, a map
6526: or the entire course.
6527:
6528: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
6529: context, this will contain the URL for the landing item in
6530: the course, after launch from an LTI Consumer
6531:
6532: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
6533: context, this will contain a reference to hash of items
6534: to be included in the page header and/or inline menu.
6535:
6536: =item * $menucoll, optional argument, if specific menu collection is in
6537: effect, either set as the default for the course, or set for
6538: the deeplink paramater for $env{'request.deeplink.login'}
6539: then $menucoll will be the number of that collection.
6540:
6541: =item * $menuref, optional argument, reference to a hash, containing the
6542: menu options included for the menu in effect, based on the
6543: configuration for the numbered menu collection in use.
6544:
6545: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
6546: within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
6547: if so, $showncrumbsref is set there to 1, and will propagate back
6548: via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
6549: being called a second time.
6550:
6551: =back
6552:
6553: Returns: A uniform header for LON-CAPA web pages.
6554: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
6555: If $bodyonly is undef or zero, an html string containing a <body> tag and
6556: other decorations will be returned.
6557:
6558: =cut
6559:
6560: sub bodytag {
6561: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
6562: $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
6563: $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
6564:
6565: my $public;
6566: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
6567: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
6568: $public = 1;
6569: }
6570: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
6571: my $httphost = $args->{'use_absolute'};
6572: my $hostname = $args->{'hostname'};
6573:
6574: $function = &get_users_function() if (!$function);
6575: my $img = &designparm($function.'.img',$domain);
6576: my $font = &designparm($function.'.font',$domain);
6577: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
6578:
6579: my %design = ( 'style' => 'margin-top: 0',
6580: 'bgcolor' => $pgbg,
6581: 'text' => $font,
6582: 'alink' => &designparm($function.'.alink',$domain),
6583: 'vlink' => &designparm($function.'.vlink',$domain),
6584: 'link' => &designparm($function.'.link',$domain),);
6585: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
6586:
6587: # role and realm
6588: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
6589: if ($realm) {
6590: $realm = '/'.$realm;
6591: }
6592: if ($role eq 'ca') {
6593: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
6594: $realm = &plainname($rname,$rdom);
6595: }
6596: # realm
6597: my ($cid,$sec);
6598: if ($env{'request.course.id'}) {
6599: $cid = $env{'request.course.id'};
6600: if ($env{'request.course.sec'}) {
6601: $sec = $env{'request.course.sec'};
6602: }
6603: } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
6604: if (&Apache::lonnet::is_course($1,$2)) {
6605: $cid = $1.'_'.$2;
6606: $sec = $3;
6607: }
6608: }
6609: if ($cid) {
6610: if ($env{'request.role'} !~ /^cr/) {
6611: $role = &Apache::lonnet::plaintext($role,&course_type());
6612: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
6613: if ($env{'request.role.desc'}) {
6614: $role = $env{'request.role.desc'};
6615: } else {
6616: $role = &mt('Helpdesk[_1]',' '.$2);
6617: }
6618: } else {
6619: $role = (split(/\//,$role,4))[-1];
6620: }
6621: if ($sec) {
6622: $role .= (' 'x2).'- '.&mt('section:').' '.$sec;
6623: }
6624: $realm = $env{'course.'.$cid.'.description'};
6625: } else {
6626: $role = &Apache::lonnet::plaintext($role);
6627: }
6628:
6629: if (!$realm) { $realm=' '; }
6630:
6631: my $extra_body_attr = &make_attr_string($forcereg,\%design);
6632:
6633: # construct main body tag
6634: my $bodytag = "<body $extra_body_attr>".
6635: &Apache::lontexconvert::init_math_support();
6636:
6637: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6638:
6639: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
6640: return $bodytag;
6641: }
6642:
6643: if ($public) {
6644: undef($role);
6645: }
6646:
6647: my $showcrstitle = 1;
6648: if (($cid) && ($env{'request.lti.login'})) {
6649: if (ref($ltimenu) eq 'HASH') {
6650: unless ($ltimenu->{'role'}) {
6651: undef($role);
6652: }
6653: unless ($ltimenu->{'coursetitle'}) {
6654: $realm=' ';
6655: $showcrstitle = 0;
6656: }
6657: }
6658: } elsif (($cid) && ($menucoll)) {
6659: if (ref($menuref) eq 'HASH') {
6660: unless ($menuref->{'role'}) {
6661: undef($role);
6662: }
6663: unless ($menuref->{'crs'}) {
6664: $realm=' ';
6665: $showcrstitle = 0;
6666: }
6667: }
6668: }
6669:
6670: my $titleinfo = '<h1>'.$title.'</h1>';
6671: #
6672: # Extra info if you are the DC
6673: my $dc_info = '';
6674: if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
6675: (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
6676: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
6677: $dc_info =~ s/\s+$//;
6678: }
6679:
6680: my $crstype;
6681: if ($cid) {
6682: $crstype = $env{'course.'.$cid.'.type'};
6683: } elsif ($args->{'crstype'}) {
6684: $crstype = $args->{'crstype'};
6685: }
6686: if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
6687: undef($role);
6688: } else {
6689: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
6690: }
6691:
6692: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
6693:
6694: # if ($env{'request.state'} eq 'construct') {
6695: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
6696: # }
6697:
6698: $bodytag .= Apache::lonhtmlcommon::scripttag(
6699: Apache::lonmenu::utilityfunctions($httphost), 'start');
6700:
6701: unless ($args->{'no_primary_menu'}) {
6702: my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
6703: $args->{'links_disabled'},
6704: $args->{'links_target'});
6705:
6706: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
6707: if ($dc_info) {
6708: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
6709: }
6710: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
6711: <em>$realm</em> $dc_info</div>|;
6712: return $bodytag;
6713: }
6714:
6715: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
6716: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
6717: }
6718:
6719: $bodytag .= $right;
6720:
6721: if ($dc_info) {
6722: $dc_info = &dc_courseid_toggle($dc_info);
6723: }
6724: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
6725: }
6726:
6727: #if directed to not display the secondary menu, don't.
6728: if ($args->{'no_secondary_menu'}) {
6729: return $bodytag;
6730: }
6731: #don't show menus for public users
6732: if (!$public){
6733: unless ($args->{'no_inline_menu'}) {
6734: $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
6735: $args->{'no_primary_menu'},
6736: $menucoll,$menuref,
6737: $args->{'links_disabled'},
6738: $args->{'links_target'});
6739: }
6740: $bodytag .= Apache::lonmenu::serverform();
6741: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6742: if ($env{'request.state'} eq 'construct') {
6743: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
6744: $args->{'bread_crumbs'},'','',$hostname,
6745: $ltiscope,$ltiuri,$showncrumbsref);
6746: } elsif ($forcereg) {
6747: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
6748: $args->{'group'},$args->{'hide_buttons'},
6749: $hostname,$ltiscope,$ltiuri,$showncrumbsref);
6750: } else {
6751: $bodytag .=
6752: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6753: $forcereg,$args->{'group'},
6754: $args->{'bread_crumbs'},
6755: $advtoolsref,'',$hostname);
6756: }
6757: }else{
6758: # this is to seperate menu from content when there's no secondary
6759: # menu. Especially needed for public accessible ressources.
6760: $bodytag .= '<hr style="clear:both" />';
6761: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6762: }
6763:
6764: return $bodytag;
6765: }
6766:
6767: sub dc_courseid_toggle {
6768: my ($dc_info) = @_;
6769: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
6770: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
6771: &mt('(More ...)').'</a></span>'.
6772: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
6773: }
6774:
6775: sub make_attr_string {
6776: my ($register,$attr_ref) = @_;
6777:
6778: if ($attr_ref && !ref($attr_ref)) {
6779: die("addentries Must be a hash ref ".
6780: join(':',caller(1))." ".
6781: join(':',caller(0))." ");
6782: }
6783:
6784: if ($register) {
6785: my ($on_load,$on_unload);
6786: foreach my $key (keys(%{$attr_ref})) {
6787: if (lc($key) eq 'onload') {
6788: $on_load.=$attr_ref->{$key}.';';
6789: delete($attr_ref->{$key});
6790:
6791: } elsif (lc($key) eq 'onunload') {
6792: $on_unload.=$attr_ref->{$key}.';';
6793: delete($attr_ref->{$key});
6794: }
6795: }
6796: $attr_ref->{'onload'} = $on_load;
6797: $attr_ref->{'onunload'}= $on_unload;
6798: }
6799:
6800: my $attr_string;
6801: foreach my $attr (sort(keys(%$attr_ref))) {
6802: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6803: }
6804: return $attr_string;
6805: }
6806:
6807:
6808: ###############################################
6809: ###############################################
6810:
6811: =pod
6812:
6813: =item * &endbodytag()
6814:
6815: Returns a uniform footer for LON-CAPA web pages.
6816:
6817: Inputs: 1 - optional reference to an args hash
6818: If in the hash, key for noredirectlink has a value which evaluates to true,
6819: a 'Continue' link is not displayed if the page contains an
6820: internal redirect in the <head></head> section,
6821: i.e., $env{'internal.head.redirect'} exists
6822:
6823: =cut
6824:
6825: sub endbodytag {
6826: my ($args) = @_;
6827: my $endbodytag;
6828: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6829: $endbodytag='</body>';
6830: }
6831: if ( exists( $env{'internal.head.redirect'} ) ) {
6832: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6833: my ($endbodyjs,$idattr);
6834: if ($env{'internal.head.to_opener'}) {
6835: my $linkid = 'LC_continue_link';
6836: $idattr = ' id="'.$linkid.'"';
6837: my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
6838: $endbodyjs=<<ENDJS;
6839: <script type="text/javascript">
6840: // <![CDATA[
6841: function ebFunction(evt) {
6842: evt.preventDefault();
6843: var dest = '$redirect_for_js';
6844: if (window.opener != null && !window.opener.closed) {
6845: window.opener.location.href=dest;
6846: window.close();
6847: } else {
6848: window.location.href=dest;
6849: }
6850: return false;
6851: }
6852:
6853: \$(document).ready(function () {
6854: if (document.getElementById('$linkid')) {
6855: var clickelem = document.getElementById('$linkid');
6856: clickelem.addEventListener('click',ebFunction,false);
6857: }
6858: });
6859: // ]]>
6860: </script>
6861: ENDJS
6862: }
6863: $endbodytag=
6864: "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
6865: &mt('Continue').'</a>'.
6866: $endbodytag;
6867: }
6868: }
6869: if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
6870: $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
6871: }
6872: return $endbodytag;
6873: }
6874:
6875: =pod
6876:
6877: =item * &standard_css()
6878:
6879: Returns a style sheet
6880:
6881: Inputs: (all optional)
6882: domain -> force to color decorate a page for a specific
6883: domain
6884: function -> force usage of a specific rolish color scheme
6885: bgcolor -> override the default page bgcolor
6886:
6887: =cut
6888:
6889: sub standard_css {
6890: my ($function,$domain,$bgcolor) = @_;
6891: $function = &get_users_function() if (!$function);
6892: my $img = &designparm($function.'.img', $domain);
6893: my $tabbg = &designparm($function.'.tabbg', $domain);
6894: my $font = &designparm($function.'.font', $domain);
6895: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6896: #second colour for later usage
6897: my $sidebg = &designparm($function.'.sidebg',$domain);
6898: my $pgbg_or_bgcolor =
6899: $bgcolor ||
6900: &designparm($function.'.pgbg', $domain);
6901: my $pgbg = &designparm($function.'.pgbg', $domain);
6902: my $alink = &designparm($function.'.alink', $domain);
6903: my $vlink = &designparm($function.'.vlink', $domain);
6904: my $link = &designparm($function.'.link', $domain);
6905:
6906: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6907: my $mono = 'monospace';
6908: my $data_table_head = $sidebg;
6909: my $data_table_light = '#FAFAFA';
6910: my $data_table_dark = '#E0E0E0';
6911: my $data_table_darker = '#CCCCCC';
6912: my $data_table_highlight = '#FFFF00';
6913: my $mail_new = '#FFBB77';
6914: my $mail_new_hover = '#DD9955';
6915: my $mail_read = '#BBBB77';
6916: my $mail_read_hover = '#999944';
6917: my $mail_replied = '#AAAA88';
6918: my $mail_replied_hover = '#888855';
6919: my $mail_other = '#99BBBB';
6920: my $mail_other_hover = '#669999';
6921: my $table_header = '#DDDDDD';
6922: my $feedback_link_bg = '#BBBBBB';
6923: my $lg_border_color = '#C8C8C8';
6924: my $button_hover = '#BF2317';
6925:
6926: my $border = ($env{'browser.type'} eq 'explorer' ||
6927: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6928: : '0 3px 0 4px';
6929:
6930:
6931: return <<END;
6932:
6933: /* needed for iframe to allow 100% height in FF */
6934: body, html {
6935: margin: 0;
6936: padding: 0 0.5%;
6937: height: 99%; /* to avoid scrollbars */
6938: }
6939:
6940: body {
6941: font-family: $sans;
6942: line-height:130%;
6943: font-size:0.83em;
6944: color:$font;
6945: }
6946:
6947: a:focus,
6948: a:focus img {
6949: color: red;
6950: }
6951:
6952: form, .inline {
6953: display: inline;
6954: }
6955:
6956: .LC_right {
6957: text-align:right;
6958: }
6959:
6960: .LC_middle {
6961: vertical-align:middle;
6962: }
6963:
6964: .LC_floatleft {
6965: float: left;
6966: }
6967:
6968: .LC_floatright {
6969: float: right;
6970: }
6971:
6972: .LC_400Box {
6973: width:400px;
6974: }
6975:
6976: .LC_iframecontainer {
6977: width: 98%;
6978: margin: 0;
6979: position: fixed;
6980: top: 8.5em;
6981: bottom: 0;
6982: }
6983:
6984: .LC_iframecontainer iframe{
6985: border: none;
6986: width: 100%;
6987: height: 100%;
6988: }
6989:
6990: .LC_filename {
6991: font-family: $mono;
6992: white-space:pre;
6993: font-size: 120%;
6994: }
6995:
6996: .LC_fileicon {
6997: border: none;
6998: height: 1.3em;
6999: vertical-align: text-bottom;
7000: margin-right: 0.3em;
7001: text-decoration:none;
7002: }
7003:
7004: .LC_setting {
7005: text-decoration:underline;
7006: }
7007:
7008: .LC_error {
7009: color: red;
7010: }
7011:
7012: .LC_warning {
7013: color: darkorange;
7014: }
7015:
7016: .LC_diff_removed {
7017: color: red;
7018: }
7019:
7020: .LC_info,
7021: .LC_success,
7022: .LC_diff_added {
7023: color: green;
7024: }
7025:
7026: div.LC_confirm_box {
7027: background-color: #FAFAFA;
7028: border: 1px solid $lg_border_color;
7029: margin-right: 0;
7030: padding: 5px;
7031: }
7032:
7033: div.LC_confirm_box .LC_error img,
7034: div.LC_confirm_box .LC_success img {
7035: vertical-align: middle;
7036: }
7037:
7038: .LC_maxwidth {
7039: max-width: 100%;
7040: height: auto;
7041: }
7042:
7043: .LC_textsize_mobile {
7044: \@media only screen and (max-device-width: 480px) {
7045: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
7046: }
7047: }
7048:
7049: .LC_icon {
7050: border: none;
7051: vertical-align: middle;
7052: }
7053:
7054: .LC_docs_spacer {
7055: width: 25px;
7056: height: 1px;
7057: border: none;
7058: }
7059:
7060: .LC_internal_info {
7061: color: #999999;
7062: }
7063:
7064: .LC_discussion {
7065: background: $data_table_dark;
7066: border: 1px solid black;
7067: margin: 2px;
7068: }
7069:
7070: .LC_disc_action_left {
7071: background: $sidebg;
7072: text-align: left;
7073: padding: 4px;
7074: margin: 2px;
7075: }
7076:
7077: .LC_disc_action_right {
7078: background: $sidebg;
7079: text-align: right;
7080: padding: 4px;
7081: margin: 2px;
7082: }
7083:
7084: .LC_disc_new_item {
7085: background: white;
7086: border: 2px solid red;
7087: margin: 4px;
7088: padding: 4px;
7089: }
7090:
7091: .LC_disc_old_item {
7092: background: white;
7093: margin: 4px;
7094: padding: 4px;
7095: }
7096:
7097: table.LC_pastsubmission {
7098: border: 1px solid black;
7099: margin: 2px;
7100: }
7101:
7102: table#LC_menubuttons {
7103: width: 100%;
7104: background: $pgbg;
7105: border: 2px;
7106: border-collapse: separate;
7107: padding: 0;
7108: }
7109:
7110: table#LC_title_bar a {
7111: color: $fontmenu;
7112: }
7113:
7114: table#LC_title_bar {
7115: clear: both;
7116: display: none;
7117: }
7118:
7119: table#LC_title_bar,
7120: table.LC_breadcrumbs, /* obsolete? */
7121: table#LC_title_bar.LC_with_remote {
7122: width: 100%;
7123: border-color: $pgbg;
7124: border-style: solid;
7125: border-width: $border;
7126: background: $pgbg;
7127: color: $fontmenu;
7128: border-collapse: collapse;
7129: padding: 0;
7130: margin: 0;
7131: }
7132:
7133: ul.LC_breadcrumb_tools_outerlist {
7134: margin: 0;
7135: padding: 0;
7136: position: relative;
7137: list-style: none;
7138: }
7139: ul.LC_breadcrumb_tools_outerlist li {
7140: display: inline;
7141: }
7142:
7143: .LC_breadcrumb_tools_navigation {
7144: padding: 0;
7145: margin: 0;
7146: float: left;
7147: }
7148: .LC_breadcrumb_tools_tools {
7149: padding: 0;
7150: margin: 0;
7151: float: right;
7152: }
7153:
7154: .LC_placement_prog {
7155: padding-right: 20px;
7156: font-weight: bold;
7157: font-size: 90%;
7158: }
7159:
7160: table#LC_title_bar td {
7161: background: $tabbg;
7162: }
7163:
7164: table#LC_menubuttons img {
7165: border: none;
7166: }
7167:
7168: .LC_breadcrumbs_component {
7169: float: right;
7170: margin: 0 1em;
7171: }
7172: .LC_breadcrumbs_component img {
7173: vertical-align: middle;
7174: }
7175:
7176: .LC_breadcrumbs_hoverable {
7177: background: $sidebg;
7178: }
7179:
7180: td.LC_table_cell_checkbox {
7181: text-align: center;
7182: }
7183:
7184: .LC_fontsize_small {
7185: font-size: 70%;
7186: }
7187:
7188: #LC_breadcrumbs {
7189: clear:both;
7190: background: $sidebg;
7191: border-bottom: 1px solid $lg_border_color;
7192: line-height: 2.5em;
7193: overflow: hidden;
7194: margin: 0;
7195: padding: 0;
7196: text-align: left;
7197: }
7198:
7199: .LC_head_subbox, .LC_actionbox {
7200: clear:both;
7201: background: #F8F8F8; /* $sidebg; */
7202: border: 1px solid $sidebg;
7203: margin: 0 0 10px 0;
7204: padding: 3px;
7205: text-align: left;
7206: }
7207:
7208: .LC_fontsize_medium {
7209: font-size: 85%;
7210: }
7211:
7212: .LC_fontsize_large {
7213: font-size: 120%;
7214: }
7215:
7216: .LC_menubuttons_inline_text {
7217: color: $font;
7218: font-size: 90%;
7219: padding-left:3px;
7220: }
7221:
7222: .LC_menubuttons_inline_text img{
7223: vertical-align: middle;
7224: }
7225:
7226: li.LC_menubuttons_inline_text img {
7227: cursor:pointer;
7228: text-decoration: none;
7229: }
7230:
7231: .LC_menubuttons_link {
7232: text-decoration: none;
7233: }
7234:
7235: .LC_menubuttons_category {
7236: color: $font;
7237: background: $pgbg;
7238: font-size: larger;
7239: font-weight: bold;
7240: }
7241:
7242: td.LC_menubuttons_text {
7243: color: $font;
7244: }
7245:
7246: .LC_current_location {
7247: background: $tabbg;
7248: }
7249:
7250: td.LC_zero_height {
7251: line-height: 0;
7252: cellpadding: 0;
7253: }
7254:
7255: table.LC_data_table {
7256: border: 1px solid #000000;
7257: border-collapse: separate;
7258: border-spacing: 1px;
7259: background: $pgbg;
7260: }
7261:
7262: .LC_data_table_dense {
7263: font-size: small;
7264: }
7265:
7266: table.LC_nested_outer {
7267: border: 1px solid #000000;
7268: border-collapse: collapse;
7269: border-spacing: 0;
7270: width: 100%;
7271: }
7272:
7273: table.LC_innerpickbox,
7274: table.LC_nested {
7275: border: none;
7276: border-collapse: collapse;
7277: border-spacing: 0;
7278: width: 100%;
7279: }
7280:
7281: table.LC_data_table tr th,
7282: table.LC_calendar tr th,
7283: table.LC_prior_tries tr th,
7284: table.LC_innerpickbox tr th {
7285: font-weight: bold;
7286: background-color: $data_table_head;
7287: color:$fontmenu;
7288: font-size:90%;
7289: }
7290:
7291: table.LC_innerpickbox tr th,
7292: table.LC_innerpickbox tr td {
7293: vertical-align: top;
7294: }
7295:
7296: table.LC_data_table tr.LC_info_row > td {
7297: background-color: #CCCCCC;
7298: font-weight: bold;
7299: text-align: left;
7300: }
7301:
7302: table.LC_data_table tr.LC_odd_row > td {
7303: background-color: $data_table_light;
7304: padding: 2px;
7305: vertical-align: top;
7306: }
7307:
7308: table.LC_pick_box tr > td.LC_odd_row {
7309: background-color: $data_table_light;
7310: vertical-align: top;
7311: }
7312:
7313: table.LC_data_table tr.LC_even_row > td {
7314: background-color: $data_table_dark;
7315: padding: 2px;
7316: vertical-align: top;
7317: }
7318:
7319: table.LC_pick_box tr > td.LC_even_row {
7320: background-color: $data_table_dark;
7321: vertical-align: top;
7322: }
7323:
7324: table.LC_data_table tr.LC_data_table_highlight td {
7325: background-color: $data_table_darker;
7326: }
7327:
7328: table.LC_data_table tr td.LC_leftcol_header {
7329: background-color: $data_table_head;
7330: font-weight: bold;
7331: }
7332:
7333: table.LC_data_table tr.LC_empty_row td,
7334: table.LC_nested tr.LC_empty_row td {
7335: font-weight: bold;
7336: font-style: italic;
7337: text-align: center;
7338: padding: 8px;
7339: }
7340:
7341: table.LC_data_table tr.LC_empty_row td,
7342: table.LC_data_table tr.LC_footer_row td {
7343: background-color: $sidebg;
7344: }
7345:
7346: table.LC_nested tr.LC_empty_row td {
7347: background-color: #FFFFFF;
7348: }
7349:
7350: table.LC_caption {
7351: }
7352:
7353: table.LC_nested tr.LC_empty_row td {
7354: padding: 4ex
7355: }
7356:
7357: table.LC_nested_outer tr th {
7358: font-weight: bold;
7359: color:$fontmenu;
7360: background-color: $data_table_head;
7361: font-size: small;
7362: border-bottom: 1px solid #000000;
7363: }
7364:
7365: table.LC_nested_outer tr td.LC_subheader {
7366: background-color: $data_table_head;
7367: font-weight: bold;
7368: font-size: small;
7369: border-bottom: 1px solid #000000;
7370: text-align: right;
7371: }
7372:
7373: table.LC_nested tr.LC_info_row td {
7374: background-color: #CCCCCC;
7375: font-weight: bold;
7376: font-size: small;
7377: text-align: center;
7378: }
7379:
7380: table.LC_nested tr.LC_info_row td.LC_left_item,
7381: table.LC_nested_outer tr th.LC_left_item {
7382: text-align: left;
7383: }
7384:
7385: table.LC_nested td {
7386: background-color: #FFFFFF;
7387: font-size: small;
7388: }
7389:
7390: table.LC_nested_outer tr th.LC_right_item,
7391: table.LC_nested tr.LC_info_row td.LC_right_item,
7392: table.LC_nested tr.LC_odd_row td.LC_right_item,
7393: table.LC_nested tr td.LC_right_item {
7394: text-align: right;
7395: }
7396:
7397: table.LC_nested tr.LC_odd_row td {
7398: background-color: #EEEEEE;
7399: }
7400:
7401: table.LC_createuser {
7402: }
7403:
7404: table.LC_createuser tr.LC_section_row td {
7405: font-size: small;
7406: }
7407:
7408: table.LC_createuser tr.LC_info_row td {
7409: background-color: #CCCCCC;
7410: font-weight: bold;
7411: text-align: center;
7412: }
7413:
7414: table.LC_calendar {
7415: border: 1px solid #000000;
7416: border-collapse: collapse;
7417: width: 98%;
7418: }
7419:
7420: table.LC_calendar_pickdate {
7421: font-size: xx-small;
7422: }
7423:
7424: table.LC_calendar tr td {
7425: border: 1px solid #000000;
7426: vertical-align: top;
7427: width: 14%;
7428: }
7429:
7430: table.LC_calendar tr td.LC_calendar_day_empty {
7431: background-color: $data_table_dark;
7432: }
7433:
7434: table.LC_calendar tr td.LC_calendar_day_current {
7435: background-color: $data_table_highlight;
7436: }
7437:
7438: table.LC_data_table tr td.LC_mail_new {
7439: background-color: $mail_new;
7440: }
7441:
7442: table.LC_data_table tr.LC_mail_new:hover {
7443: background-color: $mail_new_hover;
7444: }
7445:
7446: table.LC_data_table tr td.LC_mail_read {
7447: background-color: $mail_read;
7448: }
7449:
7450: /*
7451: table.LC_data_table tr.LC_mail_read:hover {
7452: background-color: $mail_read_hover;
7453: }
7454: */
7455:
7456: table.LC_data_table tr td.LC_mail_replied {
7457: background-color: $mail_replied;
7458: }
7459:
7460: /*
7461: table.LC_data_table tr.LC_mail_replied:hover {
7462: background-color: $mail_replied_hover;
7463: }
7464: */
7465:
7466: table.LC_data_table tr td.LC_mail_other {
7467: background-color: $mail_other;
7468: }
7469:
7470: /*
7471: table.LC_data_table tr.LC_mail_other:hover {
7472: background-color: $mail_other_hover;
7473: }
7474: */
7475:
7476: table.LC_data_table tr > td.LC_browser_file,
7477: table.LC_data_table tr > td.LC_browser_file_published {
7478: background: #AAEE77;
7479: }
7480:
7481: table.LC_data_table tr > td.LC_browser_file_locked,
7482: table.LC_data_table tr > td.LC_browser_file_unpublished {
7483: background: #FFAA99;
7484: }
7485:
7486: table.LC_data_table tr > td.LC_browser_file_obsolete {
7487: background: #888888;
7488: }
7489:
7490: table.LC_data_table tr > td.LC_browser_file_modified,
7491: table.LC_data_table tr > td.LC_browser_file_metamodified {
7492: background: #F8F866;
7493: }
7494:
7495: table.LC_data_table tr.LC_browser_folder > td {
7496: background: #E0E8FF;
7497: }
7498:
7499: table.LC_data_table tr > td.LC_roles_is {
7500: /* background: #77FF77; */
7501: }
7502:
7503: table.LC_data_table tr > td.LC_roles_future {
7504: border-right: 8px solid #FFFF77;
7505: }
7506:
7507: table.LC_data_table tr > td.LC_roles_will {
7508: border-right: 8px solid #FFAA77;
7509: }
7510:
7511: table.LC_data_table tr > td.LC_roles_expired {
7512: border-right: 8px solid #FF7777;
7513: }
7514:
7515: table.LC_data_table tr > td.LC_roles_will_not {
7516: border-right: 8px solid #AAFF77;
7517: }
7518:
7519: table.LC_data_table tr > td.LC_roles_selected {
7520: border-right: 8px solid #11CC55;
7521: }
7522:
7523: span.LC_current_location {
7524: font-size:larger;
7525: background: $pgbg;
7526: }
7527:
7528: span.LC_current_nav_location {
7529: font-weight:bold;
7530: background: $sidebg;
7531: }
7532:
7533: span.LC_parm_menu_item {
7534: font-size: larger;
7535: }
7536:
7537: span.LC_parm_scope_all {
7538: color: red;
7539: }
7540:
7541: span.LC_parm_scope_folder {
7542: color: green;
7543: }
7544:
7545: span.LC_parm_scope_resource {
7546: color: orange;
7547: }
7548:
7549: span.LC_parm_part {
7550: color: blue;
7551: }
7552:
7553: span.LC_parm_folder,
7554: span.LC_parm_symb {
7555: font-size: x-small;
7556: font-family: $mono;
7557: color: #AAAAAA;
7558: }
7559:
7560: ul.LC_parm_parmlist li {
7561: display: inline-block;
7562: padding: 0.3em 0.8em;
7563: vertical-align: top;
7564: width: 150px;
7565: border-top:1px solid $lg_border_color;
7566: }
7567:
7568: td.LC_parm_overview_level_menu,
7569: td.LC_parm_overview_map_menu,
7570: td.LC_parm_overview_parm_selectors,
7571: td.LC_parm_overview_restrictions {
7572: border: 1px solid black;
7573: border-collapse: collapse;
7574: }
7575:
7576: span.LC_parm_recursive,
7577: td.LC_parm_recursive {
7578: font-weight: bold;
7579: font-size: smaller;
7580: }
7581:
7582: table.LC_parm_overview_restrictions td {
7583: border-width: 1px 4px 1px 4px;
7584: border-style: solid;
7585: border-color: $pgbg;
7586: text-align: center;
7587: }
7588:
7589: table.LC_parm_overview_restrictions th {
7590: background: $tabbg;
7591: border-width: 1px 4px 1px 4px;
7592: border-style: solid;
7593: border-color: $pgbg;
7594: }
7595:
7596: table#LC_helpmenu {
7597: border: none;
7598: height: 55px;
7599: border-spacing: 0;
7600: }
7601:
7602: table#LC_helpmenu fieldset legend {
7603: font-size: larger;
7604: }
7605:
7606: table#LC_helpmenu_links {
7607: width: 100%;
7608: border: 1px solid black;
7609: background: $pgbg;
7610: padding: 0;
7611: border-spacing: 1px;
7612: }
7613:
7614: table#LC_helpmenu_links tr td {
7615: padding: 1px;
7616: background: $tabbg;
7617: text-align: center;
7618: font-weight: bold;
7619: }
7620:
7621: table#LC_helpmenu_links a:link,
7622: table#LC_helpmenu_links a:visited,
7623: table#LC_helpmenu_links a:active {
7624: text-decoration: none;
7625: color: $font;
7626: }
7627:
7628: table#LC_helpmenu_links a:hover {
7629: text-decoration: underline;
7630: color: $vlink;
7631: }
7632:
7633: .LC_chrt_popup_exists {
7634: border: 1px solid #339933;
7635: margin: -1px;
7636: }
7637:
7638: .LC_chrt_popup_up {
7639: border: 1px solid yellow;
7640: margin: -1px;
7641: }
7642:
7643: .LC_chrt_popup {
7644: border: 1px solid #8888FF;
7645: background: #CCCCFF;
7646: }
7647:
7648: table.LC_pick_box {
7649: border-collapse: separate;
7650: background: white;
7651: border: 1px solid black;
7652: border-spacing: 1px;
7653: }
7654:
7655: table.LC_pick_box td.LC_pick_box_title {
7656: background: $sidebg;
7657: font-weight: bold;
7658: text-align: left;
7659: vertical-align: top;
7660: width: 184px;
7661: padding: 8px;
7662: }
7663:
7664: table.LC_pick_box td.LC_pick_box_value {
7665: text-align: left;
7666: padding: 8px;
7667: }
7668:
7669: table.LC_pick_box td.LC_pick_box_select {
7670: text-align: left;
7671: padding: 8px;
7672: }
7673:
7674: table.LC_pick_box td.LC_pick_box_separator {
7675: padding: 0;
7676: height: 1px;
7677: background: black;
7678: }
7679:
7680: table.LC_pick_box td.LC_pick_box_submit {
7681: text-align: right;
7682: }
7683:
7684: table.LC_pick_box td.LC_evenrow_value {
7685: text-align: left;
7686: padding: 8px;
7687: background-color: $data_table_light;
7688: }
7689:
7690: table.LC_pick_box td.LC_oddrow_value {
7691: text-align: left;
7692: padding: 8px;
7693: background-color: $data_table_light;
7694: }
7695:
7696: span.LC_helpform_receipt_cat {
7697: font-weight: bold;
7698: }
7699:
7700: table.LC_group_priv_box {
7701: background: white;
7702: border: 1px solid black;
7703: border-spacing: 1px;
7704: }
7705:
7706: table.LC_group_priv_box td.LC_pick_box_title {
7707: background: $tabbg;
7708: font-weight: bold;
7709: text-align: right;
7710: width: 184px;
7711: }
7712:
7713: table.LC_group_priv_box td.LC_groups_fixed {
7714: background: $data_table_light;
7715: text-align: center;
7716: }
7717:
7718: table.LC_group_priv_box td.LC_groups_optional {
7719: background: $data_table_dark;
7720: text-align: center;
7721: }
7722:
7723: table.LC_group_priv_box td.LC_groups_functionality {
7724: background: $data_table_darker;
7725: text-align: center;
7726: font-weight: bold;
7727: }
7728:
7729: table.LC_group_priv td {
7730: text-align: left;
7731: padding: 0;
7732: }
7733:
7734: .LC_navbuttons {
7735: margin: 2ex 0ex 2ex 0ex;
7736: }
7737:
7738: .LC_topic_bar {
7739: font-weight: bold;
7740: background: $tabbg;
7741: margin: 1em 0em 1em 2em;
7742: padding: 3px;
7743: font-size: 1.2em;
7744: }
7745:
7746: .LC_topic_bar span {
7747: left: 0.5em;
7748: position: absolute;
7749: vertical-align: middle;
7750: font-size: 1.2em;
7751: }
7752:
7753: table.LC_course_group_status {
7754: margin: 20px;
7755: }
7756:
7757: table.LC_status_selector td {
7758: vertical-align: top;
7759: text-align: center;
7760: padding: 4px;
7761: }
7762:
7763: div.LC_feedback_link {
7764: clear: both;
7765: background: $sidebg;
7766: width: 100%;
7767: padding-bottom: 10px;
7768: border: 1px $tabbg solid;
7769: height: 22px;
7770: line-height: 22px;
7771: padding-top: 5px;
7772: }
7773:
7774: div.LC_feedback_link img {
7775: height: 22px;
7776: vertical-align:middle;
7777: }
7778:
7779: div.LC_feedback_link a {
7780: text-decoration: none;
7781: }
7782:
7783: div.LC_comblock {
7784: display:inline;
7785: color:$font;
7786: font-size:90%;
7787: }
7788:
7789: div.LC_feedback_link div.LC_comblock {
7790: padding-left:5px;
7791: }
7792:
7793: div.LC_feedback_link div.LC_comblock a {
7794: color:$font;
7795: }
7796:
7797: span.LC_feedback_link {
7798: /* background: $feedback_link_bg; */
7799: font-size: larger;
7800: }
7801:
7802: span.LC_message_link {
7803: /* background: $feedback_link_bg; */
7804: font-size: larger;
7805: position: absolute;
7806: right: 1em;
7807: }
7808:
7809: table.LC_prior_tries {
7810: border: 1px solid #000000;
7811: border-collapse: separate;
7812: border-spacing: 1px;
7813: }
7814:
7815: table.LC_prior_tries td {
7816: padding: 2px;
7817: }
7818:
7819: .LC_answer_correct {
7820: background: lightgreen;
7821: color: darkgreen;
7822: padding: 6px;
7823: }
7824:
7825: .LC_answer_charged_try {
7826: background: #FFAAAA;
7827: color: darkred;
7828: padding: 6px;
7829: }
7830:
7831: .LC_answer_not_charged_try,
7832: .LC_answer_no_grade,
7833: .LC_answer_late {
7834: background: lightyellow;
7835: color: black;
7836: padding: 6px;
7837: }
7838:
7839: .LC_answer_previous {
7840: background: lightblue;
7841: color: darkblue;
7842: padding: 6px;
7843: }
7844:
7845: .LC_answer_no_message {
7846: background: #FFFFFF;
7847: color: black;
7848: padding: 6px;
7849: }
7850:
7851: .LC_answer_unknown,
7852: .LC_answer_warning {
7853: background: orange;
7854: color: black;
7855: padding: 6px;
7856: }
7857:
7858: span.LC_prior_numerical,
7859: span.LC_prior_string,
7860: span.LC_prior_custom,
7861: span.LC_prior_reaction,
7862: span.LC_prior_math {
7863: font-family: $mono;
7864: white-space: pre;
7865: }
7866:
7867: span.LC_prior_string {
7868: font-family: $mono;
7869: white-space: pre;
7870: }
7871:
7872: table.LC_prior_option {
7873: width: 100%;
7874: border-collapse: collapse;
7875: }
7876:
7877: table.LC_prior_rank,
7878: table.LC_prior_match {
7879: border-collapse: collapse;
7880: }
7881:
7882: table.LC_prior_option tr td,
7883: table.LC_prior_rank tr td,
7884: table.LC_prior_match tr td {
7885: border: 1px solid #000000;
7886: }
7887:
7888: .LC_nobreak {
7889: white-space: nowrap;
7890: }
7891:
7892: span.LC_cusr_emph {
7893: font-style: italic;
7894: }
7895:
7896: span.LC_cusr_subheading {
7897: font-weight: normal;
7898: font-size: 85%;
7899: }
7900:
7901: div.LC_docs_entry_move {
7902: border: 1px solid #BBBBBB;
7903: background: #DDDDDD;
7904: width: 22px;
7905: padding: 1px;
7906: margin: 0;
7907: }
7908:
7909: table.LC_data_table tr > td.LC_docs_entry_commands,
7910: table.LC_data_table tr > td.LC_docs_entry_parameter {
7911: font-size: x-small;
7912: }
7913:
7914: .LC_docs_entry_parameter {
7915: white-space: nowrap;
7916: }
7917:
7918: .LC_docs_copy {
7919: color: #000099;
7920: }
7921:
7922: .LC_docs_cut {
7923: color: #550044;
7924: }
7925:
7926: .LC_docs_rename {
7927: color: #009900;
7928: }
7929:
7930: .LC_docs_remove {
7931: color: #990000;
7932: }
7933:
7934: .LC_docs_alias {
7935: color: #440055;
7936: }
7937:
7938: .LC_domprefs_email,
7939: .LC_docs_alias_name,
7940: .LC_docs_reinit_warn,
7941: .LC_docs_ext_edit {
7942: font-size: x-small;
7943: }
7944:
7945: table.LC_docs_adddocs td,
7946: table.LC_docs_adddocs th {
7947: border: 1px solid #BBBBBB;
7948: padding: 4px;
7949: background: #DDDDDD;
7950: }
7951:
7952: table.LC_sty_begin {
7953: background: #BBFFBB;
7954: }
7955:
7956: table.LC_sty_end {
7957: background: #FFBBBB;
7958: }
7959:
7960: table.LC_double_column {
7961: border-width: 0;
7962: border-collapse: collapse;
7963: width: 100%;
7964: padding: 2px;
7965: }
7966:
7967: table.LC_double_column tr td.LC_left_col {
7968: top: 2px;
7969: left: 2px;
7970: width: 47%;
7971: vertical-align: top;
7972: }
7973:
7974: table.LC_double_column tr td.LC_right_col {
7975: top: 2px;
7976: right: 2px;
7977: width: 47%;
7978: vertical-align: top;
7979: }
7980:
7981: div.LC_left_float {
7982: float: left;
7983: padding-right: 5%;
7984: padding-bottom: 4px;
7985: }
7986:
7987: div.LC_clear_float_header {
7988: padding-bottom: 2px;
7989: }
7990:
7991: div.LC_clear_float_footer {
7992: padding-top: 10px;
7993: clear: both;
7994: }
7995:
7996: div.LC_grade_show_user {
7997: /* border-left: 5px solid $sidebg; */
7998: border-top: 5px solid #000000;
7999: margin: 50px 0 0 0;
8000: padding: 15px 0 5px 10px;
8001: }
8002:
8003: div.LC_grade_show_user_odd_row {
8004: /* border-left: 5px solid #000000; */
8005: }
8006:
8007: div.LC_grade_show_user div.LC_Box {
8008: margin-right: 50px;
8009: }
8010:
8011: div.LC_grade_submissions,
8012: div.LC_grade_message_center,
8013: div.LC_grade_info_links {
8014: margin: 5px;
8015: width: 99%;
8016: background: #FFFFFF;
8017: }
8018:
8019: div.LC_grade_submissions_header,
8020: div.LC_grade_message_center_header {
8021: font-weight: bold;
8022: font-size: large;
8023: }
8024:
8025: div.LC_grade_submissions_body,
8026: div.LC_grade_message_center_body {
8027: border: 1px solid black;
8028: width: 99%;
8029: background: #FFFFFF;
8030: }
8031:
8032: table.LC_scantron_action {
8033: width: 100%;
8034: }
8035:
8036: table.LC_scantron_action tr th {
8037: font-weight:bold;
8038: font-style:normal;
8039: }
8040:
8041: .LC_edit_problem_header,
8042: div.LC_edit_problem_footer {
8043: font-weight: normal;
8044: font-size: medium;
8045: margin: 2px;
8046: background-color: $sidebg;
8047: }
8048:
8049: div.LC_edit_problem_header,
8050: div.LC_edit_problem_header div,
8051: div.LC_edit_problem_footer,
8052: div.LC_edit_problem_footer div,
8053: div.LC_edit_problem_editxml_header,
8054: div.LC_edit_problem_editxml_header div {
8055: z-index: 100;
8056: }
8057:
8058: div.LC_edit_problem_header_title {
8059: font-weight: bold;
8060: font-size: larger;
8061: background: $tabbg;
8062: padding: 3px;
8063: margin: 0 0 5px 0;
8064: }
8065:
8066: table.LC_edit_problem_header_title {
8067: width: 100%;
8068: background: $tabbg;
8069: }
8070:
8071: div.LC_edit_actionbar {
8072: background-color: $sidebg;
8073: margin: 0;
8074: padding: 0;
8075: line-height: 200%;
8076: }
8077:
8078: div.LC_edit_actionbar div{
8079: padding: 0;
8080: margin: 0;
8081: display: inline-block;
8082: }
8083:
8084: .LC_edit_opt {
8085: padding-left: 1em;
8086: white-space: nowrap;
8087: }
8088:
8089: .LC_edit_problem_latexhelper{
8090: text-align: right;
8091: }
8092:
8093: #LC_edit_problem_colorful div{
8094: margin-left: 40px;
8095: }
8096:
8097: #LC_edit_problem_codemirror div{
8098: margin-left: 0px;
8099: }
8100:
8101: img.stift {
8102: border-width: 0;
8103: vertical-align: middle;
8104: }
8105:
8106: table td.LC_mainmenu_col_fieldset {
8107: vertical-align: top;
8108: }
8109:
8110: div.LC_createcourse {
8111: margin: 10px 10px 10px 10px;
8112: }
8113:
8114: .LC_dccid {
8115: float: right;
8116: margin: 0.2em 0 0 0;
8117: padding: 0;
8118: font-size: 90%;
8119: display:none;
8120: }
8121:
8122: ol.LC_primary_menu a:hover,
8123: ol#LC_MenuBreadcrumbs a:hover,
8124: ol#LC_PathBreadcrumbs a:hover,
8125: ul#LC_secondary_menu a:hover,
8126: .LC_FormSectionClearButton input:hover
8127: ul.LC_TabContent li:hover a {
8128: color:$button_hover;
8129: text-decoration:none;
8130: }
8131:
8132: h1 {
8133: padding: 0;
8134: line-height:130%;
8135: }
8136:
8137: h2,
8138: h3,
8139: h4,
8140: h5,
8141: h6 {
8142: margin: 5px 0 5px 0;
8143: padding: 0;
8144: line-height:130%;
8145: }
8146:
8147: .LC_hcell {
8148: padding:3px 15px 3px 15px;
8149: margin: 0;
8150: background-color:$tabbg;
8151: color:$fontmenu;
8152: border-bottom:solid 1px $lg_border_color;
8153: }
8154:
8155: .LC_Box > .LC_hcell {
8156: margin: 0 -10px 10px -10px;
8157: }
8158:
8159: .LC_noBorder {
8160: border: 0;
8161: }
8162:
8163: .LC_FormSectionClearButton input {
8164: background-color:transparent;
8165: border: none;
8166: cursor:pointer;
8167: text-decoration:underline;
8168: }
8169:
8170: .LC_help_open_topic {
8171: color: #FFFFFF;
8172: background-color: #EEEEFF;
8173: margin: 1px;
8174: padding: 4px;
8175: border: 1px solid #000033;
8176: white-space: nowrap;
8177: /* vertical-align: middle; */
8178: }
8179:
8180: dl,
8181: ul,
8182: div,
8183: fieldset {
8184: margin: 10px 10px 10px 0;
8185: /* overflow: hidden; */
8186: }
8187:
8188: fieldset#LC_selectuser {
8189: margin: 0;
8190: padding: 0;
8191: }
8192:
8193: article.geogebraweb div {
8194: margin: 0;
8195: }
8196:
8197: fieldset > legend {
8198: font-weight: bold;
8199: padding: 0 5px 0 5px;
8200: }
8201:
8202: #LC_nav_bar {
8203: float: left;
8204: background-color: $pgbg_or_bgcolor;
8205: margin: 0 0 2px 0;
8206: }
8207:
8208: #LC_realm {
8209: margin: 0.2em 0 0 0;
8210: padding: 0;
8211: font-weight: bold;
8212: text-align: center;
8213: background-color: $pgbg_or_bgcolor;
8214: }
8215:
8216: #LC_nav_bar em {
8217: font-weight: bold;
8218: font-style: normal;
8219: }
8220:
8221: ol.LC_primary_menu {
8222: margin: 0;
8223: padding: 0;
8224: }
8225:
8226: ol#LC_PathBreadcrumbs {
8227: margin: 0;
8228: }
8229:
8230: ol.LC_primary_menu li {
8231: color: RGB(80, 80, 80);
8232: vertical-align: middle;
8233: text-align: left;
8234: list-style: none;
8235: position: relative;
8236: float: left;
8237: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
8238: line-height: 1.5em;
8239: }
8240:
8241: ol.LC_primary_menu li a,
8242: ol.LC_primary_menu li p {
8243: display: block;
8244: margin: 0;
8245: padding: 0 5px 0 10px;
8246: text-decoration: none;
8247: }
8248:
8249: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
8250: display: inline-block;
8251: width: 95%;
8252: text-align: left;
8253: }
8254:
8255: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
8256: display: inline-block;
8257: width: 5%;
8258: float: right;
8259: text-align: right;
8260: font-size: 70%;
8261: }
8262:
8263: ol.LC_primary_menu ul {
8264: display: none;
8265: width: 15em;
8266: background-color: $data_table_light;
8267: position: absolute;
8268: top: 100%;
8269: }
8270:
8271: ol.LC_primary_menu ul ul {
8272: left: 100%;
8273: top: 0;
8274: }
8275:
8276: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
8277: display: block;
8278: position: absolute;
8279: margin: 0;
8280: padding: 0;
8281: z-index: 2;
8282: }
8283:
8284: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
8285: /* First Submenu -> size should be smaller than the menu title of the whole menu */
8286: font-size: 90%;
8287: vertical-align: top;
8288: float: none;
8289: border-left: 1px solid black;
8290: border-right: 1px solid black;
8291: /* A dark bottom border to visualize different menu options;
8292: overwritten in the create_submenu routine for the last border-bottom of the menu */
8293: border-bottom: 1px solid $data_table_dark;
8294: }
8295:
8296: ol.LC_primary_menu li li p:hover {
8297: color:$button_hover;
8298: text-decoration:none;
8299: background-color:$data_table_dark;
8300: }
8301:
8302: ol.LC_primary_menu li li a:hover {
8303: color:$button_hover;
8304: background-color:$data_table_dark;
8305: }
8306:
8307: /* Font-size equal to the size of the predecessors*/
8308: ol.LC_primary_menu li:hover li li {
8309: font-size: 100%;
8310: }
8311:
8312: ol.LC_primary_menu li img {
8313: vertical-align: bottom;
8314: height: 1.1em;
8315: margin: 0.2em 0 0 0;
8316: }
8317:
8318: ol.LC_primary_menu a {
8319: color: RGB(80, 80, 80);
8320: text-decoration: none;
8321: }
8322:
8323: ol.LC_primary_menu a.LC_new_message {
8324: font-weight:bold;
8325: color: darkred;
8326: }
8327:
8328: ol.LC_docs_parameters {
8329: margin-left: 0;
8330: padding: 0;
8331: list-style: none;
8332: }
8333:
8334: ol.LC_docs_parameters li {
8335: margin: 0;
8336: padding-right: 20px;
8337: display: inline;
8338: }
8339:
8340: ol.LC_docs_parameters li:before {
8341: content: "\\002022 \\0020";
8342: }
8343:
8344: li.LC_docs_parameters_title {
8345: font-weight: bold;
8346: }
8347:
8348: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
8349: content: "";
8350: }
8351:
8352: ul#LC_secondary_menu {
8353: clear: right;
8354: color: $fontmenu;
8355: background: $tabbg;
8356: list-style: none;
8357: padding: 0;
8358: margin: 0;
8359: width: 100%;
8360: text-align: left;
8361: float: left;
8362: }
8363:
8364: ul#LC_secondary_menu li {
8365: font-weight: bold;
8366: line-height: 1.8em;
8367: border-right: 1px solid black;
8368: float: left;
8369: }
8370:
8371: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
8372: background-color: $data_table_light;
8373: }
8374:
8375: ul#LC_secondary_menu li a {
8376: padding: 0 0.8em;
8377: }
8378:
8379: ul#LC_secondary_menu li ul {
8380: display: none;
8381: }
8382:
8383: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
8384: display: block;
8385: position: absolute;
8386: margin: 0;
8387: padding: 0;
8388: list-style:none;
8389: float: none;
8390: background-color: $data_table_light;
8391: z-index: 2;
8392: margin-left: -1px;
8393: }
8394:
8395: ul#LC_secondary_menu li ul li {
8396: font-size: 90%;
8397: vertical-align: top;
8398: border-left: 1px solid black;
8399: border-right: 1px solid black;
8400: background-color: $data_table_light;
8401: list-style:none;
8402: float: none;
8403: }
8404:
8405: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
8406: background-color: $data_table_dark;
8407: }
8408:
8409: ul.LC_TabContent {
8410: display:block;
8411: background: $sidebg;
8412: border-bottom: solid 1px $lg_border_color;
8413: list-style:none;
8414: margin: -1px -10px 0 -10px;
8415: padding: 0;
8416: }
8417:
8418: ul.LC_TabContent li,
8419: ul.LC_TabContentBigger li {
8420: float:left;
8421: }
8422:
8423: ul#LC_secondary_menu li a {
8424: color: $fontmenu;
8425: text-decoration: none;
8426: }
8427:
8428: ul.LC_TabContent {
8429: min-height:20px;
8430: }
8431:
8432: ul.LC_TabContent li {
8433: vertical-align:middle;
8434: padding: 0 16px 0 10px;
8435: background-color:$tabbg;
8436: border-bottom:solid 1px $lg_border_color;
8437: border-left: solid 1px $font;
8438: }
8439:
8440: ul.LC_TabContent .right {
8441: float:right;
8442: }
8443:
8444: ul.LC_TabContent li a,
8445: ul.LC_TabContent li {
8446: color:rgb(47,47,47);
8447: text-decoration:none;
8448: font-size:95%;
8449: font-weight:bold;
8450: min-height:20px;
8451: }
8452:
8453: ul.LC_TabContent li a:hover,
8454: ul.LC_TabContent li a:focus {
8455: color: $button_hover;
8456: background:none;
8457: outline:none;
8458: }
8459:
8460: ul.LC_TabContent li:hover {
8461: color: $button_hover;
8462: cursor:pointer;
8463: }
8464:
8465: ul.LC_TabContent li.active {
8466: color: $font;
8467: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
8468: border-bottom:solid 1px #FFFFFF;
8469: cursor: default;
8470: }
8471:
8472: ul.LC_TabContent li.active a {
8473: color:$font;
8474: background:#FFFFFF;
8475: outline: none;
8476: }
8477:
8478: ul.LC_TabContent li.goback {
8479: float: left;
8480: border-left: none;
8481: }
8482:
8483: #maincoursedoc {
8484: clear:both;
8485: }
8486:
8487: ul.LC_TabContentBigger {
8488: display:block;
8489: list-style:none;
8490: padding: 0;
8491: }
8492:
8493: ul.LC_TabContentBigger li {
8494: vertical-align:bottom;
8495: height: 30px;
8496: font-size:110%;
8497: font-weight:bold;
8498: color: #737373;
8499: }
8500:
8501: ul.LC_TabContentBigger li.active {
8502: position: relative;
8503: top: 1px;
8504: }
8505:
8506: ul.LC_TabContentBigger li a {
8507: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
8508: height: 30px;
8509: line-height: 30px;
8510: text-align: center;
8511: display: block;
8512: text-decoration: none;
8513: outline: none;
8514: }
8515:
8516: ul.LC_TabContentBigger li.active a {
8517: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
8518: color:$font;
8519: }
8520:
8521: ul.LC_TabContentBigger li b {
8522: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
8523: display: block;
8524: float: left;
8525: padding: 0 30px;
8526: border-bottom: 1px solid $lg_border_color;
8527: }
8528:
8529: ul.LC_TabContentBigger li:hover b {
8530: color:$button_hover;
8531: }
8532:
8533: ul.LC_TabContentBigger li.active b {
8534: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
8535: color:$font;
8536: border: 0;
8537: }
8538:
8539:
8540: ul.LC_CourseBreadcrumbs {
8541: background: $sidebg;
8542: height: 2em;
8543: padding-left: 10px;
8544: margin: 0;
8545: list-style-position: inside;
8546: }
8547:
8548: ol#LC_MenuBreadcrumbs,
8549: ol#LC_PathBreadcrumbs {
8550: padding-left: 10px;
8551: margin: 0;
8552: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
8553: }
8554:
8555: ol#LC_MenuBreadcrumbs li,
8556: ol#LC_PathBreadcrumbs li,
8557: ul.LC_CourseBreadcrumbs li {
8558: display: inline;
8559: white-space: normal;
8560: }
8561:
8562: ol#LC_MenuBreadcrumbs li a,
8563: ul.LC_CourseBreadcrumbs li a {
8564: text-decoration: none;
8565: font-size:90%;
8566: }
8567:
8568: ol#LC_MenuBreadcrumbs h1 {
8569: display: inline;
8570: font-size: 90%;
8571: line-height: 2.5em;
8572: margin: 0;
8573: padding: 0;
8574: }
8575:
8576: ol#LC_PathBreadcrumbs li a {
8577: text-decoration:none;
8578: font-size:100%;
8579: font-weight:bold;
8580: }
8581:
8582: .LC_Box {
8583: border: solid 1px $lg_border_color;
8584: padding: 0 10px 10px 10px;
8585: }
8586:
8587: .LC_DocsBox {
8588: border: solid 1px $lg_border_color;
8589: padding: 0 0 10px 10px;
8590: }
8591:
8592: .LC_AboutMe_Image {
8593: float:left;
8594: margin-right:10px;
8595: }
8596:
8597: .LC_Clear_AboutMe_Image {
8598: clear:left;
8599: }
8600:
8601: dl.LC_ListStyleClean dt {
8602: padding-right: 5px;
8603: display: table-header-group;
8604: }
8605:
8606: dl.LC_ListStyleClean dd {
8607: display: table-row;
8608: }
8609:
8610: .LC_ListStyleClean,
8611: .LC_ListStyleSimple,
8612: .LC_ListStyleNormal,
8613: .LC_ListStyleSpecial {
8614: /* display:block; */
8615: list-style-position: inside;
8616: list-style-type: none;
8617: overflow: hidden;
8618: padding: 0;
8619: }
8620:
8621: .LC_ListStyleSimple li,
8622: .LC_ListStyleSimple dd,
8623: .LC_ListStyleNormal li,
8624: .LC_ListStyleNormal dd,
8625: .LC_ListStyleSpecial li,
8626: .LC_ListStyleSpecial dd {
8627: margin: 0;
8628: padding: 5px 5px 5px 10px;
8629: clear: both;
8630: }
8631:
8632: .LC_ListStyleClean li,
8633: .LC_ListStyleClean dd {
8634: padding-top: 0;
8635: padding-bottom: 0;
8636: }
8637:
8638: .LC_ListStyleSimple dd,
8639: .LC_ListStyleSimple li {
8640: border-bottom: solid 1px $lg_border_color;
8641: }
8642:
8643: .LC_ListStyleSpecial li,
8644: .LC_ListStyleSpecial dd {
8645: list-style-type: none;
8646: background-color: RGB(220, 220, 220);
8647: margin-bottom: 4px;
8648: }
8649:
8650: table.LC_SimpleTable {
8651: margin:5px;
8652: border:solid 1px $lg_border_color;
8653: }
8654:
8655: table.LC_SimpleTable tr {
8656: padding: 0;
8657: border:solid 1px $lg_border_color;
8658: }
8659:
8660: table.LC_SimpleTable thead {
8661: background:rgb(220,220,220);
8662: }
8663:
8664: div.LC_columnSection {
8665: display: block;
8666: clear: both;
8667: overflow: hidden;
8668: margin: 0;
8669: }
8670:
8671: div.LC_columnSection>* {
8672: float: left;
8673: margin: 10px 20px 10px 0;
8674: overflow:hidden;
8675: }
8676:
8677: table em {
8678: font-weight: bold;
8679: font-style: normal;
8680: }
8681:
8682: table.LC_tableBrowseRes,
8683: table.LC_tableOfContent {
8684: border:none;
8685: border-spacing: 1px;
8686: padding: 3px;
8687: background-color: #FFFFFF;
8688: font-size: 90%;
8689: }
8690:
8691: table.LC_tableOfContent {
8692: border-collapse: collapse;
8693: }
8694:
8695: table.LC_tableBrowseRes a,
8696: table.LC_tableOfContent a {
8697: background-color: transparent;
8698: text-decoration: none;
8699: }
8700:
8701: table.LC_tableOfContent img {
8702: border: none;
8703: height: 1.3em;
8704: vertical-align: text-bottom;
8705: margin-right: 0.3em;
8706: }
8707:
8708: a#LC_content_toolbar_firsthomework {
8709: background-image:url(/res/adm/pages/open-first-problem.gif);
8710: }
8711:
8712: a#LC_content_toolbar_everything {
8713: background-image:url(/res/adm/pages/show-all.gif);
8714: }
8715:
8716: a#LC_content_toolbar_uncompleted {
8717: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
8718: }
8719:
8720: #LC_content_toolbar_clearbubbles {
8721: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
8722: }
8723:
8724: a#LC_content_toolbar_changefolder {
8725: background : url(/res/adm/pages/close-all-folders.gif) top center ;
8726: }
8727:
8728: a#LC_content_toolbar_changefolder_toggled {
8729: background-image:url(/res/adm/pages/open-all-folders.gif);
8730: }
8731:
8732: a#LC_content_toolbar_edittoplevel {
8733: background-image:url(/res/adm/pages/edittoplevel.gif);
8734: }
8735:
8736: a#LC_content_toolbar_printout {
8737: background-image:url(/res/adm/pages/printout.gif);
8738: }
8739:
8740: ul#LC_toolbar li a:hover {
8741: background-position: bottom center;
8742: }
8743:
8744: ul#LC_toolbar {
8745: padding: 0;
8746: margin: 2px;
8747: list-style:none;
8748: position:relative;
8749: background-color:white;
8750: overflow: auto;
8751: }
8752:
8753: ul#LC_toolbar li {
8754: border:1px solid white;
8755: padding: 0;
8756: margin: 0;
8757: float: left;
8758: display:inline;
8759: vertical-align:middle;
8760: white-space: nowrap;
8761: }
8762:
8763:
8764: a.LC_toolbarItem {
8765: display:block;
8766: padding: 0;
8767: margin: 0;
8768: height: 32px;
8769: width: 32px;
8770: color:white;
8771: border: none;
8772: background-repeat:no-repeat;
8773: background-color:transparent;
8774: }
8775:
8776: ul.LC_funclist {
8777: margin: 0;
8778: padding: 0.5em 1em 0.5em 0;
8779: }
8780:
8781: ul.LC_funclist > li:first-child {
8782: font-weight:bold;
8783: margin-left:0.8em;
8784: }
8785:
8786: ul.LC_funclist + ul.LC_funclist {
8787: /*
8788: left border as a seperator if we have more than
8789: one list
8790: */
8791: border-left: 1px solid $sidebg;
8792: /*
8793: this hides the left border behind the border of the
8794: outer box if element is wrapped to the next 'line'
8795: */
8796: margin-left: -1px;
8797: }
8798:
8799: ul.LC_funclist li {
8800: display: inline;
8801: white-space: nowrap;
8802: margin: 0 0 0 25px;
8803: line-height: 150%;
8804: }
8805:
8806: .LC_hidden {
8807: display: none;
8808: }
8809:
8810: .LCmodal-overlay {
8811: position:fixed;
8812: top:0;
8813: right:0;
8814: bottom:0;
8815: left:0;
8816: height:100%;
8817: width:100%;
8818: margin:0;
8819: padding:0;
8820: background:#999;
8821: opacity:.75;
8822: filter: alpha(opacity=75);
8823: -moz-opacity: 0.75;
8824: z-index:101;
8825: }
8826:
8827: * html .LCmodal-overlay {
8828: position: absolute;
8829: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
8830: }
8831:
8832: .LCmodal-window {
8833: position:fixed;
8834: top:50%;
8835: left:50%;
8836: margin:0;
8837: padding:0;
8838: z-index:102;
8839: }
8840:
8841: * html .LCmodal-window {
8842: position:absolute;
8843: }
8844:
8845: .LCclose-window {
8846: position:absolute;
8847: width:32px;
8848: height:32px;
8849: right:8px;
8850: top:8px;
8851: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
8852: text-indent:-99999px;
8853: overflow:hidden;
8854: cursor:pointer;
8855: }
8856:
8857: .LCisDisabled {
8858: cursor: not-allowed;
8859: opacity: 0.5;
8860: }
8861:
8862: a[aria-disabled="true"] {
8863: color: currentColor;
8864: display: inline-block; /* For IE11/ MS Edge bug */
8865: pointer-events: none;
8866: text-decoration: none;
8867: }
8868:
8869: pre.LC_wordwrap {
8870: white-space: pre-wrap;
8871: white-space: -moz-pre-wrap;
8872: white-space: -pre-wrap;
8873: white-space: -o-pre-wrap;
8874: word-wrap: break-word;
8875: }
8876:
8877: /*
8878: styles used for response display
8879: */
8880: div.LC_radiofoil, div.LC_rankfoil {
8881: margin: .5em 0em .5em 0em;
8882: }
8883: table.LC_itemgroup {
8884: margin-top: 1em;
8885: }
8886:
8887: /*
8888: styles used by TTH when "Default set of options to pass to tth/m
8889: when converting TeX" in course settings has been set
8890:
8891: option passed: -t
8892:
8893: */
8894:
8895: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8896: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8897: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8898: td div.norm {line-height:normal;}
8899:
8900: /*
8901: option passed -y3
8902: */
8903:
8904: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8905: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8906: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8907:
8908: /*
8909: sections with roles, for content only
8910: */
8911: section[class^="role-"] {
8912: padding-left: 10px;
8913: padding-right: 5px;
8914: margin-top: 8px;
8915: margin-bottom: 8px;
8916: border: 1px solid #2A4;
8917: border-radius: 5px;
8918: box-shadow: 0px 1px 1px #BBB;
8919: }
8920: section[class^="role-"]>h1 {
8921: position: relative;
8922: margin: 0px;
8923: padding-top: 10px;
8924: padding-left: 40px;
8925: }
8926: section[class^="role-"]>h1:before {
8927: position: absolute;
8928: left: -5px;
8929: top: 5px;
8930: }
8931: section.role-activity>h1:before {
8932: content:url('/adm/daxe/images/section_icons/activity.png');
8933: }
8934: section.role-advice>h1:before {
8935: content:url('/adm/daxe/images/section_icons/advice.png');
8936: }
8937: section.role-bibliography>h1:before {
8938: content:url('/adm/daxe/images/section_icons/bibliography.png');
8939: }
8940: section.role-citation>h1:before {
8941: content:url('/adm/daxe/images/section_icons/citation.png');
8942: }
8943: section.role-conclusion>h1:before {
8944: content:url('/adm/daxe/images/section_icons/conclusion.png');
8945: }
8946: section.role-definition>h1:before {
8947: content:url('/adm/daxe/images/section_icons/definition.png');
8948: }
8949: section.role-demonstration>h1:before {
8950: content:url('/adm/daxe/images/section_icons/demonstration.png');
8951: }
8952: section.role-example>h1:before {
8953: content:url('/adm/daxe/images/section_icons/example.png');
8954: }
8955: section.role-explanation>h1:before {
8956: content:url('/adm/daxe/images/section_icons/explanation.png');
8957: }
8958: section.role-introduction>h1:before {
8959: content:url('/adm/daxe/images/section_icons/introduction.png');
8960: }
8961: section.role-method>h1:before {
8962: content:url('/adm/daxe/images/section_icons/method.png');
8963: }
8964: section.role-more_information>h1:before {
8965: content:url('/adm/daxe/images/section_icons/more_information.png');
8966: }
8967: section.role-objectives>h1:before {
8968: content:url('/adm/daxe/images/section_icons/objectives.png');
8969: }
8970: section.role-prerequisites>h1:before {
8971: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8972: }
8973: section.role-remark>h1:before {
8974: content:url('/adm/daxe/images/section_icons/remark.png');
8975: }
8976: section.role-reminder>h1:before {
8977: content:url('/adm/daxe/images/section_icons/reminder.png');
8978: }
8979: section.role-summary>h1:before {
8980: content:url('/adm/daxe/images/section_icons/summary.png');
8981: }
8982: section.role-syntax>h1:before {
8983: content:url('/adm/daxe/images/section_icons/syntax.png');
8984: }
8985: section.role-warning>h1:before {
8986: content:url('/adm/daxe/images/section_icons/warning.png');
8987: }
8988:
8989: #LC_minitab_header {
8990: float:left;
8991: width:100%;
8992: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
8993: font-size:93%;
8994: line-height:normal;
8995: margin: 0.5em 0 0.5em 0;
8996: }
8997: #LC_minitab_header ul {
8998: margin:0;
8999: padding:10px 10px 0;
9000: list-style:none;
9001: }
9002: #LC_minitab_header li {
9003: float:left;
9004: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
9005: margin:0;
9006: padding:0 0 0 9px;
9007: }
9008: #LC_minitab_header a {
9009: display:block;
9010: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
9011: padding:5px 15px 4px 6px;
9012: }
9013: #LC_minitab_header #LC_current_minitab {
9014: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
9015: }
9016: #LC_minitab_header #LC_current_minitab a {
9017: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
9018: padding-bottom:5px;
9019: }
9020:
9021:
9022: END
9023: }
9024:
9025: =pod
9026:
9027: =item * &headtag()
9028:
9029: Returns a uniform footer for LON-CAPA web pages.
9030:
9031: Inputs: $title - optional title for the head
9032: $head_extra - optional extra HTML to put inside the <head>
9033: $args - optional arguments
9034: force_register - if is true call registerurl so the remote is
9035: informed
9036: redirect -> array ref of
9037: 1- seconds before redirect occurs
9038: 2- url to redirect to
9039: 3- whether the side effect should occur
9040: (side effect of setting
9041: $env{'internal.head.redirect'} to the url
9042: redirected to)
9043: 4- whether the redirect target should be
9044: the opener of the current (pop-up)
9045: window (side effect of setting
9046: $env{'internal.head.to_opener'} to
9047: 1, if true.
9048: 5- whether encrypt check should be skipped
9049: domain -> force to color decorate a page for a specific
9050: domain
9051: function -> force usage of a specific rolish color scheme
9052: bgcolor -> override the default page bgcolor
9053: no_auto_mt_title
9054: -> prevent &mt()ing the title arg
9055:
9056: =cut
9057:
9058: sub headtag {
9059: my ($title,$head_extra,$args) = @_;
9060:
9061: my $function = $args->{'function'} || &get_users_function();
9062: my $domain = $args->{'domain'} || &determinedomain();
9063: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
9064: my $httphost = $args->{'use_absolute'};
9065: my $url = join(':',$env{'user.name'},$env{'user.domain'},
9066: $Apache::lonnet::perlvar{'lonVersion'},
9067: #time(),
9068: $env{'environment.color.timestamp'},
9069: $function,$domain,$bgcolor);
9070:
9071: $url = '/adm/css/'.&escape($url).'.css';
9072:
9073: my $result =
9074: '<head>'.
9075: &font_settings($args);
9076:
9077: my $inhibitprint;
9078: if ($args->{'print_suppress'}) {
9079: $inhibitprint = &print_suppression();
9080: }
9081:
9082: if (!$args->{'frameset'}) {
9083: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
9084: }
9085: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
9086: $result .= Apache::lonxml::display_title();
9087: }
9088: if (!$args->{'no_nav_bar'}
9089: && !$args->{'only_body'}
9090: && !$args->{'frameset'}) {
9091: $result .= &help_menu_js($httphost);
9092: $result.=&modal_window();
9093: $result.=&togglebox_script();
9094: $result.=&wishlist_window();
9095: $result.=&LCprogressbarUpdate_script();
9096: } else {
9097: if ($args->{'add_modal'}) {
9098: $result.=&modal_window();
9099: }
9100: if ($args->{'add_wishlist'}) {
9101: $result.=&wishlist_window();
9102: }
9103: if ($args->{'add_togglebox'}) {
9104: $result.=&togglebox_script();
9105: }
9106: if ($args->{'add_progressbar'}) {
9107: $result.=&LCprogressbarUpdate_script();
9108: }
9109: }
9110: if (ref($args->{'redirect'})) {
9111: my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
9112: if (!$skip_enc_check) {
9113: $url = &Apache::lonenc::check_encrypt($url);
9114: }
9115: if (!$inhibit_continue) {
9116: $env{'internal.head.redirect'} = $url;
9117: }
9118: $result.=<<"ADDMETA";
9119: <meta http-equiv="pragma" content="no-cache" />
9120: ADDMETA
9121: if ($to_opener) {
9122: $env{'internal.head.to_opener'} = 1;
9123: my $dest = &js_escape($url);
9124: my $timeout = int($time * 1000);
9125: $result .=<<"ENDJS";
9126: <script type="text/javascript">
9127: // <![CDATA[
9128: function LC_To_Opener() {
9129: var dest = '$dest';
9130: if (dest != '') {
9131: if (window.opener != null && !window.opener.closed) {
9132: window.opener.location.href=dest;
9133: window.close();
9134: } else {
9135: window.location.href=dest;
9136: }
9137: }
9138: }
9139: \$(document).ready(function () {
9140: setTimeout('LC_To_Opener()',$timeout);
9141: });
9142: // ]]>
9143: </script>
9144: ENDJS
9145: } else {
9146: $result.=<<"ADDMETA";
9147: <meta http-equiv="Refresh" content="$time; url=$url" />
9148: ADDMETA
9149: }
9150: } else {
9151: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
9152: my $requrl = $env{'request.uri'};
9153: if ($requrl eq '') {
9154: $requrl = $ENV{'REQUEST_URI'};
9155: $requrl =~ s/\?.+$//;
9156: }
9157: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
9158: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
9159: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
9160: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
9161: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
9162: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
9163: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
9164: my ($offload,$offloadoth);
9165: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
9166: if ($domdefs{'offloadnow'}{$lonhost}) {
9167: $offload = 1;
9168: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
9169: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
9170: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
9171: $offloadoth = 1;
9172: $dom_in_use = $env{'user.domain'};
9173: }
9174: }
9175: }
9176: }
9177: unless ($offload) {
9178: if (ref($domdefs{'offloadoth'}) eq 'HASH') {
9179: if ($domdefs{'offloadoth'}{$lonhost}) {
9180: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
9181: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
9182: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
9183: $offload = 1;
9184: $offloadoth = 1;
9185: $dom_in_use = $env{'user.domain'};
9186: }
9187: }
9188: }
9189: }
9190: }
9191: if ($offload) {
9192: my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
9193: if (($newserver eq '') && ($offloadoth)) {
9194: my @domains = &Apache::lonnet::current_machine_domains();
9195: if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
9196: ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
9197: }
9198: }
9199: if (($newserver) && ($newserver ne $lonhost)) {
9200: my $numsec = 5;
9201: my $timeout = $numsec * 1000;
9202: my ($newurl,$locknum,%locks,$msg);
9203: if ($env{'request.role.adv'}) {
9204: ($locknum,%locks) = &Apache::lonnet::get_locks();
9205: }
9206: my $disable_submit = 0;
9207: if ($requrl =~ /$LONCAPA::assess_re/) {
9208: $disable_submit = 1;
9209: }
9210: if ($locknum) {
9211: my @lockinfo = sort(values(%locks));
9212: $msg = &mt('Once the following tasks are complete:')." \n".
9213: join(", ",sort(values(%locks)))."\n";
9214: if (&show_course()) {
9215: $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
9216: } else {
9217: $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
9218: }
9219: } else {
9220: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
9221: $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
9222: }
9223: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
9224: $newurl = '/adm/switchserver?otherserver='.$newserver;
9225: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
9226: $newurl .= '&role='.$env{'request.role'};
9227: }
9228: if ($env{'request.symb'}) {
9229: my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
9230: if ($shownsymb =~ m{^/enc/}) {
9231: my $reqdmajor = 2;
9232: my $reqdminor = 11;
9233: my $reqdsubminor = 3;
9234: my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
9235: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
9236: my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
9237: if (($major eq '' && $minor eq '') ||
9238: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
9239: (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
9240: ($reqdsubminor > $subminor))))) {
9241: undef($shownsymb);
9242: }
9243: }
9244: if ($shownsymb) {
9245: &js_escape(\$shownsymb);
9246: $newurl .= '&symb='.$shownsymb;
9247: }
9248: } else {
9249: my $shownurl = &Apache::lonenc::check_encrypt($requrl);
9250: &js_escape(\$shownurl);
9251: $newurl .= '&origurl='.$shownurl;
9252: }
9253: }
9254: &js_escape(\$msg);
9255: $result.=<<OFFLOAD
9256: <meta http-equiv="pragma" content="no-cache" />
9257: <script type="text/javascript">
9258: // <![CDATA[
9259: function LC_Offload_Now() {
9260: var dest = "$newurl";
9261: if (dest != '') {
9262: window.location.href="$newurl";
9263: }
9264: }
9265: \$(document).ready(function () {
9266: window.alert('$msg');
9267: if ($disable_submit) {
9268: \$(".LC_hwk_submit").prop("disabled", true);
9269: \$( ".LC_textline" ).prop( "readonly", "readonly");
9270: }
9271: setTimeout('LC_Offload_Now()', $timeout);
9272: });
9273: // ]]>
9274: </script>
9275: OFFLOAD
9276: }
9277: }
9278: }
9279: }
9280: }
9281: }
9282: if (!defined($title)) {
9283: $title = 'The LearningOnline Network with CAPA';
9284: }
9285: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
9286: $result .= '<title> LON-CAPA '.$title.'</title>'
9287: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
9288: if (!$args->{'frameset'}) {
9289: $result .= ' /';
9290: }
9291: $result .= '>'
9292: .$inhibitprint
9293: .$head_extra;
9294: my $clientmobile;
9295: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
9296: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
9297: } else {
9298: $clientmobile = $env{'browser.mobile'};
9299: }
9300: if ($clientmobile) {
9301: $result .= '
9302: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
9303: <meta name="apple-mobile-web-app-capable" content="yes" />';
9304: }
9305: $result .= '<meta name="google" content="notranslate" />'."\n";
9306: return $result.'</head>';
9307: }
9308:
9309: =pod
9310:
9311: =item * &font_settings()
9312:
9313: Returns neccessary <meta> to set the proper encoding
9314:
9315: Inputs: optional reference to HASH -- $args passed to &headtag()
9316:
9317: =cut
9318:
9319: sub font_settings {
9320: my ($args) = @_;
9321: my $headerstring='';
9322: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
9323: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
9324: $headerstring.=
9325: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
9326: if (!$args->{'frameset'}) {
9327: $headerstring.= ' /';
9328: }
9329: $headerstring .= '>'."\n";
9330: }
9331: return $headerstring;
9332: }
9333:
9334: =pod
9335:
9336: =item * &print_suppression()
9337:
9338: In course context returns css which causes the body to be blank when media="print",
9339: if printout generation is unavailable for the current resource.
9340:
9341: This could be because:
9342:
9343: (a) printstartdate is in the future
9344:
9345: (b) printenddate is in the past
9346:
9347: (c) there is an active exam block with "printout"
9348: functionality blocked
9349:
9350: Users with pav, pfo or evb privileges are exempt.
9351:
9352: Inputs: none
9353:
9354: =cut
9355:
9356:
9357: sub print_suppression {
9358: my $noprint;
9359: if ($env{'request.course.id'}) {
9360: my $scope = $env{'request.course.id'};
9361: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9362: (&Apache::lonnet::allowed('pfo',$scope))) {
9363: return;
9364: }
9365: if ($env{'request.course.sec'} ne '') {
9366: $scope .= "/$env{'request.course.sec'}";
9367: if ((&Apache::lonnet::allowed('pav',$scope)) ||
9368: (&Apache::lonnet::allowed('pfo',$scope))) {
9369: return;
9370: }
9371: }
9372: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9373: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9374: my $clientip = &Apache::lonnet::get_requestor_ip();
9375: my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
9376: if ($blocked) {
9377: my $checkrole = "cm./$cdom/$cnum";
9378: if ($env{'request.course.sec'} ne '') {
9379: $checkrole .= "/$env{'request.course.sec'}";
9380: }
9381: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
9382: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
9383: $noprint = 1;
9384: }
9385: }
9386: unless ($noprint) {
9387: my $symb = &Apache::lonnet::symbread();
9388: if ($symb ne '') {
9389: my $navmap = Apache::lonnavmaps::navmap->new();
9390: if (ref($navmap)) {
9391: my $res = $navmap->getBySymb($symb);
9392: if (ref($res)) {
9393: if (!$res->resprintable()) {
9394: $noprint = 1;
9395: }
9396: }
9397: }
9398: }
9399: }
9400: if ($noprint) {
9401: return <<"ENDSTYLE";
9402: <style type="text/css" media="print">
9403: body { display:none }
9404: </style>
9405: ENDSTYLE
9406: }
9407: }
9408: return;
9409: }
9410:
9411: =pod
9412:
9413: =item * &xml_begin()
9414:
9415: Returns the needed doctype and <html>
9416:
9417: Inputs: none
9418:
9419: =cut
9420:
9421: sub xml_begin {
9422: my ($is_frameset) = @_;
9423: my $output='';
9424:
9425: if ($env{'browser.mathml'}) {
9426: $output='<?xml version="1.0"?>'
9427: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
9428: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
9429:
9430: # .'<!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">] >'
9431: .'<!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">'
9432: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
9433: .'xmlns="http://www.w3.org/1999/xhtml">';
9434: } elsif ($is_frameset) {
9435: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
9436: '<html>'."\n";
9437: } else {
9438: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
9439: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
9440: }
9441: return $output;
9442: }
9443:
9444: =pod
9445:
9446: =item * &start_page()
9447:
9448: Returns a complete <html> .. <body> section for LON-CAPA web pages.
9449:
9450: Inputs:
9451:
9452: =over 4
9453:
9454: $title - optional title for the page
9455:
9456: $head_extra - optional extra HTML to incude inside the <head>
9457:
9458: $args - additional optional args supported are:
9459:
9460: =over 8
9461:
9462: only_body -> is true will set &bodytag() onlybodytag
9463: arg on
9464: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
9465: add_entries -> additional attributes to add to the <body>
9466: domain -> force to color decorate a page for a
9467: specific domain
9468: function -> force usage of a specific rolish color
9469: scheme
9470: redirect -> see &headtag()
9471: bgcolor -> override the default page bg color
9472: js_ready -> return a string ready for being used in
9473: a javascript writeln
9474: html_encode -> return a string ready for being used in
9475: a html attribute
9476: force_register -> if is true will turn on the &bodytag()
9477: $forcereg arg
9478: frameset -> if true will start with a <frameset>
9479: rather than <body>
9480: skip_phases -> hash ref of
9481: head -> skip the <html><head> generation
9482: body -> skip all <body> generation
9483: no_auto_mt_title -> prevent &mt()ing the title arg
9484: bread_crumbs -> Array containing breadcrumbs
9485: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
9486: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
9487: to lonhtmlcommon::breadcrumbs
9488: group -> includes the current group, if page is for a
9489: specific group
9490: use_absolute -> for request for external resource or syllabus, this
9491: will contain https://<hostname> if server uses
9492: https (as per hosts.tab), but request is for http
9493: hostname -> hostname, originally from $r->hostname(), (optional).
9494: links_disabled -> Links in primary and secondary menus are disabled
9495: (Can enable them once page has loaded - see lonroles.pm
9496: for an example).
9497: links_target -> Target for links, e.g., _parent (optional).
9498:
9499: =back
9500:
9501: =back
9502:
9503: =cut
9504:
9505: sub start_page {
9506: my ($title,$head_extra,$args) = @_;
9507: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
9508:
9509: $env{'internal.start_page'}++;
9510: my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
9511:
9512: if (! exists($args->{'skip_phases'}{'head'}) ) {
9513: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
9514: }
9515:
9516: if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
9517: if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
9518: unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
9519: $args->{'no_primary_menu'} = 1;
9520: }
9521: unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
9522: $args->{'no_inline_menu'} = 1;
9523: }
9524: if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
9525: map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
9526: }
9527: } else {
9528: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9529: my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
9530: if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
9531: unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
9532: $args->{'no_primary_menu'} = 1;
9533: }
9534: unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
9535: $args->{'no_inline_menu'} = 1;
9536: }
9537: if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
9538: map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
9539: }
9540: }
9541: }
9542: ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
9543: $env{'course.'.$env{'request.course.id'}.'.domain'},
9544: $env{'course.'.$env{'request.course.id'}.'.num'});
9545: } elsif ($env{'request.course.id'}) {
9546: my $expiretime=600;
9547: if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
9548: &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
9549: }
9550: my ($deeplinkmenu,$menuref);
9551: ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
9552: if ($menucoll) {
9553: if (ref($menuref) eq 'HASH') {
9554: %menu = %{$menuref};
9555: }
9556: if ($menu{'top'} eq 'n') {
9557: $args->{'no_primary_menu'} = 1;
9558: }
9559: if ($menu{'inline'} eq 'n') {
9560: unless (&Apache::lonnet::allowed('opa')) {
9561: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9562: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9563: my $crstype = &course_type();
9564: my $now = time;
9565: my $ccrole;
9566: if ($crstype eq 'Community') {
9567: $ccrole = 'co';
9568: } else {
9569: $ccrole = 'cc';
9570: }
9571: if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
9572: my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
9573: if ((($start) && ($start<0)) ||
9574: (($end) && ($end<$now)) ||
9575: (($start) && ($now<$start))) {
9576: $args->{'no_inline_menu'} = 1;
9577: }
9578: } else {
9579: $args->{'no_inline_menu'} = 1;
9580: }
9581: }
9582: }
9583: }
9584: }
9585:
9586: my $showncrumbs;
9587: if (! exists($args->{'skip_phases'}{'body'}) ) {
9588: if ($args->{'frameset'}) {
9589: my $attr_string = &make_attr_string($args->{'force_register'},
9590: $args->{'add_entries'});
9591: $result .= "\n<frameset $attr_string>\n";
9592: } else {
9593: $result .=
9594: &bodytag($title,
9595: $args->{'function'}, $args->{'add_entries'},
9596: $args->{'only_body'}, $args->{'domain'},
9597: $args->{'force_register'}, $args->{'no_nav_bar'},
9598: $args->{'bgcolor'}, $args,
9599: \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
9600: \%menu,\$showncrumbs);
9601: }
9602: }
9603:
9604: if ($args->{'js_ready'}) {
9605: $result = &js_ready($result);
9606: }
9607: if ($args->{'html_encode'}) {
9608: $result = &html_encode($result);
9609: }
9610:
9611: # Preparation for new and consistent functionlist at top of screen
9612: # if ($args->{'functionlist'}) {
9613: # $result .= &build_functionlist();
9614: #}
9615:
9616: # Don't add anything more if only_body wanted or in const space
9617: return $result if $args->{'only_body'}
9618: || $env{'request.state'} eq 'construct';
9619:
9620: #Breadcrumbs
9621: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
9622: unless ($showncrumbs) {
9623: &Apache::lonhtmlcommon::clear_breadcrumbs();
9624: #if any br links exists, add them to the breadcrumbs
9625: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
9626: foreach my $crumb (@{$args->{'bread_crumbs'}}){
9627: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
9628: }
9629: }
9630: # if @advtools array contains items add then to the breadcrumbs
9631: if (@advtools > 0) {
9632: &Apache::lonmenu::advtools_crumbs(@advtools);
9633: }
9634: my $menulink;
9635: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
9636: if ((exists($args->{'bread_crumbs_nomenu'})) ||
9637: ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
9638: ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
9639: ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
9640: (!$env{'request.role.adv'}))) {
9641: $menulink = 0;
9642: } else {
9643: undef($menulink);
9644: }
9645: my $linkprotout;
9646: if ($env{'request.deeplink.login'}) {
9647: my $linkprotout = &Apache::lonmenu::linkprot_exit();
9648: if ($linkprotout) {
9649: &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
9650: }
9651: }
9652: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
9653: if(exists($args->{'bread_crumbs_component'})){
9654: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
9655: } else {
9656: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
9657: }
9658: }
9659: }
9660: return $result;
9661: }
9662:
9663: sub end_page {
9664: my ($args) = @_;
9665: $env{'internal.end_page'}++;
9666: my $result;
9667: if ($args->{'discussion'}) {
9668: my ($target,$parser);
9669: if (ref($args->{'discussion'})) {
9670: ($target,$parser) =($args->{'discussion'}{'target'},
9671: $args->{'discussion'}{'parser'});
9672: }
9673: $result .= &Apache::lonxml::xmlend($target,$parser);
9674: }
9675: if ($args->{'frameset'}) {
9676: $result .= '</frameset>';
9677: } else {
9678: $result .= &endbodytag($args);
9679: }
9680: unless ($args->{'notbody'}) {
9681: $result .= "\n</html>";
9682: }
9683:
9684: if ($args->{'js_ready'}) {
9685: $result = &js_ready($result);
9686: }
9687:
9688: if ($args->{'html_encode'}) {
9689: $result = &html_encode($result);
9690: }
9691:
9692: return $result;
9693: }
9694:
9695: sub menucoll_in_effect {
9696: my ($menucoll,$deeplinkmenu,%menu);
9697: if ($env{'request.course.id'}) {
9698: $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
9699: if ($env{'request.deeplink.login'}) {
9700: my ($deeplink_symb,$deeplink,$check_login_symb);
9701: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9702: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9703: if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
9704: if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
9705: my $navmap = Apache::lonnavmaps::navmap->new();
9706: if (ref($navmap)) {
9707: $deeplink = $navmap->get_mapparam(undef,
9708: &Apache::lonnet::declutter($env{'request.noversionuri'}),
9709: '0.deeplink');
9710: } else {
9711: $check_login_symb = 1;
9712: }
9713: } else {
9714: my $symb = &Apache::lonnet::symbread();
9715: if ($symb) {
9716: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
9717: } else {
9718: $check_login_symb = 1;
9719: }
9720: }
9721: } else {
9722: $check_login_symb = 1;
9723: }
9724: if ($check_login_symb) {
9725: $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
9726: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9727: my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
9728: my $navmap = Apache::lonnavmaps::navmap->new();
9729: if (ref($navmap)) {
9730: $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
9731: }
9732: } else {
9733: $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
9734: }
9735: }
9736: if ($deeplink ne '') {
9737: my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
9738: if ($display =~ /^\d+$/) {
9739: $deeplinkmenu = 1;
9740: $menucoll = $display;
9741: }
9742: }
9743: }
9744: if ($menucoll) {
9745: %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
9746: }
9747: }
9748: return ($menucoll,$deeplinkmenu,\%menu);
9749: }
9750:
9751: sub deeplink_login_symb {
9752: my ($cnum,$cdom) = @_;
9753: my $login_symb;
9754: if ($env{'request.deeplink.login'}) {
9755: $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
9756: }
9757: return $login_symb;
9758: }
9759:
9760: sub symb_from_tinyurl {
9761: my ($url,$cnum,$cdom) = @_;
9762: if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
9763: my $key = $1;
9764: my ($tinyurl,$login);
9765: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
9766: if (defined($cached)) {
9767: $tinyurl = $result;
9768: } else {
9769: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
9770: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
9771: if ($currtiny{$key} ne '') {
9772: $tinyurl = $currtiny{$key};
9773: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
9774: }
9775: }
9776: if ($tinyurl ne '') {
9777: my ($cnumreq,$symb) = split(/\&/,$tinyurl);
9778: if (wantarray) {
9779: return ($cnumreq,$symb);
9780: } elsif ($cnumreq eq $cnum) {
9781: return $symb;
9782: }
9783: }
9784: }
9785: if (wantarray) {
9786: return ();
9787: } else {
9788: return;
9789: }
9790: }
9791:
9792: sub usable_exttools {
9793: my %tooltypes;
9794: if ($env{'request.course.id'}) {
9795: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
9796: if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
9797: %tooltypes = (
9798: crs => 1,
9799: dom => 1,
9800: );
9801: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
9802: $tooltypes{'crs'} = 1;
9803: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
9804: $tooltypes{'dom'} = 1;
9805: }
9806: } else {
9807: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9808: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9809: my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
9810: if ($crstype eq '') {
9811: $crstype = 'course';
9812: }
9813: if ($crstype eq 'course') {
9814: if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
9815: $crstype = 'official';
9816: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
9817: $crstype = 'textbook';
9818: } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
9819: $crstype = 'lti';
9820: } else {
9821: $crstype = 'unofficial';
9822: }
9823: }
9824: my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
9825: if ($domdefaults{$crstype.'domexttool'}) {
9826: $tooltypes{'dom'} = 1;
9827: }
9828: if ($domdefaults{$crstype.'exttool'}) {
9829: $tooltypes{'crs'} = 1;
9830: }
9831: }
9832: }
9833: return %tooltypes;
9834: }
9835:
9836: sub wishlist_window {
9837: return(<<'ENDWISHLIST');
9838: <script type="text/javascript">
9839: // <![CDATA[
9840: // <!-- BEGIN LON-CAPA Internal
9841: function set_wishlistlink(title, path) {
9842: if (!title) {
9843: title = document.title;
9844: title = title.replace(/^LON-CAPA /,'');
9845: }
9846: title = encodeURIComponent(title);
9847: title = title.replace("'","\\\'");
9848: if (!path) {
9849: path = location.pathname;
9850: }
9851: path = encodeURIComponent(path);
9852: path = path.replace("'","\\\'");
9853: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
9854: 'wishlistNewLink','width=560,height=350,scrollbars=0');
9855: }
9856: // END LON-CAPA Internal -->
9857: // ]]>
9858: </script>
9859: ENDWISHLIST
9860: }
9861:
9862: sub modal_window {
9863: return(<<'ENDMODAL');
9864: <script type="text/javascript">
9865: // <![CDATA[
9866: // <!-- BEGIN LON-CAPA Internal
9867: var modalWindow = {
9868: parent:"body",
9869: windowId:null,
9870: content:null,
9871: width:null,
9872: height:null,
9873: close:function()
9874: {
9875: $(".LCmodal-window").remove();
9876: $(".LCmodal-overlay").remove();
9877: },
9878: open:function()
9879: {
9880: var modal = "";
9881: modal += "<div class=\"LCmodal-overlay\"></div>";
9882: 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;\">";
9883: modal += this.content;
9884: modal += "</div>";
9885:
9886: $(this.parent).append(modal);
9887:
9888: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
9889: $(".LCclose-window").click(function(){modalWindow.close();});
9890: $(".LCmodal-overlay").click(function(){modalWindow.close();});
9891: }
9892: };
9893: var openMyModal = function(source,width,height,scrolling,transparency,style)
9894: {
9895: source = source.replace(/'/g,"'");
9896: modalWindow.windowId = "myModal";
9897: modalWindow.width = width;
9898: modalWindow.height = height;
9899: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
9900: modalWindow.open();
9901: };
9902: // END LON-CAPA Internal -->
9903: // ]]>
9904: </script>
9905: ENDMODAL
9906: }
9907:
9908: sub modal_link {
9909: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
9910: unless ($width) { $width=480; }
9911: unless ($height) { $height=400; }
9912: unless ($scrolling) { $scrolling='yes'; }
9913: unless ($transparency) { $transparency='true'; }
9914:
9915: my $target_attr;
9916: if (defined($target)) {
9917: $target_attr = 'target="'.$target.'"';
9918: }
9919: return <<"ENDLINK";
9920: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
9921: ENDLINK
9922: }
9923:
9924: sub modal_adhoc_script {
9925: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9926: my $mathjax;
9927: if ($possmathjax) {
9928: $mathjax = <<'ENDJAX';
9929: if (typeof MathJax == 'object') {
9930: MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
9931: }
9932: ENDJAX
9933: }
9934: return (<<ENDADHOC);
9935: <script type="text/javascript">
9936: // <![CDATA[
9937: var $funcname = function()
9938: {
9939: modalWindow.windowId = "myModal";
9940: modalWindow.width = $width;
9941: modalWindow.height = $height;
9942: modalWindow.content = '$content';
9943: modalWindow.open();
9944: $mathjax
9945: };
9946: // ]]>
9947: </script>
9948: ENDADHOC
9949: }
9950:
9951: sub modal_adhoc_inner {
9952: my ($funcname,$width,$height,$content,$possmathjax)=@_;
9953: my $innerwidth=$width-20;
9954: $content=&js_ready(
9955: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
9956: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
9957: $content.
9958: &end_scrollbox().
9959: &end_page()
9960: );
9961: return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
9962: }
9963:
9964: sub modal_adhoc_window {
9965: my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
9966: return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
9967: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
9968: }
9969:
9970: sub modal_adhoc_launch {
9971: my ($funcname,$width,$height,$content)=@_;
9972: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
9973: <script type="text/javascript">
9974: // <![CDATA[
9975: $funcname();
9976: // ]]>
9977: </script>
9978: ENDLAUNCH
9979: }
9980:
9981: sub modal_adhoc_close {
9982: return (<<ENDCLOSE);
9983: <script type="text/javascript">
9984: // <![CDATA[
9985: modalWindow.close();
9986: // ]]>
9987: </script>
9988: ENDCLOSE
9989: }
9990:
9991: sub togglebox_script {
9992: return(<<ENDTOGGLE);
9993: <script type="text/javascript">
9994: // <![CDATA[
9995: function LCtoggleDisplay(id,hidetext,showtext) {
9996: link = document.getElementById(id + "link").childNodes[0];
9997: with (document.getElementById(id).style) {
9998: if (display == "none" ) {
9999: display = "inline";
10000: link.nodeValue = hidetext;
10001: } else {
10002: display = "none";
10003: link.nodeValue = showtext;
10004: }
10005: }
10006: }
10007: // ]]>
10008: </script>
10009: ENDTOGGLE
10010: }
10011:
10012: sub start_togglebox {
10013: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
10014: unless ($heading) { $heading=''; } else { $heading.=' '; }
10015: unless ($showtext) { $showtext=&mt('show'); }
10016: unless ($hidetext) { $hidetext=&mt('hide'); }
10017: unless ($headerbg) { $headerbg='#FFFFFF'; }
10018: return &start_data_table().
10019: &start_data_table_header_row().
10020: '<td bgcolor="'.$headerbg.'">'.$heading.
10021: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
10022: $showtext.'\')">'.$showtext.'</a>]</td>'.
10023: &end_data_table_header_row().
10024: '<tr id="'.$id.'" style="display:none""><td>';
10025: }
10026:
10027: sub end_togglebox {
10028: return '</td></tr>'.&end_data_table();
10029: }
10030:
10031: sub LCprogressbar_script {
10032: my ($id,$number_to_do)=@_;
10033: if ($number_to_do) {
10034: return(<<ENDPROGRESS);
10035: <script type="text/javascript">
10036: // <![CDATA[
10037: \$('#progressbar$id').progressbar({
10038: value: 0,
10039: change: function(event, ui) {
10040: var newVal = \$(this).progressbar('option', 'value');
10041: \$('.pblabel', this).text(LCprogressTxt);
10042: }
10043: });
10044: // ]]>
10045: </script>
10046: ENDPROGRESS
10047: } else {
10048: return(<<ENDPROGRESS);
10049: <script type="text/javascript">
10050: // <![CDATA[
10051: \$('#progressbar$id').progressbar({
10052: value: false,
10053: create: function(event, ui) {
10054: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
10055: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
10056: }
10057: });
10058: // ]]>
10059: </script>
10060: ENDPROGRESS
10061: }
10062: }
10063:
10064: sub LCprogressbarUpdate_script {
10065: return(<<ENDPROGRESSUPDATE);
10066: <style type="text/css">
10067: .ui-progressbar { position:relative; }
10068: .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%; }
10069: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
10070: </style>
10071: <script type="text/javascript">
10072: // <![CDATA[
10073: var LCprogressTxt='---';
10074:
10075: function LCupdateProgress(percent,progresstext,id,maxnum) {
10076: LCprogressTxt=progresstext;
10077: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
10078: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
10079: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
10080: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
10081: } else {
10082: \$('#progressbar'+id).progressbar('value',percent);
10083: }
10084: }
10085: // ]]>
10086: </script>
10087: ENDPROGRESSUPDATE
10088: }
10089:
10090: my $LClastpercent;
10091: my $LCidcnt;
10092: my $LCcurrentid;
10093:
10094: sub LCprogressbar {
10095: my ($r,$number_to_do,$preamble)=@_;
10096: $LClastpercent=0;
10097: $LCidcnt++;
10098: $LCcurrentid=$$.'_'.$LCidcnt;
10099: my ($starting,$content);
10100: if ($number_to_do) {
10101: $starting=&mt('Starting');
10102: $content=(<<ENDPROGBAR);
10103: $preamble
10104: <div id="progressbar$LCcurrentid">
10105: <span class="pblabel">$starting</span>
10106: </div>
10107: ENDPROGBAR
10108: } else {
10109: $starting=&mt('Loading...');
10110: $LClastpercent='false';
10111: $content=(<<ENDPROGBAR);
10112: $preamble
10113: <div id="progressbar$LCcurrentid">
10114: <div class="progress-label">$starting</div>
10115: </div>
10116: ENDPROGBAR
10117: }
10118: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
10119: }
10120:
10121: sub LCprogressbarUpdate {
10122: my ($r,$val,$text,$number_to_do)=@_;
10123: if ($number_to_do) {
10124: unless ($val) {
10125: if ($LClastpercent) {
10126: $val=$LClastpercent;
10127: } else {
10128: $val=0;
10129: }
10130: }
10131: if ($val<0) { $val=0; }
10132: if ($val>100) { $val=0; }
10133: $LClastpercent=$val;
10134: unless ($text) { $text=$val.'%'; }
10135: } else {
10136: $val = 'false';
10137: }
10138: $text=&js_ready($text);
10139: &r_print($r,<<ENDUPDATE);
10140: <script type="text/javascript">
10141: // <![CDATA[
10142: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
10143: // ]]>
10144: </script>
10145: ENDUPDATE
10146: }
10147:
10148: sub LCprogressbarClose {
10149: my ($r)=@_;
10150: $LClastpercent=0;
10151: &r_print($r,<<ENDCLOSE);
10152: <script type="text/javascript">
10153: // <![CDATA[
10154: \$("#progressbar$LCcurrentid").hide('slow');
10155: // ]]>
10156: </script>
10157: ENDCLOSE
10158: }
10159:
10160: sub r_print {
10161: my ($r,$to_print)=@_;
10162: if ($r) {
10163: $r->print($to_print);
10164: $r->rflush();
10165: } else {
10166: print($to_print);
10167: }
10168: }
10169:
10170: sub html_encode {
10171: my ($result) = @_;
10172:
10173: $result = &HTML::Entities::encode($result,'<>&"');
10174:
10175: return $result;
10176: }
10177:
10178: sub js_ready {
10179: my ($result) = @_;
10180:
10181: $result =~ s/[\n\r]/ /xmsg;
10182: $result =~ s/\\/\\\\/xmsg;
10183: $result =~ s/'/\\'/xmsg;
10184: $result =~ s{</}{<\\/}xmsg;
10185:
10186: return $result;
10187: }
10188:
10189: sub validate_page {
10190: if ( exists($env{'internal.start_page'})
10191: && $env{'internal.start_page'} > 1) {
10192: &Apache::lonnet::logthis('start_page called multiple times '.
10193: $env{'internal.start_page'}.' '.
10194: $ENV{'request.filename'});
10195: }
10196: if ( exists($env{'internal.end_page'})
10197: && $env{'internal.end_page'} > 1) {
10198: &Apache::lonnet::logthis('end_page called multiple times '.
10199: $env{'internal.end_page'}.' '.
10200: $env{'request.filename'});
10201: }
10202: if ( exists($env{'internal.start_page'})
10203: && ! exists($env{'internal.end_page'})) {
10204: &Apache::lonnet::logthis('start_page called without end_page '.
10205: $env{'request.filename'});
10206: }
10207: if ( ! exists($env{'internal.start_page'})
10208: && exists($env{'internal.end_page'})) {
10209: &Apache::lonnet::logthis('end_page called without start_page'.
10210: $env{'request.filename'});
10211: }
10212: }
10213:
10214:
10215: sub start_scrollbox {
10216: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
10217: unless ($outerwidth) { $outerwidth='520px'; }
10218: unless ($width) { $width='500px'; }
10219: unless ($height) { $height='200px'; }
10220: my ($table_id,$div_id,$tdcol);
10221: if ($id ne '') {
10222: $table_id = ' id="table_'.$id.'"';
10223: $div_id = ' id="div_'.$id.'"';
10224: }
10225: if ($bgcolor ne '') {
10226: $tdcol = "background-color: $bgcolor;";
10227: }
10228: my $nicescroll_js;
10229: if ($env{'browser.mobile'}) {
10230: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
10231: }
10232: return <<"END";
10233: $nicescroll_js
10234:
10235: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
10236: <div style="overflow:auto; width:$width; height:$height;"$div_id>
10237: END
10238: }
10239:
10240: sub end_scrollbox {
10241: return '</div></td></tr></table>';
10242: }
10243:
10244: sub nicescroll_javascript {
10245: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
10246: my %options;
10247: if (ref($cursor) eq 'HASH') {
10248: %options = %{$cursor};
10249: }
10250: unless ($options{'railalign'} =~ /^left|right$/) {
10251: $options{'railalign'} = 'left';
10252: }
10253: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10254: my $function = &get_users_function();
10255: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
10256: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
10257: $options{'cursorcolor'} = '#00F';
10258: }
10259: }
10260: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
10261: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
10262: $options{'cursoropacity'}='1.0';
10263: }
10264: } else {
10265: $options{'cursoropacity'}='1.0';
10266: }
10267: if ($options{'cursorfixedheight'} eq 'none') {
10268: delete($options{'cursorfixedheight'});
10269: } else {
10270: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
10271: }
10272: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
10273: delete($options{'railoffset'});
10274: }
10275: my @niceoptions;
10276: while (my($key,$value) = each(%options)) {
10277: if ($value =~ /^\{.+\}$/) {
10278: push(@niceoptions,$key.':'.$value);
10279: } else {
10280: push(@niceoptions,$key.':"'.$value.'"');
10281: }
10282: }
10283: my $nicescroll_js = '
10284: $(document).ready(
10285: function() {
10286: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
10287: }
10288: );
10289: ';
10290: if ($framecheck) {
10291: $nicescroll_js .= '
10292: function expand_div(caller) {
10293: if (top === self) {
10294: document.getElementById("'.$id.'").style.width = "auto";
10295: document.getElementById("'.$id.'").style.height = "auto";
10296: } else {
10297: try {
10298: if (parent.frames) {
10299: if (parent.frames.length > 1) {
10300: var framesrc = parent.frames[1].location.href;
10301: var currsrc = framesrc.replace(/\#.*$/,"");
10302: if ((caller == "search") || (currsrc == "'.$location.'")) {
10303: document.getElementById("'.$id.'").style.width = "auto";
10304: document.getElementById("'.$id.'").style.height = "auto";
10305: }
10306: }
10307: }
10308: } catch (e) {
10309: return;
10310: }
10311: }
10312: return;
10313: }
10314: ';
10315: }
10316: if ($needjsready) {
10317: $nicescroll_js = '
10318: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
10319: } else {
10320: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
10321: }
10322: return $nicescroll_js;
10323: }
10324:
10325: sub simple_error_page {
10326: my ($r,$title,$msg,$args) = @_;
10327: my %displayargs;
10328: if (ref($args) eq 'HASH') {
10329: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
10330: if ($args->{'only_body'}) {
10331: $displayargs{'only_body'} = 1;
10332: }
10333: if ($args->{'no_nav_bar'}) {
10334: $displayargs{'no_nav_bar'} = 1;
10335: }
10336: } else {
10337: $msg = &mt($msg);
10338: }
10339:
10340: my $page =
10341: &Apache::loncommon::start_page($title,'',\%displayargs).
10342: '<p class="LC_error">'.$msg.'</p>'.
10343: &Apache::loncommon::end_page();
10344: if (ref($r)) {
10345: $r->print($page);
10346: return;
10347: }
10348: return $page;
10349: }
10350:
10351: {
10352: my @row_count;
10353:
10354: sub start_data_table_count {
10355: unshift(@row_count, 0);
10356: return;
10357: }
10358:
10359: sub end_data_table_count {
10360: shift(@row_count);
10361: return;
10362: }
10363:
10364: sub start_data_table {
10365: my ($add_class,$id) = @_;
10366: my $css_class = (join(' ','LC_data_table',$add_class));
10367: my $table_id;
10368: if (defined($id)) {
10369: $table_id = ' id="'.$id.'"';
10370: }
10371: &start_data_table_count();
10372: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
10373: }
10374:
10375: sub end_data_table {
10376: &end_data_table_count();
10377: return '</table>'."\n";;
10378: }
10379:
10380: sub start_data_table_row {
10381: my ($add_class, $id) = @_;
10382: $row_count[0]++;
10383: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10384: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10385: $id = (' id="'.$id.'"') unless ($id eq '');
10386: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10387: }
10388:
10389: sub continue_data_table_row {
10390: my ($add_class, $id) = @_;
10391: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
10392: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
10393: $id = (' id="'.$id.'"') unless ($id eq '');
10394: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
10395: }
10396:
10397: sub end_data_table_row {
10398: return '</tr>'."\n";;
10399: }
10400:
10401: sub start_data_table_empty_row {
10402: # $row_count[0]++;
10403: return '<tr class="LC_empty_row" >'."\n";;
10404: }
10405:
10406: sub end_data_table_empty_row {
10407: return '</tr>'."\n";;
10408: }
10409:
10410: sub start_data_table_header_row {
10411: return '<tr class="LC_header_row">'."\n";;
10412: }
10413:
10414: sub end_data_table_header_row {
10415: return '</tr>'."\n";;
10416: }
10417:
10418: sub data_table_caption {
10419: my $caption = shift;
10420: return "<caption class=\"LC_caption\">$caption</caption>";
10421: }
10422: }
10423:
10424: =pod
10425:
10426: =item * &inhibit_menu_check($arg)
10427:
10428: Checks for a inhibitmenu state and generates output to preserve it
10429:
10430: Inputs: $arg - can be any of
10431: - undef - in which case the return value is a string
10432: to add into arguments list of a uri
10433: - 'input' - in which case the return value is a HTML
10434: <form> <input> field of type hidden to
10435: preserve the value
10436: - a url - in which case the return value is the url with
10437: the neccesary cgi args added to preserve the
10438: inhibitmenu state
10439: - a ref to a url - no return value, but the string is
10440: updated to include the neccessary cgi
10441: args to preserve the inhibitmenu state
10442:
10443: =cut
10444:
10445: sub inhibit_menu_check {
10446: my ($arg) = @_;
10447: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
10448: if ($arg eq 'input') {
10449: if ($env{'form.inhibitmenu'}) {
10450: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
10451: } else {
10452: return
10453: }
10454: }
10455: if ($env{'form.inhibitmenu'}) {
10456: if (ref($arg)) {
10457: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10458: } elsif ($arg eq '') {
10459: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
10460: } else {
10461: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
10462: }
10463: }
10464: if (!ref($arg)) {
10465: return $arg;
10466: }
10467: }
10468:
10469: ###############################################
10470:
10471: =pod
10472:
10473: =back
10474:
10475: =head1 User Information Routines
10476:
10477: =over 4
10478:
10479: =item * &get_users_function()
10480:
10481: Used by &bodytag to determine the current users primary role.
10482: Returns either 'student','coordinator','admin', or 'author'.
10483:
10484: =cut
10485:
10486: ###############################################
10487: sub get_users_function {
10488: my $function = 'norole';
10489: if ($env{'request.role'}=~/^(st)/) {
10490: $function='student';
10491: }
10492: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
10493: $function='coordinator';
10494: }
10495: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
10496: $function='admin';
10497: }
10498: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
10499: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
10500: $function='author';
10501: }
10502: return $function;
10503: }
10504:
10505: ###############################################
10506:
10507: =pod
10508:
10509: =item * &show_course()
10510:
10511: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
10512: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
10513:
10514: Inputs:
10515: None
10516:
10517: Outputs:
10518: Scalar: 1 if 'Course' to be used, 0 otherwise.
10519:
10520: =cut
10521:
10522: ###############################################
10523: sub show_course {
10524: my ($udom,$uname) = @_;
10525: if (($udom ne '') && ($uname ne '')) {
10526: if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
10527: if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
10528: return 0;
10529: } else {
10530: return 1;
10531: }
10532: }
10533: }
10534: my $course = !$env{'user.adv'};
10535: if (!$env{'user.adv'}) {
10536: foreach my $env (keys(%env)) {
10537: next if ($env !~ m/^user\.priv\./);
10538: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
10539: $course = 0;
10540: last;
10541: }
10542: }
10543: }
10544: return $course;
10545: }
10546:
10547: ###############################################
10548:
10549: =pod
10550:
10551: =item * &check_user_status()
10552:
10553: Determines current status of supplied role for a
10554: specific user. Roles can be active, previous or future.
10555:
10556: Inputs:
10557: user's domain, user's username, course's domain,
10558: course's number, optional section ID.
10559:
10560: Outputs:
10561: role status: active, previous or future.
10562:
10563: =cut
10564:
10565: sub check_user_status {
10566: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
10567: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
10568: my @uroles = keys(%userinfo);
10569: my $srchstr;
10570: my $active_chk = 'none';
10571: my $now = time;
10572: if (@uroles > 0) {
10573: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
10574: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
10575: } else {
10576: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
10577: }
10578: if (grep/^\Q$srchstr\E$/,@uroles) {
10579: my $role_end = 0;
10580: my $role_start = 0;
10581: $active_chk = 'active';
10582: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
10583: $role_end = $1;
10584: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
10585: $role_start = $1;
10586: }
10587: }
10588: if ($role_start > 0) {
10589: if ($now < $role_start) {
10590: $active_chk = 'future';
10591: }
10592: }
10593: if ($role_end > 0) {
10594: if ($now > $role_end) {
10595: $active_chk = 'previous';
10596: }
10597: }
10598: }
10599: }
10600: return $active_chk;
10601: }
10602:
10603: ###############################################
10604:
10605: =pod
10606:
10607: =item * &get_sections()
10608:
10609: Determines all the sections for a course including
10610: sections with students and sections containing other roles.
10611: Incoming parameters:
10612:
10613: 1. domain
10614: 2. course number
10615: 3. reference to array containing roles for which sections should
10616: be gathered (optional).
10617: 4. reference to array containing status types for which sections
10618: should be gathered (optional).
10619:
10620: If the third argument is undefined, sections are gathered for any role.
10621: If the fourth argument is undefined, sections are gathered for any status.
10622: Permissible values are 'active' or 'future' or 'previous'.
10623:
10624: Returns section hash (keys are section IDs, values are
10625: number of users in each section), subject to the
10626: optional roles filter, optional status filter
10627:
10628: =cut
10629:
10630: ###############################################
10631: sub get_sections {
10632: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
10633: if (!defined($cdom) || !defined($cnum)) {
10634: my $cid = $env{'request.course.id'};
10635:
10636: return if (!defined($cid));
10637:
10638: $cdom = $env{'course.'.$cid.'.domain'};
10639: $cnum = $env{'course.'.$cid.'.num'};
10640: }
10641:
10642: my %sectioncount;
10643: my $now = time;
10644:
10645: my $check_students = 1;
10646: my $only_students = 0;
10647: if (ref($possible_roles) eq 'ARRAY') {
10648: if (grep(/^st$/,@{$possible_roles})) {
10649: if (@{$possible_roles} == 1) {
10650: $only_students = 1;
10651: }
10652: } else {
10653: $check_students = 0;
10654: }
10655: }
10656:
10657: if ($check_students) {
10658: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
10659: my $sec_index = &Apache::loncoursedata::CL_SECTION();
10660: my $status_index = &Apache::loncoursedata::CL_STATUS();
10661: my $start_index = &Apache::loncoursedata::CL_START();
10662: my $end_index = &Apache::loncoursedata::CL_END();
10663: my $status;
10664: while (my ($student,$data) = each(%$classlist)) {
10665: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
10666: $data->[$status_index],
10667: $data->[$start_index],
10668: $data->[$end_index]);
10669: if ($stu_status eq 'Active') {
10670: $status = 'active';
10671: } elsif ($end < $now) {
10672: $status = 'previous';
10673: } elsif ($start > $now) {
10674: $status = 'future';
10675: }
10676: if ($section ne '-1' && $section !~ /^\s*$/) {
10677: if ((!defined($possible_status)) || (($status ne '') &&
10678: (grep/^\Q$status\E$/,@{$possible_status}))) {
10679: $sectioncount{$section}++;
10680: }
10681: }
10682: }
10683: }
10684: if ($only_students) {
10685: return %sectioncount;
10686: }
10687: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10688: foreach my $user (sort(keys(%courseroles))) {
10689: if ($user !~ /^(\w{2})/) { next; }
10690: my ($role) = ($user =~ /^(\w{2})/);
10691: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
10692: my ($section,$status);
10693: if ($role eq 'cr' &&
10694: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
10695: $section=$1;
10696: }
10697: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
10698: if (!defined($section) || $section eq '-1') { next; }
10699: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
10700: if ($end == -1 && $start == -1) {
10701: next; #deleted role
10702: }
10703: if (!defined($possible_status)) {
10704: $sectioncount{$section}++;
10705: } else {
10706: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
10707: $status = 'active';
10708: } elsif ($end < $now) {
10709: $status = 'future';
10710: } elsif ($start > $now) {
10711: $status = 'previous';
10712: }
10713: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
10714: $sectioncount{$section}++;
10715: }
10716: }
10717: }
10718: return %sectioncount;
10719: }
10720:
10721: ###############################################
10722:
10723: =pod
10724:
10725: =item * &get_course_users()
10726:
10727: Retrieves usernames:domains for users in the specified course
10728: with specific role(s), and access status.
10729:
10730: Incoming parameters:
10731: 1. course domain
10732: 2. course number
10733: 3. access status: users must have - either active,
10734: previous, future, or all.
10735: 4. reference to array of permissible roles
10736: 5. reference to array of section restrictions (optional)
10737: 6. reference to results object (hash of hashes).
10738: 7. reference to optional userdata hash
10739: 8. reference to optional statushash
10740: 9. flag if privileged users (except those set to unhide in
10741: course settings) should be excluded
10742: Keys of top level results hash are roles.
10743: Keys of inner hashes are username:domain, with
10744: values set to access type.
10745: Optional userdata hash returns an array with arguments in the
10746: same order as loncoursedata::get_classlist() for student data.
10747:
10748: Optional statushash returns
10749:
10750: Entries for end, start, section and status are blank because
10751: of the possibility of multiple values for non-student roles.
10752:
10753: =cut
10754:
10755: ###############################################
10756:
10757: sub get_course_users {
10758: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10759: my %idx = ();
10760: my %seclists;
10761:
10762: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10763: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
10764: $idx{end} = &Apache::loncoursedata::CL_END();
10765: $idx{start} = &Apache::loncoursedata::CL_START();
10766: $idx{id} = &Apache::loncoursedata::CL_ID();
10767: $idx{section} = &Apache::loncoursedata::CL_SECTION();
10768: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10769: $idx{status} = &Apache::loncoursedata::CL_STATUS();
10770:
10771: if (grep(/^st$/,@{$roles})) {
10772: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10773: my $now = time;
10774: foreach my $student (keys(%{$classlist})) {
10775: my $match = 0;
10776: my $secmatch = 0;
10777: my $section = $$classlist{$student}[$idx{section}];
10778: my $status = $$classlist{$student}[$idx{status}];
10779: if ($section eq '') {
10780: $section = 'none';
10781: }
10782: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10783: if (grep(/^all$/,@{$sections})) {
10784: $secmatch = 1;
10785: } elsif ($$classlist{$student}[$idx{section}] eq '') {
10786: if (grep(/^none$/,@{$sections})) {
10787: $secmatch = 1;
10788: }
10789: } else {
10790: if (grep(/^\Q$section\E$/,@{$sections})) {
10791: $secmatch = 1;
10792: }
10793: }
10794: if (!$secmatch) {
10795: next;
10796: }
10797: }
10798: if (defined($$types{'active'})) {
10799: if ($$classlist{$student}[$idx{status}] eq 'Active') {
10800: push(@{$$users{st}{$student}},'active');
10801: $match = 1;
10802: }
10803: }
10804: if (defined($$types{'previous'})) {
10805: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10806: push(@{$$users{st}{$student}},'previous');
10807: $match = 1;
10808: }
10809: }
10810: if (defined($$types{'future'})) {
10811: if ($$classlist{$student}[$idx{status}] eq 'Future') {
10812: push(@{$$users{st}{$student}},'future');
10813: $match = 1;
10814: }
10815: }
10816: if ($match) {
10817: push(@{$seclists{$student}},$section);
10818: if (ref($userdata) eq 'HASH') {
10819: $$userdata{$student} = $$classlist{$student};
10820: }
10821: if (ref($statushash) eq 'HASH') {
10822: $statushash->{$student}{'st'}{$section} = $status;
10823: }
10824: }
10825: }
10826: }
10827: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10828: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10829: my $now = time;
10830: my %displaystatus = ( previous => 'Expired',
10831: active => 'Active',
10832: future => 'Future',
10833: );
10834: my (%nothide,@possdoms);
10835: if ($hidepriv) {
10836: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10837: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10838: if ($user !~ /:/) {
10839: $nothide{join(':',split(/[\@]/,$user))}=1;
10840: } else {
10841: $nothide{$user} = 1;
10842: }
10843: }
10844: my @possdoms = ($cdom);
10845: if ($coursehash{'checkforpriv'}) {
10846: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10847: }
10848: }
10849: foreach my $person (sort(keys(%coursepersonnel))) {
10850: my $match = 0;
10851: my $secmatch = 0;
10852: my $status;
10853: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10854: $user =~ s/:$//;
10855: my ($end,$start) = split(/:/,$coursepersonnel{$person});
10856: if ($end == -1 || $start == -1) {
10857: next;
10858: }
10859: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10860: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10861: my ($uname,$udom) = split(/:/,$user);
10862: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10863: if (grep(/^all$/,@{$sections})) {
10864: $secmatch = 1;
10865: } elsif ($usec eq '') {
10866: if (grep(/^none$/,@{$sections})) {
10867: $secmatch = 1;
10868: }
10869: } else {
10870: if (grep(/^\Q$usec\E$/,@{$sections})) {
10871: $secmatch = 1;
10872: }
10873: }
10874: if (!$secmatch) {
10875: next;
10876: }
10877: }
10878: if ($usec eq '') {
10879: $usec = 'none';
10880: }
10881: if ($uname ne '' && $udom ne '') {
10882: if ($hidepriv) {
10883: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10884: (!$nothide{$uname.':'.$udom})) {
10885: next;
10886: }
10887: }
10888: if ($end > 0 && $end < $now) {
10889: $status = 'previous';
10890: } elsif ($start > $now) {
10891: $status = 'future';
10892: } else {
10893: $status = 'active';
10894: }
10895: foreach my $type (keys(%{$types})) {
10896: if ($status eq $type) {
10897: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10898: push(@{$$users{$role}{$user}},$type);
10899: }
10900: $match = 1;
10901: }
10902: }
10903: if (($match) && (ref($userdata) eq 'HASH')) {
10904: if (!exists($$userdata{$uname.':'.$udom})) {
10905: &get_user_info($udom,$uname,\%idx,$userdata);
10906: }
10907: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10908: push(@{$seclists{$uname.':'.$udom}},$usec);
10909: }
10910: if (ref($statushash) eq 'HASH') {
10911: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10912: }
10913: }
10914: }
10915: }
10916: }
10917: if (grep(/^ow$/,@{$roles})) {
10918: if ((defined($cdom)) && (defined($cnum))) {
10919: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10920: if ( defined($csettings{'internal.courseowner'}) ) {
10921: my $owner = $csettings{'internal.courseowner'};
10922: next if ($owner eq '');
10923: my ($ownername,$ownerdom);
10924: if ($owner =~ /^([^:]+):([^:]+)$/) {
10925: $ownername = $1;
10926: $ownerdom = $2;
10927: } else {
10928: $ownername = $owner;
10929: $ownerdom = $cdom;
10930: $owner = $ownername.':'.$ownerdom;
10931: }
10932: @{$$users{'ow'}{$owner}} = 'any';
10933: if (defined($userdata) &&
10934: !exists($$userdata{$owner})) {
10935: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
10936: if (!grep(/^none$/,@{$seclists{$owner}})) {
10937: push(@{$seclists{$owner}},'none');
10938: }
10939: if (ref($statushash) eq 'HASH') {
10940: $statushash->{$owner}{'ow'}{'none'} = 'Any';
10941: }
10942: }
10943: }
10944: }
10945: }
10946: foreach my $user (keys(%seclists)) {
10947: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10948: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10949: }
10950: }
10951: return;
10952: }
10953:
10954: sub get_user_info {
10955: my ($udom,$uname,$idx,$userdata) = @_;
10956: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
10957: &plainname($uname,$udom,'lastname');
10958: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10959: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10960: my %idhash = &Apache::lonnet::idrget($udom,($uname));
10961: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
10962: return;
10963: }
10964:
10965: ###############################################
10966:
10967: =pod
10968:
10969: =item * &get_user_quota()
10970:
10971: Retrieves quota assigned for storage of user files.
10972: Default is to report quota for portfolio files.
10973:
10974: Incoming parameters:
10975: 1. user's username
10976: 2. user's domain
10977: 3. quota name - portfolio, author, or course
10978: (if no quota name provided, defaults to portfolio).
10979: 4. crstype - official, unofficial, textbook, placement or community,
10980: if quota name is course
10981:
10982: Returns:
10983: 1. Disk quota (in MB) assigned to student.
10984: 2. (Optional) Type of setting: custom or default
10985: (individually assigned or default for user's
10986: institutional status).
10987: 3. (Optional) - User's institutional status (e.g., faculty, staff
10988: or student - types as defined in localenroll::inst_usertypes
10989: for user's domain, which determines default quota for user.
10990: 4. (Optional) - Default quota which would apply to the user.
10991:
10992: If a value has been stored in the user's environment,
10993: it will return that, otherwise it returns the maximal default
10994: defined for the user's institutional status(es) in the domain.
10995:
10996: =cut
10997:
10998: ###############################################
10999:
11000:
11001: sub get_user_quota {
11002: my ($uname,$udom,$quotaname,$crstype) = @_;
11003: my ($quota,$quotatype,$settingstatus,$defquota);
11004: if (!defined($udom)) {
11005: $udom = $env{'user.domain'};
11006: }
11007: if (!defined($uname)) {
11008: $uname = $env{'user.name'};
11009: }
11010: if (($udom eq '' || $uname eq '') ||
11011: ($udom eq 'public') && ($uname eq 'public')) {
11012: $quota = 0;
11013: $quotatype = 'default';
11014: $defquota = 0;
11015: } else {
11016: my $inststatus;
11017: if ($quotaname eq 'course') {
11018: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
11019: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
11020: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
11021: } else {
11022: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
11023: $quota = $cenv{'internal.uploadquota'};
11024: }
11025: } else {
11026: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
11027: if ($quotaname eq 'author') {
11028: $quota = $env{'environment.authorquota'};
11029: } else {
11030: $quota = $env{'environment.portfolioquota'};
11031: }
11032: $inststatus = $env{'environment.inststatus'};
11033: } else {
11034: my %userenv =
11035: &Apache::lonnet::get('environment',['portfolioquota',
11036: 'authorquota','inststatus'],$udom,$uname);
11037: my ($tmp) = keys(%userenv);
11038: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11039: if ($quotaname eq 'author') {
11040: $quota = $userenv{'authorquota'};
11041: } else {
11042: $quota = $userenv{'portfolioquota'};
11043: }
11044: $inststatus = $userenv{'inststatus'};
11045: } else {
11046: undef(%userenv);
11047: }
11048: }
11049: }
11050: if ($quota eq '' || wantarray) {
11051: if ($quotaname eq 'course') {
11052: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
11053: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
11054: ($crstype eq 'community') || ($crstype eq 'textbook') ||
11055: ($crstype eq 'placement')) {
11056: $defquota = $domdefs{$crstype.'quota'};
11057: }
11058: if ($defquota eq '') {
11059: $defquota = 500;
11060: }
11061: } else {
11062: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
11063: }
11064: if ($quota eq '') {
11065: $quota = $defquota;
11066: $quotatype = 'default';
11067: } else {
11068: $quotatype = 'custom';
11069: }
11070: }
11071: }
11072: if (wantarray) {
11073: return ($quota,$quotatype,$settingstatus,$defquota);
11074: } else {
11075: return $quota;
11076: }
11077: }
11078:
11079: ###############################################
11080:
11081: =pod
11082:
11083: =item * &default_quota()
11084:
11085: Retrieves default quota assigned for storage of user portfolio files,
11086: given an (optional) user's institutional status.
11087:
11088: Incoming parameters:
11089:
11090: 1. domain
11091: 2. (Optional) institutional status(es). This is a : separated list of
11092: status types (e.g., faculty, staff, student etc.)
11093: which apply to the user for whom the default is being retrieved.
11094: If the institutional status string in undefined, the domain
11095: default quota will be returned.
11096: 3. quota name - portfolio, author, or course
11097: (if no quota name provided, defaults to portfolio).
11098:
11099: Returns:
11100:
11101: 1. Default disk quota (in MB) for user portfolios in the domain.
11102: 2. (Optional) institutional type which determined the value of the
11103: default quota.
11104:
11105: If a value has been stored in the domain's configuration db,
11106: it will return that, otherwise it returns 20 (for backwards
11107: compatibility with domains which have not set up a configuration
11108: db file; the original statically defined portfolio quota was 20 MB).
11109:
11110: If the user's status includes multiple types (e.g., staff and student),
11111: the largest default quota which applies to the user determines the
11112: default quota returned.
11113:
11114: =cut
11115:
11116: ###############################################
11117:
11118:
11119: sub default_quota {
11120: my ($udom,$inststatus,$quotaname) = @_;
11121: my ($defquota,$settingstatus);
11122: my %quotahash = &Apache::lonnet::get_dom('configuration',
11123: ['quotas'],$udom);
11124: my $key = 'defaultquota';
11125: if ($quotaname eq 'author') {
11126: $key = 'authorquota';
11127: }
11128: if (ref($quotahash{'quotas'}) eq 'HASH') {
11129: if ($inststatus ne '') {
11130: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
11131: foreach my $item (@statuses) {
11132: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11133: if ($quotahash{'quotas'}{$key}{$item} ne '') {
11134: if ($defquota eq '') {
11135: $defquota = $quotahash{'quotas'}{$key}{$item};
11136: $settingstatus = $item;
11137: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
11138: $defquota = $quotahash{'quotas'}{$key}{$item};
11139: $settingstatus = $item;
11140: }
11141: }
11142: } elsif ($key eq 'defaultquota') {
11143: if ($quotahash{'quotas'}{$item} ne '') {
11144: if ($defquota eq '') {
11145: $defquota = $quotahash{'quotas'}{$item};
11146: $settingstatus = $item;
11147: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
11148: $defquota = $quotahash{'quotas'}{$item};
11149: $settingstatus = $item;
11150: }
11151: }
11152: }
11153: }
11154: }
11155: if ($defquota eq '') {
11156: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
11157: $defquota = $quotahash{'quotas'}{$key}{'default'};
11158: } elsif ($key eq 'defaultquota') {
11159: $defquota = $quotahash{'quotas'}{'default'};
11160: }
11161: $settingstatus = 'default';
11162: if ($defquota eq '') {
11163: if ($quotaname eq 'author') {
11164: $defquota = 500;
11165: }
11166: }
11167: }
11168: } else {
11169: $settingstatus = 'default';
11170: if ($quotaname eq 'author') {
11171: $defquota = 500;
11172: } else {
11173: $defquota = 20;
11174: }
11175: }
11176: if (wantarray) {
11177: return ($defquota,$settingstatus);
11178: } else {
11179: return $defquota;
11180: }
11181: }
11182:
11183: ###############################################
11184:
11185: =pod
11186:
11187: =item * &excess_filesize_warning()
11188:
11189: Returns warning message if upload of file to authoring space, or copying
11190: of existing file within authoring space will cause quota for the authoring
11191: space to be exceeded.
11192:
11193: Same, if upload of a file directly to a course/community via Course Editor
11194: will cause quota for uploaded content for the course to be exceeded.
11195:
11196: Inputs: 7
11197: 1. username or coursenum
11198: 2. domain
11199: 3. context ('author' or 'course')
11200: 4. filename of file for which action is being requested
11201: 5. filesize (kB) of file
11202: 6. action being taken: copy or upload.
11203: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
11204:
11205: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
11206: otherwise return null.
11207:
11208: =back
11209:
11210: =cut
11211:
11212: sub excess_filesize_warning {
11213: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
11214: my $current_disk_usage = 0;
11215: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
11216: if ($context eq 'author') {
11217: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
11218: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
11219: } else {
11220: foreach my $subdir ('docs','supplemental') {
11221: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
11222: }
11223: }
11224: $disk_quota = int($disk_quota * 1000);
11225: if (($current_disk_usage + $filesize) > $disk_quota) {
11226: return '<p class="LC_warning">'.
11227: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
11228: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
11229: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11230: $disk_quota,$current_disk_usage).
11231: '</p>';
11232: }
11233: return;
11234: }
11235:
11236: ###############################################
11237:
11238:
11239:
11240:
11241: sub get_secgrprole_info {
11242: my ($cdom,$cnum,$needroles,$type) = @_;
11243: my %sections_count = &get_sections($cdom,$cnum);
11244: my @sections = (sort {$a <=> $b} keys(%sections_count));
11245: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
11246: my @groups = sort(keys(%curr_groups));
11247: my $allroles = [];
11248: my $rolehash;
11249: my $accesshash = {
11250: active => 'Currently has access',
11251: future => 'Will have future access',
11252: previous => 'Previously had access',
11253: };
11254: if ($needroles) {
11255: $rolehash = {'all' => 'all'};
11256: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
11257: if (&Apache::lonnet::error(%user_roles)) {
11258: undef(%user_roles);
11259: }
11260: foreach my $item (keys(%user_roles)) {
11261: my ($role)=split(/\:/,$item,2);
11262: if ($role eq 'cr') { next; }
11263: if ($role =~ /^cr/) {
11264: $$rolehash{$role} = (split('/',$role))[3];
11265: } else {
11266: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
11267: }
11268: }
11269: foreach my $key (sort(keys(%{$rolehash}))) {
11270: push(@{$allroles},$key);
11271: }
11272: push (@{$allroles},'st');
11273: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
11274: }
11275: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
11276: }
11277:
11278: sub user_picker {
11279: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
11280: my $currdom = $dom;
11281: my @alldoms = &Apache::lonnet::all_domains();
11282: if (@alldoms == 1) {
11283: my %domsrch = &Apache::lonnet::get_dom('configuration',
11284: ['directorysrch'],$alldoms[0]);
11285: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
11286: my $showdom = $domdesc;
11287: if ($showdom eq '') {
11288: $showdom = $dom;
11289: }
11290: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
11291: if ((!$domsrch{'directorysrch'}{'available'}) &&
11292: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
11293: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
11294: }
11295: }
11296: }
11297: my %curr_selected = (
11298: srchin => 'dom',
11299: srchby => 'lastname',
11300: );
11301: my $srchterm;
11302: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
11303: if ($srch->{'srchby'} ne '') {
11304: $curr_selected{'srchby'} = $srch->{'srchby'};
11305: }
11306: if ($srch->{'srchin'} ne '') {
11307: $curr_selected{'srchin'} = $srch->{'srchin'};
11308: }
11309: if ($srch->{'srchtype'} ne '') {
11310: $curr_selected{'srchtype'} = $srch->{'srchtype'};
11311: }
11312: if ($srch->{'srchdomain'} ne '') {
11313: $currdom = $srch->{'srchdomain'};
11314: }
11315: $srchterm = $srch->{'srchterm'};
11316: }
11317: my %html_lt=&Apache::lonlocal::texthash(
11318: 'usr' => 'Search criteria',
11319: 'doma' => 'Domain/institution to search',
11320: 'uname' => 'username',
11321: 'lastname' => 'last name',
11322: 'lastfirst' => 'last name, first name',
11323: 'crs' => 'in this course',
11324: 'dom' => 'in selected LON-CAPA domain',
11325: 'alc' => 'all LON-CAPA',
11326: 'instd' => 'in institutional directory for selected domain',
11327: 'exact' => 'is',
11328: 'contains' => 'contains',
11329: 'begins' => 'begins with',
11330: );
11331: my %js_lt=&Apache::lonlocal::texthash(
11332: 'youm' => "You must include some text to search for.",
11333: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
11334: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
11335: 'yomc' => "You must choose a domain when using an institutional directory search.",
11336: 'ymcd' => "You must choose a domain when using a domain search.",
11337: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
11338: 'whse' => "When searching by last,first you must include at least one character in the first name.",
11339: 'thfo' => "The following need to be corrected before the search can be run:",
11340: );
11341: &html_escape(\%html_lt);
11342: &js_escape(\%js_lt);
11343: my $domform;
11344: my $allow_blank = 1;
11345: if ($fixeddom) {
11346: $allow_blank = 0;
11347: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
11348: } else {
11349: my $defdom = $env{'request.role.domain'};
11350: my ($trusted,$untrusted);
11351: if (($context eq 'requestcrs') || ($context eq 'course')) {
11352: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
11353: } elsif ($context eq 'author') {
11354: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
11355: } elsif ($context eq 'domain') {
11356: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
11357: }
11358: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
11359: }
11360: my $srchinsel = ' <select name="srchin">';
11361:
11362: my @srchins = ('crs','dom','alc','instd');
11363:
11364: foreach my $option (@srchins) {
11365: # FIXME 'alc' option unavailable until
11366: # loncreateuser::print_user_query_page()
11367: # has been completed.
11368: next if ($option eq 'alc');
11369: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
11370: next if ($option eq 'crs' && !$env{'request.course.id'});
11371: next if (($option eq 'instd') && ($noinstd));
11372: if ($curr_selected{'srchin'} eq $option) {
11373: $srchinsel .= '
11374: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11375: } else {
11376: $srchinsel .= '
11377: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11378: }
11379: }
11380: $srchinsel .= "\n </select>\n";
11381:
11382: my $srchbysel = ' <select name="srchby">';
11383: foreach my $option ('lastname','lastfirst','uname') {
11384: if ($curr_selected{'srchby'} eq $option) {
11385: $srchbysel .= '
11386: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11387: } else {
11388: $srchbysel .= '
11389: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11390: }
11391: }
11392: $srchbysel .= "\n </select>\n";
11393:
11394: my $srchtypesel = ' <select name="srchtype">';
11395: foreach my $option ('begins','contains','exact') {
11396: if ($curr_selected{'srchtype'} eq $option) {
11397: $srchtypesel .= '
11398: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
11399: } else {
11400: $srchtypesel .= '
11401: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
11402: }
11403: }
11404: $srchtypesel .= "\n </select>\n";
11405:
11406: my ($newuserscript,$new_user_create);
11407: my $context_dom = $env{'request.role.domain'};
11408: if ($context eq 'requestcrs') {
11409: if ($env{'form.coursedom'} ne '') {
11410: $context_dom = $env{'form.coursedom'};
11411: }
11412: }
11413: if ($forcenewuser) {
11414: if (ref($srch) eq 'HASH') {
11415: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
11416: if ($cancreate) {
11417: $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>';
11418: } else {
11419: my $helplink = 'javascript:helpMenu('."'display'".')';
11420: my %usertypetext = (
11421: official => 'institutional',
11422: unofficial => 'non-institutional',
11423: );
11424: $new_user_create = '<p class="LC_warning">'
11425: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
11426: .' '
11427: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
11428: ,'<a href="'.$helplink.'">','</a>')
11429: .'</p><br />';
11430: }
11431: }
11432: }
11433:
11434: $newuserscript = <<"ENDSCRIPT";
11435:
11436: function setSearch(createnew,callingForm) {
11437: if (createnew == 1) {
11438: for (var i=0; i<callingForm.srchby.length; i++) {
11439: if (callingForm.srchby.options[i].value == 'uname') {
11440: callingForm.srchby.selectedIndex = i;
11441: }
11442: }
11443: for (var i=0; i<callingForm.srchin.length; i++) {
11444: if ( callingForm.srchin.options[i].value == 'dom') {
11445: callingForm.srchin.selectedIndex = i;
11446: }
11447: }
11448: for (var i=0; i<callingForm.srchtype.length; i++) {
11449: if (callingForm.srchtype.options[i].value == 'exact') {
11450: callingForm.srchtype.selectedIndex = i;
11451: }
11452: }
11453: for (var i=0; i<callingForm.srchdomain.length; i++) {
11454: if (callingForm.srchdomain.options[i].value == '$context_dom') {
11455: callingForm.srchdomain.selectedIndex = i;
11456: }
11457: }
11458: }
11459: }
11460: ENDSCRIPT
11461:
11462: }
11463:
11464: my $output = <<"END_BLOCK";
11465: <script type="text/javascript">
11466: // <![CDATA[
11467: function validateEntry(callingForm) {
11468:
11469: var checkok = 1;
11470: var srchin;
11471: for (var i=0; i<callingForm.srchin.length; i++) {
11472: if ( callingForm.srchin[i].checked ) {
11473: srchin = callingForm.srchin[i].value;
11474: }
11475: }
11476:
11477: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
11478: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
11479: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
11480: var srchterm = callingForm.srchterm.value;
11481: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
11482: var msg = "";
11483:
11484: if (srchterm == "") {
11485: checkok = 0;
11486: msg += "$js_lt{'youm'}\\n";
11487: }
11488:
11489: if (srchtype== 'begins') {
11490: if (srchterm.length < 2) {
11491: checkok = 0;
11492: msg += "$js_lt{'thte'}\\n";
11493: }
11494: }
11495:
11496: if (srchtype== 'contains') {
11497: if (srchterm.length < 3) {
11498: checkok = 0;
11499: msg += "$js_lt{'thet'}\\n";
11500: }
11501: }
11502: if (srchin == 'instd') {
11503: if (srchdomain == '') {
11504: checkok = 0;
11505: msg += "$js_lt{'yomc'}\\n";
11506: }
11507: }
11508: if (srchin == 'dom') {
11509: if (srchdomain == '') {
11510: checkok = 0;
11511: msg += "$js_lt{'ymcd'}\\n";
11512: }
11513: }
11514: if (srchby == 'lastfirst') {
11515: if (srchterm.indexOf(",") == -1) {
11516: checkok = 0;
11517: msg += "$js_lt{'whus'}\\n";
11518: }
11519: if (srchterm.indexOf(",") == srchterm.length -1) {
11520: checkok = 0;
11521: msg += "$js_lt{'whse'}\\n";
11522: }
11523: }
11524: if (checkok == 0) {
11525: alert("$js_lt{'thfo'}\\n"+msg);
11526: return;
11527: }
11528: if (checkok == 1) {
11529: callingForm.submit();
11530: }
11531: }
11532:
11533: $newuserscript
11534:
11535: // ]]>
11536: </script>
11537:
11538: $new_user_create
11539:
11540: END_BLOCK
11541:
11542: $output .= &Apache::lonhtmlcommon::start_pick_box().
11543: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
11544: $domform.
11545: &Apache::lonhtmlcommon::row_closure().
11546: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
11547: $srchbysel.
11548: $srchtypesel.
11549: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
11550: $srchinsel.
11551: &Apache::lonhtmlcommon::row_closure(1).
11552: &Apache::lonhtmlcommon::end_pick_box().
11553: '<br />';
11554: return ($output,1);
11555: }
11556:
11557: sub user_rule_check {
11558: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
11559: my ($response,%inst_response);
11560: if (ref($usershash) eq 'HASH') {
11561: if (keys(%{$usershash}) > 1) {
11562: my (%by_username,%by_id,%userdoms);
11563: my $checkid;
11564: if (ref($checks) eq 'HASH') {
11565: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
11566: $checkid = 1;
11567: }
11568: }
11569: foreach my $user (keys(%{$usershash})) {
11570: my ($uname,$udom) = split(/:/,$user);
11571: if ($checkid) {
11572: if (ref($usershash->{$user}) eq 'HASH') {
11573: if ($usershash->{$user}->{'id'} ne '') {
11574: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
11575: $userdoms{$udom} = 1;
11576: if (ref($inst_results) eq 'HASH') {
11577: $inst_results->{$uname.':'.$udom} = {};
11578: }
11579: }
11580: }
11581: } else {
11582: $by_username{$udom}{$uname} = 1;
11583: $userdoms{$udom} = 1;
11584: if (ref($inst_results) eq 'HASH') {
11585: $inst_results->{$uname.':'.$udom} = {};
11586: }
11587: }
11588: }
11589: foreach my $udom (keys(%userdoms)) {
11590: if (!$got_rules->{$udom}) {
11591: my %domconfig = &Apache::lonnet::get_dom('configuration',
11592: ['usercreation'],$udom);
11593: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11594: foreach my $item ('username','id') {
11595: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11596: $$curr_rules{$udom}{$item} =
11597: $domconfig{'usercreation'}{$item.'_rule'};
11598: }
11599: }
11600: }
11601: $got_rules->{$udom} = 1;
11602: }
11603: }
11604: if ($checkid) {
11605: foreach my $udom (keys(%by_id)) {
11606: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
11607: if ($outcome eq 'ok') {
11608: foreach my $id (keys(%{$by_id{$udom}})) {
11609: my $uname = $by_id{$udom}{$id};
11610: $inst_response{$uname.':'.$udom} = $outcome;
11611: }
11612: if (ref($results) eq 'HASH') {
11613: foreach my $uname (keys(%{$results})) {
11614: if (exists($inst_response{$uname.':'.$udom})) {
11615: $inst_response{$uname.':'.$udom} = $outcome;
11616: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11617: }
11618: }
11619: }
11620: }
11621: }
11622: } else {
11623: foreach my $udom (keys(%by_username)) {
11624: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
11625: if ($outcome eq 'ok') {
11626: foreach my $uname (keys(%{$by_username{$udom}})) {
11627: $inst_response{$uname.':'.$udom} = $outcome;
11628: }
11629: if (ref($results) eq 'HASH') {
11630: foreach my $uname (keys(%{$results})) {
11631: $inst_results->{$uname.':'.$udom} = $results->{$uname};
11632: }
11633: }
11634: }
11635: }
11636: }
11637: } elsif (keys(%{$usershash}) == 1) {
11638: my $user = (keys(%{$usershash}))[0];
11639: my ($uname,$udom) = split(/:/,$user);
11640: if (($udom ne '') && ($uname ne '')) {
11641: if (ref($usershash->{$user}) eq 'HASH') {
11642: if (ref($checks) eq 'HASH') {
11643: if (defined($checks->{'username'})) {
11644: ($inst_response{$user},%{$inst_results->{$user}}) =
11645: &Apache::lonnet::get_instuser($udom,$uname);
11646: } elsif (defined($checks->{'id'})) {
11647: if ($usershash->{$user}->{'id'} ne '') {
11648: ($inst_response{$user},%{$inst_results->{$user}}) =
11649: &Apache::lonnet::get_instuser($udom,undef,
11650: $usershash->{$user}->{'id'});
11651: } else {
11652: ($inst_response{$user},%{$inst_results->{$user}}) =
11653: &Apache::lonnet::get_instuser($udom,$uname);
11654: }
11655: }
11656: } else {
11657: ($inst_response{$user},%{$inst_results->{$user}}) =
11658: &Apache::lonnet::get_instuser($udom,$uname);
11659: return;
11660: }
11661: if (!$got_rules->{$udom}) {
11662: my %domconfig = &Apache::lonnet::get_dom('configuration',
11663: ['usercreation'],$udom);
11664: if (ref($domconfig{'usercreation'}) eq 'HASH') {
11665: foreach my $item ('username','id') {
11666: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
11667: $$curr_rules{$udom}{$item} =
11668: $domconfig{'usercreation'}{$item.'_rule'};
11669: }
11670: }
11671: }
11672: $got_rules->{$udom} = 1;
11673: }
11674: }
11675: } else {
11676: return;
11677: }
11678: } else {
11679: return;
11680: }
11681: foreach my $user (keys(%{$usershash})) {
11682: my ($uname,$udom) = split(/:/,$user);
11683: next if (($udom eq '') || ($uname eq ''));
11684: my $id;
11685: if (ref($inst_results) eq 'HASH') {
11686: if (ref($inst_results->{$user}) eq 'HASH') {
11687: $id = $inst_results->{$user}->{'id'};
11688: }
11689: }
11690: if ($id eq '') {
11691: if (ref($usershash->{$user})) {
11692: $id = $usershash->{$user}->{'id'};
11693: }
11694: }
11695: foreach my $item (keys(%{$checks})) {
11696: if (ref($$curr_rules{$udom}) eq 'HASH') {
11697: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
11698: if (@{$$curr_rules{$udom}{$item}} > 0) {
11699: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
11700: $$curr_rules{$udom}{$item});
11701: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
11702: if ($rule_check{$rule}) {
11703: $$rulematch{$user}{$item} = $rule;
11704: if ($inst_response{$user} eq 'ok') {
11705: if (ref($inst_results) eq 'HASH') {
11706: if (ref($inst_results->{$user}) eq 'HASH') {
11707: if (keys(%{$inst_results->{$user}}) == 0) {
11708: $$alerts{$item}{$udom}{$uname} = 1;
11709: } elsif ($item eq 'id') {
11710: if ($inst_results->{$user}->{'id'} eq '') {
11711: $$alerts{$item}{$udom}{$uname} = 1;
11712: }
11713: }
11714: }
11715: }
11716: }
11717: last;
11718: }
11719: }
11720: }
11721: }
11722: }
11723: }
11724: }
11725: }
11726: return;
11727: }
11728:
11729: sub user_rule_formats {
11730: my ($domain,$domdesc,$curr_rules,$check) = @_;
11731: my %text = (
11732: 'username' => 'Usernames',
11733: 'id' => 'IDs',
11734: );
11735: my $output;
11736: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
11737: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
11738: if (@{$ruleorder} > 0) {
11739: $output = '<br />'.
11740: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
11741: '<span class="LC_cusr_emph">','</span>',$domdesc).
11742: ' <ul>';
11743: foreach my $rule (@{$ruleorder}) {
11744: if (ref($curr_rules) eq 'ARRAY') {
11745: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11746: if (ref($rules->{$rule}) eq 'HASH') {
11747: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11748: $rules->{$rule}{'desc'}.'</li>';
11749: }
11750: }
11751: }
11752: }
11753: $output .= '</ul>';
11754: }
11755: }
11756: return $output;
11757: }
11758:
11759: sub instrule_disallow_msg {
11760: my ($checkitem,$domdesc,$count,$mode) = @_;
11761: my $response;
11762: my %text = (
11763: item => 'username',
11764: items => 'usernames',
11765: match => 'matches',
11766: do => 'does',
11767: action => 'a username',
11768: one => 'one',
11769: );
11770: if ($count > 1) {
11771: $text{'item'} = 'usernames';
11772: $text{'match'} ='match';
11773: $text{'do'} = 'do';
11774: $text{'action'} = 'usernames',
11775: $text{'one'} = 'ones';
11776: }
11777: if ($checkitem eq 'id') {
11778: $text{'items'} = 'IDs';
11779: $text{'item'} = 'ID';
11780: $text{'action'} = 'an ID';
11781: if ($count > 1) {
11782: $text{'item'} = 'IDs';
11783: $text{'action'} = 'IDs';
11784: }
11785: }
11786: $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 />';
11787: if ($mode eq 'upload') {
11788: if ($checkitem eq 'username') {
11789: $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'}.");
11790: } elsif ($checkitem eq 'id') {
11791: $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.");
11792: }
11793: } elsif ($mode eq 'selfcreate') {
11794: if ($checkitem eq 'id') {
11795: $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.");
11796: }
11797: } else {
11798: if ($checkitem eq 'username') {
11799: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11800: } elsif ($checkitem eq 'id') {
11801: $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.");
11802: }
11803: }
11804: return $response;
11805: }
11806:
11807: sub personal_data_fieldtitles {
11808: my %fieldtitles = &Apache::lonlocal::texthash (
11809: id => 'Student/Employee ID',
11810: permanentemail => 'E-mail address',
11811: lastname => 'Last Name',
11812: firstname => 'First Name',
11813: middlename => 'Middle Name',
11814: generation => 'Generation',
11815: gen => 'Generation',
11816: inststatus => 'Affiliation',
11817: );
11818: return %fieldtitles;
11819: }
11820:
11821: sub sorted_inst_types {
11822: my ($dom) = @_;
11823: my ($usertypes,$order);
11824: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11825: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11826: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11827: $order = $domdefaults{'inststatus'}{'inststatusorder'};
11828: } else {
11829: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11830: }
11831: my $othertitle = &mt('All users');
11832: if ($env{'request.course.id'}) {
11833: $othertitle = &mt('Any users');
11834: }
11835: my @types;
11836: if (ref($order) eq 'ARRAY') {
11837: @types = @{$order};
11838: }
11839: if (@types == 0) {
11840: if (ref($usertypes) eq 'HASH') {
11841: @types = sort(keys(%{$usertypes}));
11842: }
11843: }
11844: if (keys(%{$usertypes}) > 0) {
11845: $othertitle = &mt('Other users');
11846: }
11847: return ($othertitle,$usertypes,\@types);
11848: }
11849:
11850: sub get_institutional_codes {
11851: my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11852: # Get complete list of course sections to update
11853: my @currsections = ();
11854: my @currxlists = ();
11855: my (%unclutteredsec,%unclutteredlcsec);
11856: my $coursecode = $$settings{'internal.coursecode'};
11857: my $crskey = $crs.':'.$coursecode;
11858: @{$unclutteredsec{$crskey}} = ();
11859: @{$unclutteredlcsec{$crskey}} = ();
11860:
11861: if ($$settings{'internal.sectionnums'} ne '') {
11862: @currsections = split(/,/,$$settings{'internal.sectionnums'});
11863: }
11864:
11865: if ($$settings{'internal.crosslistings'} ne '') {
11866: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11867: }
11868:
11869: if (@currxlists > 0) {
11870: foreach my $xl (@currxlists) {
11871: if ($xl =~ /^([^:]+):(\w*)$/) {
11872: unless (grep/^$1$/,@{$allcourses}) {
11873: push(@{$allcourses},$1);
11874: $$LC_code{$1} = $2;
11875: }
11876: }
11877: }
11878: }
11879:
11880: if (@currsections > 0) {
11881: foreach my $sec (@currsections) {
11882: if ($sec =~ m/^(\w+):(\w*)$/ ) {
11883: my $instsec = $1;
11884: my $lc_sec = $2;
11885: unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11886: push(@{$unclutteredsec{$crskey}},$instsec);
11887: push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11888: }
11889: }
11890: }
11891: }
11892:
11893: if (@{$unclutteredsec{$crskey}} > 0) {
11894: my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11895: if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11896: for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11897: my $sec = $coursecode.$formattedsec{$crskey}[$i];
11898: unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11899: push(@{$allcourses},$sec);
11900: $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11901: }
11902: }
11903: }
11904: }
11905: return;
11906: }
11907:
11908: sub get_standard_codeitems {
11909: return ('Year','Semester','Department','Number','Section');
11910: }
11911:
11912: =pod
11913:
11914: =head1 Slot Helpers
11915:
11916: =over 4
11917:
11918: =item * sorted_slots()
11919:
11920: Sorts an array of slot names in order of an optional sort key,
11921: default sort is by slot start time (earliest first).
11922:
11923: Inputs:
11924:
11925: =over 4
11926:
11927: slotsarr - Reference to array of unsorted slot names.
11928:
11929: slots - Reference to hash of hash, where outer hash keys are slot names.
11930:
11931: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
11932:
11933: =back
11934:
11935: Returns:
11936:
11937: =over 4
11938:
11939: sorted - An array of slot names sorted by a specified sort key
11940: (default sort key is start time of the slot).
11941:
11942: =back
11943:
11944: =cut
11945:
11946:
11947: sub sorted_slots {
11948: my ($slotsarr,$slots,$sortkey) = @_;
11949: if ($sortkey eq '') {
11950: $sortkey = 'starttime';
11951: }
11952: my @sorted;
11953: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11954: @sorted =
11955: sort {
11956: if (ref($slots->{$a}) && ref($slots->{$b})) {
11957: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11958: }
11959: if (ref($slots->{$a})) { return -1;}
11960: if (ref($slots->{$b})) { return 1;}
11961: return 0;
11962: } @{$slotsarr};
11963: }
11964: return @sorted;
11965: }
11966:
11967: =pod
11968:
11969: =item * get_future_slots()
11970:
11971: Inputs:
11972:
11973: =over 4
11974:
11975: cnum - course number
11976:
11977: cdom - course domain
11978:
11979: now - current UNIX time
11980:
11981: symb - optional symb
11982:
11983: =back
11984:
11985: Returns:
11986:
11987: =over 4
11988:
11989: sorted_reservable - ref to array of student_schedulable slots currently
11990: reservable, ordered by end date of reservation period.
11991:
11992: reservable_now - ref to hash of student_schedulable slots currently
11993: reservable.
11994:
11995: Keys in inner hash are:
11996: (a) symb: either blank or symb to which slot use is restricted.
11997: (b) endreserve: end date of reservation period.
11998: (c) uniqueperiod: start,end dates when slot is to be uniquely
11999: selected.
12000:
12001: sorted_future - ref to array of student_schedulable slots reservable in
12002: the future, ordered by start date of reservation period.
12003:
12004: future_reservable - ref to hash of student_schedulable slots reservable
12005: in the future.
12006:
12007: Keys in inner hash are:
12008: (a) symb: either blank or symb to which slot use is restricted.
12009: (b) startreserve: start date of reservation period.
12010: (c) uniqueperiod: start,end dates when slot is to be uniquely
12011: selected.
12012:
12013: =back
12014:
12015: =cut
12016:
12017: sub get_future_slots {
12018: my ($cnum,$cdom,$now,$symb) = @_;
12019: my $map;
12020: if ($symb) {
12021: ($map) = &Apache::lonnet::decode_symb($symb);
12022: }
12023: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
12024: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
12025: foreach my $slot (keys(%slots)) {
12026: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
12027: if ($symb) {
12028: if ($slots{$slot}->{'symb'} ne '') {
12029: my $canuse;
12030: my %oksymbs;
12031: my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
12032: map { $oksymbs{$_} = 1; } @slotsymbs;
12033: if ($oksymbs{$symb}) {
12034: $canuse = 1;
12035: } else {
12036: foreach my $item (@slotsymbs) {
12037: if ($item =~ /\.(page|sequence)$/) {
12038: (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
12039: if (($map ne '') && ($map eq $sloturl)) {
12040: $canuse = 1;
12041: last;
12042: }
12043: }
12044: }
12045: }
12046: next unless ($canuse);
12047: }
12048: }
12049: if (($slots{$slot}->{'starttime'} > $now) &&
12050: ($slots{$slot}->{'endtime'} > $now)) {
12051: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
12052: my $userallowed = 0;
12053: if ($slots{$slot}->{'allowedsections'}) {
12054: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
12055: if (!defined($env{'request.role.sec'})
12056: && grep(/^No section assigned$/,@allowed_sec)) {
12057: $userallowed=1;
12058: } else {
12059: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
12060: $userallowed=1;
12061: }
12062: }
12063: unless ($userallowed) {
12064: if (defined($env{'request.course.groups'})) {
12065: my @groups = split(/:/,$env{'request.course.groups'});
12066: foreach my $group (@groups) {
12067: if (grep(/^\Q$group\E$/,@allowed_sec)) {
12068: $userallowed=1;
12069: last;
12070: }
12071: }
12072: }
12073: }
12074: }
12075: if ($slots{$slot}->{'allowedusers'}) {
12076: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
12077: my $user = $env{'user.name'}.':'.$env{'user.domain'};
12078: if (grep(/^\Q$user\E$/,@allowed_users)) {
12079: $userallowed = 1;
12080: }
12081: }
12082: next unless($userallowed);
12083: }
12084: my $startreserve = $slots{$slot}->{'startreserve'};
12085: my $endreserve = $slots{$slot}->{'endreserve'};
12086: my $symb = $slots{$slot}->{'symb'};
12087: my $uniqueperiod;
12088: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
12089: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
12090: }
12091: if (($startreserve < $now) &&
12092: (!$endreserve || $endreserve > $now)) {
12093: my $lastres = $endreserve;
12094: if (!$lastres) {
12095: $lastres = $slots{$slot}->{'starttime'};
12096: }
12097: $reservable_now{$slot} = {
12098: symb => $symb,
12099: endreserve => $lastres,
12100: uniqueperiod => $uniqueperiod,
12101: };
12102: } elsif (($startreserve > $now) &&
12103: (!$endreserve || $endreserve > $startreserve)) {
12104: $future_reservable{$slot} = {
12105: symb => $symb,
12106: startreserve => $startreserve,
12107: uniqueperiod => $uniqueperiod,
12108: };
12109: }
12110: }
12111: }
12112: my @unsorted_reservable = keys(%reservable_now);
12113: if (@unsorted_reservable > 0) {
12114: @sorted_reservable =
12115: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
12116: }
12117: my @unsorted_future = keys(%future_reservable);
12118: if (@unsorted_future > 0) {
12119: @sorted_future =
12120: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
12121: }
12122: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
12123: }
12124:
12125: =pod
12126:
12127: =back
12128:
12129: =head1 HTTP Helpers
12130:
12131: =over 4
12132:
12133: =item * &get_unprocessed_cgi($query,$possible_names)
12134:
12135: Modify the %env hash to contain unprocessed CGI form parameters held in
12136: $query. The parameters listed in $possible_names (an array reference),
12137: will be set in $env{'form.name'} if they do not already exist.
12138:
12139: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
12140: $possible_names is an ref to an array of form element names. As an example:
12141: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
12142: will result in $env{'form.uname'} and $env{'form.udom'} being set.
12143:
12144: =cut
12145:
12146: sub get_unprocessed_cgi {
12147: my ($query,$possible_names)= @_;
12148: # $Apache::lonxml::debug=1;
12149: foreach my $pair (split(/&/,$query)) {
12150: my ($name, $value) = split(/=/,$pair);
12151: $name = &unescape($name);
12152: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
12153: $value =~ tr/+/ /;
12154: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
12155: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
12156: }
12157: }
12158: }
12159:
12160: =pod
12161:
12162: =item * &cacheheader()
12163:
12164: returns cache-controlling header code
12165:
12166: =cut
12167:
12168: sub cacheheader {
12169: unless ($env{'request.method'} eq 'GET') { return ''; }
12170: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
12171: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
12172: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
12173: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
12174: return $output;
12175: }
12176:
12177: =pod
12178:
12179: =item * &no_cache($r)
12180:
12181: specifies header code to not have cache
12182:
12183: =cut
12184:
12185: sub no_cache {
12186: my ($r) = @_;
12187: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
12188: $env{'request.method'} ne 'GET') { return ''; }
12189: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
12190: $r->no_cache(1);
12191: $r->header_out("Expires" => $date);
12192: $r->header_out("Pragma" => "no-cache");
12193: }
12194:
12195: sub content_type {
12196: my ($r,$type,$charset) = @_;
12197: if ($r) {
12198: # Note that printout.pl calls this with undef for $r.
12199: &no_cache($r);
12200: }
12201: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
12202: unless ($charset) {
12203: $charset=&Apache::lonlocal::current_encoding;
12204: }
12205: if ($charset) { $type.='; charset='.$charset; }
12206: if ($r) {
12207: $r->content_type($type);
12208: } else {
12209: print("Content-type: $type\n\n");
12210: }
12211: }
12212:
12213: =pod
12214:
12215: =item * &add_to_env($name,$value)
12216:
12217: adds $name to the %env hash with value
12218: $value, if $name already exists, the entry is converted to an array
12219: reference and $value is added to the array.
12220:
12221: =cut
12222:
12223: sub add_to_env {
12224: my ($name,$value)=@_;
12225: if (defined($env{$name})) {
12226: if (ref($env{$name})) {
12227: #already have multiple values
12228: push(@{ $env{$name} },$value);
12229: } else {
12230: #first time seeing multiple values, convert hash entry to an arrayref
12231: my $first=$env{$name};
12232: undef($env{$name});
12233: push(@{ $env{$name} },$first,$value);
12234: }
12235: } else {
12236: $env{$name}=$value;
12237: }
12238: }
12239:
12240: =pod
12241:
12242: =item * &get_env_multiple($name)
12243:
12244: gets $name from the %env hash, it seemlessly handles the cases where multiple
12245: values may be defined and end up as an array ref.
12246:
12247: returns an array of values
12248:
12249: =cut
12250:
12251: sub get_env_multiple {
12252: my ($name) = @_;
12253: my @values;
12254: if (defined($env{$name})) {
12255: # exists is it an array
12256: if (ref($env{$name})) {
12257: @values=@{ $env{$name} };
12258: } else {
12259: $values[0]=$env{$name};
12260: }
12261: }
12262: return(@values);
12263: }
12264:
12265: # Looks at given dependencies, and returns something depending on the context.
12266: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
12267: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
12268: # For all other contexts, returns ($output, $counter, $numpathchg).
12269: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
12270: # $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.
12271: # $numpathchg: integer with the number of cleaned up dependency paths.
12272: # \%existing: hash reference clean path -> 1 only for existing dependencies.
12273: # \%mapping: hash reference clean path -> original path for all dependencies.
12274: # @param {string} actionurl - The path to the handler, indicative of the context.
12275: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
12276: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
12277: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
12278: # @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)
12279: # @return {Array} - array depending on the context (not a reference)
12280: sub ask_for_embedded_content {
12281: # NOTE: documentation was added afterwards, it could be wrong
12282: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
12283: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
12284: %currsubfile,%unused,$rem);
12285: my $counter = 0;
12286: my $numnew = 0;
12287: my $numremref = 0;
12288: my $numinvalid = 0;
12289: my $numpathchg = 0;
12290: my $numexisting = 0;
12291: my $numunused = 0;
12292: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
12293: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
12294: my $heading = &mt('Upload embedded files');
12295: my $buttontext = &mt('Upload');
12296:
12297: # fills these variables based on the context:
12298: # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
12299: # $path, $fileloc, $title, $rem, $filename
12300: if ($env{'request.course.id'}) {
12301: if ($actionurl eq '/adm/dependencies') {
12302: $navmap = Apache::lonnavmaps::navmap->new();
12303: }
12304: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12305: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12306: }
12307: if (($actionurl eq '/adm/portfolio') ||
12308: ($actionurl eq '/adm/coursegrp_portfolio')) {
12309: my $current_path='/';
12310: if ($env{'form.currentpath'}) {
12311: $current_path = $env{'form.currentpath'};
12312: }
12313: if ($actionurl eq '/adm/coursegrp_portfolio') {
12314: $udom = $cdom;
12315: $uname = $cnum;
12316: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
12317: } else {
12318: $udom = $env{'user.domain'};
12319: $uname = $env{'user.name'};
12320: $url = '/userfiles/portfolio';
12321: }
12322: $toplevel = $url.'/';
12323: $url .= $current_path;
12324: $getpropath = 1;
12325: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12326: ($actionurl eq '/adm/imsimport')) {
12327: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
12328: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
12329: $toplevel = $url;
12330: if ($rest ne '') {
12331: $url .= $rest;
12332: }
12333: } elsif ($actionurl eq '/adm/coursedocs') {
12334: if (ref($args) eq 'HASH') {
12335: $url = $args->{'docs_url'};
12336: $toplevel = $url;
12337: if ($args->{'context'} eq 'paste') {
12338: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
12339: ($path) =
12340: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12341: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12342: $fileloc =~ s{^/}{};
12343: }
12344: }
12345: } elsif ($actionurl eq '/adm/dependencies') {
12346: if ($env{'request.course.id'} ne '') {
12347: if (ref($args) eq 'HASH') {
12348: $url = $args->{'docs_url'};
12349: $title = $args->{'docs_title'};
12350: $toplevel = $url;
12351: unless ($toplevel =~ m{^/}) {
12352: $toplevel = "/$url";
12353: }
12354: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
12355: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
12356: $path = $1;
12357: } else {
12358: ($path) =
12359: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
12360: }
12361: if ($toplevel=~/^\/*(uploaded|editupload)/) {
12362: $fileloc = $toplevel;
12363: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
12364: my ($udom,$uname,$fname) =
12365: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
12366: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
12367: } else {
12368: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
12369: }
12370: $fileloc =~ s{^/}{};
12371: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
12372: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
12373: }
12374: }
12375: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12376: $udom = $cdom;
12377: $uname = $cnum;
12378: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
12379: $toplevel = $url;
12380: $path = $url;
12381: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
12382: $fileloc =~ s{^/}{};
12383: }
12384:
12385: # parses the dependency paths to get some info
12386: # fills $newfiles, $mapping, $subdependencies, $dependencies
12387: # $newfiles: hash URL -> 1 for new files or external URLs
12388: # (will be completed later)
12389: # $mapping:
12390: # for external URLs: external URL -> external URL
12391: # for relative paths: clean path -> original path
12392: # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
12393: # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
12394: foreach my $file (keys(%{$allfiles})) {
12395: my $embed_file;
12396: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
12397: $embed_file = $1;
12398: } else {
12399: $embed_file = $file;
12400: }
12401: my ($absolutepath,$cleaned_file);
12402: if ($embed_file =~ m{^\w+://}) {
12403: $cleaned_file = $embed_file;
12404: $newfiles{$cleaned_file} = 1;
12405: $mapping{$cleaned_file} = $embed_file;
12406: } else {
12407: $cleaned_file = &clean_path($embed_file);
12408: if ($embed_file =~ m{^/}) {
12409: $absolutepath = $embed_file;
12410: }
12411: if ($cleaned_file =~ m{/}) {
12412: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
12413: $path = &check_for_traversal($path,$url,$toplevel);
12414: my $item = $fname;
12415: if ($path ne '') {
12416: $item = $path.'/'.$fname;
12417: $subdependencies{$path}{$fname} = 1;
12418: } else {
12419: $dependencies{$item} = 1;
12420: }
12421: if ($absolutepath) {
12422: $mapping{$item} = $absolutepath;
12423: } else {
12424: $mapping{$item} = $embed_file;
12425: }
12426: } else {
12427: $dependencies{$embed_file} = 1;
12428: if ($absolutepath) {
12429: $mapping{$cleaned_file} = $absolutepath;
12430: } else {
12431: $mapping{$cleaned_file} = $embed_file;
12432: }
12433: }
12434: }
12435: }
12436:
12437: # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
12438: # and lists
12439: # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
12440: # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
12441: # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
12442: # the path had to be cleaned up
12443: # $existing: hash clean path -> 1 if the file exists
12444: # $numexisting: number of keys in $existing
12445: # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
12446: # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
12447: # dependency subdirectories that are
12448: # not listed as dependencies, with some exceptions using $rem
12449: my $dirptr = 16384;
12450: foreach my $path (keys(%subdependencies)) {
12451: $currsubfile{$path} = {};
12452: if (($actionurl eq '/adm/portfolio') ||
12453: ($actionurl eq '/adm/coursegrp_portfolio')) {
12454: my ($sublistref,$listerror) =
12455: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
12456: if (ref($sublistref) eq 'ARRAY') {
12457: foreach my $line (@{$sublistref}) {
12458: my ($file_name,$rest) = split(/\&/,$line,2);
12459: $currsubfile{$path}{$file_name} = 1;
12460: }
12461: }
12462: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12463: if (opendir(my $dir,$url.'/'.$path)) {
12464: my @subdir_list = grep(!/^\./,readdir($dir));
12465: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
12466: }
12467: } elsif (($actionurl eq '/adm/dependencies') ||
12468: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12469: ($args->{'context'} eq 'paste')) ||
12470: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12471: if ($env{'request.course.id'} ne '') {
12472: my $dir;
12473: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
12474: $dir = $fileloc;
12475: } else {
12476: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12477: }
12478: if ($dir ne '') {
12479: my ($sublistref,$listerror) =
12480: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
12481: if (ref($sublistref) eq 'ARRAY') {
12482: foreach my $line (@{$sublistref}) {
12483: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
12484: undef,$mtime)=split(/\&/,$line,12);
12485: unless (($testdir&$dirptr) ||
12486: ($file_name =~ /^\.\.?$/)) {
12487: $currsubfile{$path}{$file_name} = [$size,$mtime];
12488: }
12489: }
12490: }
12491: }
12492: }
12493: }
12494: foreach my $file (keys(%{$subdependencies{$path}})) {
12495: if (exists($currsubfile{$path}{$file})) {
12496: my $item = $path.'/'.$file;
12497: unless ($mapping{$item} eq $item) {
12498: $pathchanges{$item} = 1;
12499: }
12500: $existing{$item} = 1;
12501: $numexisting ++;
12502: } else {
12503: $newfiles{$path.'/'.$file} = 1;
12504: }
12505: }
12506: if ($actionurl eq '/adm/dependencies') {
12507: foreach my $path (keys(%currsubfile)) {
12508: if (ref($currsubfile{$path}) eq 'HASH') {
12509: foreach my $file (keys(%{$currsubfile{$path}})) {
12510: unless ($subdependencies{$path}{$file}) {
12511: next if (($rem ne '') &&
12512: (($env{"httpref.$rem"."$path/$file"} ne '') ||
12513: (ref($navmap) &&
12514: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
12515: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12516: ($navmap->getResourceByUrl($rem."$path/$1")))))));
12517: $unused{$path.'/'.$file} = 1;
12518: }
12519: }
12520: }
12521: }
12522: }
12523: }
12524:
12525: # fills $currfile, hash file name -> 1 or [$size,$mtime]
12526: # for files in $url or $fileloc (target directory) in some contexts
12527: my %currfile;
12528: if (($actionurl eq '/adm/portfolio') ||
12529: ($actionurl eq '/adm/coursegrp_portfolio')) {
12530: my ($dirlistref,$listerror) =
12531: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
12532: if (ref($dirlistref) eq 'ARRAY') {
12533: foreach my $line (@{$dirlistref}) {
12534: my ($file_name,$rest) = split(/\&/,$line,2);
12535: $currfile{$file_name} = 1;
12536: }
12537: }
12538: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12539: if (opendir(my $dir,$url)) {
12540: my @dir_list = grep(!/^\./,readdir($dir));
12541: map {$currfile{$_} = 1;} @dir_list;
12542: }
12543: } elsif (($actionurl eq '/adm/dependencies') ||
12544: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12545: ($args->{'context'} eq 'paste')) ||
12546: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
12547: if ($env{'request.course.id'} ne '') {
12548: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
12549: if ($dir ne '') {
12550: my ($dirlistref,$listerror) =
12551: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
12552: if (ref($dirlistref) eq 'ARRAY') {
12553: foreach my $line (@{$dirlistref}) {
12554: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
12555: $size,undef,$mtime)=split(/\&/,$line,12);
12556: unless (($testdir&$dirptr) ||
12557: ($file_name =~ /^\.\.?$/)) {
12558: $currfile{$file_name} = [$size,$mtime];
12559: }
12560: }
12561: }
12562: }
12563: }
12564: }
12565: # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
12566: # are not in subdirectories, using $currfile
12567: foreach my $file (keys(%dependencies)) {
12568: if (exists($currfile{$file})) {
12569: unless ($mapping{$file} eq $file) {
12570: $pathchanges{$file} = 1;
12571: }
12572: $existing{$file} = 1;
12573: $numexisting ++;
12574: } else {
12575: $newfiles{$file} = 1;
12576: }
12577: }
12578: foreach my $file (keys(%currfile)) {
12579: unless (($file eq $filename) ||
12580: ($file eq $filename.'.bak') ||
12581: ($dependencies{$file})) {
12582: if ($actionurl eq '/adm/dependencies') {
12583: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
12584: next if (($rem ne '') &&
12585: (($env{"httpref.$rem".$file} ne '') ||
12586: (ref($navmap) &&
12587: (($navmap->getResourceByUrl($rem.$file) ne '') ||
12588: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
12589: ($navmap->getResourceByUrl($rem.$1)))))));
12590: }
12591: }
12592: $unused{$file} = 1;
12593: }
12594: }
12595:
12596: # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
12597: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
12598: ($args->{'context'} eq 'paste')) {
12599: $counter = scalar(keys(%existing));
12600: $numpathchg = scalar(keys(%pathchanges));
12601: return ($output,$counter,$numpathchg,\%existing);
12602: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
12603: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
12604: $counter = scalar(keys(%existing));
12605: $numpathchg = scalar(keys(%pathchanges));
12606: return ($output,$counter,$numpathchg,\%existing,\%mapping);
12607: }
12608:
12609: # returns HTML otherwise, with dependency results and to ask for more uploads
12610:
12611: # $upload_output: missing dependencies (with upload form)
12612: # $modify_output: uploaded dependencies (in use)
12613: # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
12614: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
12615: if ($actionurl eq '/adm/dependencies') {
12616: next if ($embed_file =~ m{^\w+://});
12617: }
12618: $upload_output .= &start_data_table_row().
12619: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12620: '<span class="LC_filename">'.$embed_file.'</span>';
12621: unless ($mapping{$embed_file} eq $embed_file) {
12622: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
12623: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
12624: }
12625: $upload_output .= '</td>';
12626: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
12627: $upload_output.='<td align="right">'.
12628: '<span class="LC_info LC_fontsize_medium">'.
12629: &mt("URL points to web address").'</span>';
12630: $numremref++;
12631: } elsif ($args->{'error_on_invalid_names'}
12632: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
12633: $upload_output.='<td align="right"><span class="LC_warning">'.
12634: &mt('Invalid characters').'</span>';
12635: $numinvalid++;
12636: } else {
12637: $upload_output .= '<td>'.
12638: &embedded_file_element('upload_embedded',$counter,
12639: $embed_file,\%mapping,
12640: $allfiles,$codebase,'upload');
12641: $counter ++;
12642: $numnew ++;
12643: }
12644: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
12645: }
12646: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
12647: if ($actionurl eq '/adm/dependencies') {
12648: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
12649: $modify_output .= &start_data_table_row().
12650: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
12651: '<img src="'.&icon($embed_file).'" border="0" />'.
12652: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
12653: '<td>'.$size.'</td>'.
12654: '<td>'.$mtime.'</td>'.
12655: '<td><label><input type="checkbox" name="mod_upload_dep" '.
12656: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
12657: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
12658: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
12659: &embedded_file_element('upload_embedded',$counter,
12660: $embed_file,\%mapping,
12661: $allfiles,$codebase,'modify').
12662: '</div></td>'.
12663: &end_data_table_row()."\n";
12664: $counter ++;
12665: } else {
12666: $upload_output .= &start_data_table_row().
12667: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
12668: '<span class="LC_filename">'.$embed_file.'</span></td>'.
12669: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
12670: &Apache::loncommon::end_data_table_row()."\n";
12671: }
12672: }
12673: my $delidx = $counter;
12674: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
12675: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
12676: $delete_output .= &start_data_table_row().
12677: '<td><img src="'.&icon($oldfile).'" />'.
12678: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
12679: '<td>'.$size.'</td>'.
12680: '<td>'.$mtime.'</td>'.
12681: '<td><label><input type="checkbox" name="del_upload_dep" '.
12682: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
12683: &embedded_file_element('upload_embedded',$delidx,
12684: $oldfile,\%mapping,$allfiles,
12685: $codebase,'delete').'</td>'.
12686: &end_data_table_row()."\n";
12687: $numunused ++;
12688: $delidx ++;
12689: }
12690: if ($upload_output) {
12691: $upload_output = &start_data_table().
12692: $upload_output.
12693: &end_data_table()."\n";
12694: }
12695: if ($modify_output) {
12696: $modify_output = &start_data_table().
12697: &start_data_table_header_row().
12698: '<th>'.&mt('File').'</th>'.
12699: '<th>'.&mt('Size (KB)').'</th>'.
12700: '<th>'.&mt('Modified').'</th>'.
12701: '<th>'.&mt('Upload replacement?').'</th>'.
12702: &end_data_table_header_row().
12703: $modify_output.
12704: &end_data_table()."\n";
12705: }
12706: if ($delete_output) {
12707: $delete_output = &start_data_table().
12708: &start_data_table_header_row().
12709: '<th>'.&mt('File').'</th>'.
12710: '<th>'.&mt('Size (KB)').'</th>'.
12711: '<th>'.&mt('Modified').'</th>'.
12712: '<th>'.&mt('Delete?').'</th>'.
12713: &end_data_table_header_row().
12714: $delete_output.
12715: &end_data_table()."\n";
12716: }
12717: my $applies = 0;
12718: if ($numremref) {
12719: $applies ++;
12720: }
12721: if ($numinvalid) {
12722: $applies ++;
12723: }
12724: if ($numexisting) {
12725: $applies ++;
12726: }
12727: if ($counter || $numunused) {
12728: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
12729: ' method="post" enctype="multipart/form-data">'."\n".
12730: $state.'<h3>'.$heading.'</h3>';
12731: if ($actionurl eq '/adm/dependencies') {
12732: if ($numnew) {
12733: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
12734: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
12735: $upload_output.'<br />'."\n";
12736: }
12737: if ($numexisting) {
12738: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
12739: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
12740: $modify_output.'<br />'."\n";
12741: $buttontext = &mt('Save changes');
12742: }
12743: if ($numunused) {
12744: $output .= '<h4>'.&mt('Unused files').'</h4>'.
12745: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
12746: $delete_output.'<br />'."\n";
12747: $buttontext = &mt('Save changes');
12748: }
12749: } else {
12750: $output .= $upload_output.'<br />'."\n";
12751: }
12752: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
12753: $counter.'" />'."\n";
12754: if ($actionurl eq '/adm/dependencies') {
12755: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
12756: $numnew.'" />'."\n";
12757: } elsif ($actionurl eq '') {
12758: $output .= '<input type="hidden" name="phase" value="three" />';
12759: }
12760: } elsif ($applies) {
12761: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
12762: if ($applies > 1) {
12763: $output .=
12764: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
12765: if ($numremref) {
12766: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
12767: }
12768: if ($numinvalid) {
12769: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
12770: }
12771: if ($numexisting) {
12772: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
12773: }
12774: $output .= '</ul><br />';
12775: } elsif ($numremref) {
12776: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
12777: } elsif ($numinvalid) {
12778: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
12779: } elsif ($numexisting) {
12780: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
12781: }
12782: $output .= $upload_output.'<br />';
12783: }
12784: my ($pathchange_output,$chgcount);
12785: $chgcount = $counter;
12786: if (keys(%pathchanges) > 0) {
12787: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
12788: if ($counter) {
12789: $output .= &embedded_file_element('pathchange',$chgcount,
12790: $embed_file,\%mapping,
12791: $allfiles,$codebase,'change');
12792: } else {
12793: $pathchange_output .=
12794: &start_data_table_row().
12795: '<td><input type ="checkbox" name="namechange" value="'.
12796: $chgcount.'" checked="checked" /></td>'.
12797: '<td>'.$mapping{$embed_file}.'</td>'.
12798: '<td>'.$embed_file.
12799: &embedded_file_element('pathchange',$numpathchg,$embed_file,
12800: \%mapping,$allfiles,$codebase,'change').
12801: '</td>'.&end_data_table_row();
12802: }
12803: $numpathchg ++;
12804: $chgcount ++;
12805: }
12806: }
12807: if (($counter) || ($numunused)) {
12808: if ($numpathchg) {
12809: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
12810: $numpathchg.'" />'."\n";
12811: }
12812: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
12813: ($actionurl eq '/adm/imsimport')) {
12814: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
12815: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
12816: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
12817: } elsif ($actionurl eq '/adm/dependencies') {
12818: $output .= '<input type="hidden" name="action" value="process_changes" />';
12819: }
12820: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
12821: } elsif ($numpathchg) {
12822: my %pathchange = ();
12823: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12824: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12825: $output .= '<p>'.&mt('or').'</p>';
12826: }
12827: }
12828: return ($output,$counter,$numpathchg);
12829: }
12830:
12831: =pod
12832:
12833: =item * clean_path($name)
12834:
12835: Performs clean-up of directories, subdirectories and filename in an
12836: embedded object, referenced in an HTML file which is being uploaded
12837: to a course or portfolio, where
12838: "Upload embedded images/multimedia files if HTML file" checkbox was
12839: checked.
12840:
12841: Clean-up is similar to replacements in lonnet::clean_filename()
12842: except each / between sub-directory and next level is preserved.
12843:
12844: =cut
12845:
12846: sub clean_path {
12847: my ($embed_file) = @_;
12848: $embed_file =~s{^/+}{};
12849: my @contents;
12850: if ($embed_file =~ m{/}) {
12851: @contents = split(/\//,$embed_file);
12852: } else {
12853: @contents = ($embed_file);
12854: }
12855: my $lastidx = scalar(@contents)-1;
12856: for (my $i=0; $i<=$lastidx; $i++) {
12857: $contents[$i]=~s{\\}{/}g;
12858: $contents[$i]=~s/\s+/\_/g;
12859: $contents[$i]=~s{[^/\w\.\-]}{}g;
12860: if ($i == $lastidx) {
12861: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12862: }
12863: }
12864: if ($lastidx > 0) {
12865: return join('/',@contents);
12866: } else {
12867: return $contents[0];
12868: }
12869: }
12870:
12871: sub embedded_file_element {
12872: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12873: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12874: (ref($codebase) eq 'HASH'));
12875: my $output;
12876: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12877: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12878: }
12879: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12880: &escape($embed_file).'" />';
12881: unless (($context eq 'upload_embedded') &&
12882: ($mapping->{$embed_file} eq $embed_file)) {
12883: $output .='
12884: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12885: }
12886: my $attrib;
12887: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12888: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12889: }
12890: $output .=
12891: "\n\t\t".
12892: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12893: $attrib.'" />';
12894: if (exists($codebase->{$mapping->{$embed_file}})) {
12895: $output .=
12896: "\n\t\t".
12897: '<input name="codebase_'.$num.'" type="hidden" value="'.
12898: &escape($codebase->{$mapping->{$embed_file}}).'" />';
12899: }
12900: return $output;
12901: }
12902:
12903: sub get_dependency_details {
12904: my ($currfile,$currsubfile,$embed_file) = @_;
12905: my ($size,$mtime,$showsize,$showmtime);
12906: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12907: if ($embed_file =~ m{/}) {
12908: my ($path,$fname) = split(/\//,$embed_file);
12909: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12910: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12911: }
12912: } else {
12913: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12914: ($size,$mtime) = @{$currfile->{$embed_file}};
12915: }
12916: }
12917: $showsize = $size/1024.0;
12918: $showsize = sprintf("%.1f",$showsize);
12919: if ($mtime > 0) {
12920: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12921: }
12922: }
12923: return ($showsize,$showmtime);
12924: }
12925:
12926: sub ask_embedded_js {
12927: return <<"END";
12928: <script type="text/javascript"">
12929: // <![CDATA[
12930: function toggleBrowse(counter) {
12931: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12932: var fileid = document.getElementById('embedded_item_'+counter);
12933: var uploaddivid = document.getElementById('moduploaddep_'+counter);
12934: if (chkboxid.checked == true) {
12935: uploaddivid.style.display='block';
12936: } else {
12937: uploaddivid.style.display='none';
12938: fileid.value = '';
12939: }
12940: }
12941: // ]]>
12942: </script>
12943:
12944: END
12945: }
12946:
12947: sub upload_embedded {
12948: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12949: $current_disk_usage,$hiddenstate,$actionurl) = @_;
12950: my (%pathchange,$output,$modifyform,$footer,$returnflag);
12951: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12952: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12953: my $orig_uploaded_filename =
12954: $env{'form.embedded_item_'.$i.'.filename'};
12955: foreach my $type ('orig','ref','attrib','codebase') {
12956: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12957: $env{'form.embedded_'.$type.'_'.$i} =
12958: &unescape($env{'form.embedded_'.$type.'_'.$i});
12959: }
12960: }
12961: my ($path,$fname) =
12962: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12963: # no path, whole string is fname
12964: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12965: $fname = &Apache::lonnet::clean_filename($fname);
12966: # See if there is anything left
12967: next if ($fname eq '');
12968:
12969: # Check if file already exists as a file or directory.
12970: my ($state,$msg);
12971: if ($context eq 'portfolio') {
12972: my $port_path = $dirpath;
12973: if ($group ne '') {
12974: $port_path = "groups/$group/$port_path";
12975: }
12976: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12977: $fname,$group,'embedded_item_'.$i,
12978: $dir_root,$port_path,$disk_quota,
12979: $current_disk_usage,$uname,$udom);
12980: if ($state eq 'will_exceed_quota'
12981: || $state eq 'file_locked') {
12982: $output .= $msg;
12983: next;
12984: }
12985: } elsif (($context eq 'author') || ($context eq 'testbank')) {
12986: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12987: if ($state eq 'exists') {
12988: $output .= $msg;
12989: next;
12990: }
12991: }
12992: # Check if extension is valid
12993: if (($fname =~ /\.(\w+)$/) &&
12994: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12995: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12996: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12997: next;
12998: } elsif (($fname =~ /\.(\w+)$/) &&
12999: (!defined(&Apache::loncommon::fileembstyle($1)))) {
13000: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
13001: next;
13002: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
13003: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
13004: next;
13005: }
13006: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
13007: my $subdir = $path;
13008: $subdir =~ s{/+$}{};
13009: if ($context eq 'portfolio') {
13010: my $result;
13011: if ($state eq 'existingfile') {
13012: $result=
13013: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
13014: $dirpath.$env{'form.currentpath'}.$subdir);
13015: } else {
13016: $result=
13017: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
13018: $dirpath.
13019: $env{'form.currentpath'}.$subdir);
13020: if ($result !~ m|^/uploaded/|) {
13021: $output .= '<span class="LC_error">'
13022: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13023: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13024: .'</span><br />';
13025: next;
13026: } else {
13027: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13028: $path.$fname.'</span>').'<br />';
13029: }
13030: }
13031: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
13032: my $extendedsubdir = $dirpath.'/'.$subdir;
13033: $extendedsubdir =~ s{/+$}{};
13034: my $result =
13035: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
13036: if ($result !~ m|^/uploaded/|) {
13037: $output .= '<span class="LC_error">'
13038: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
13039: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
13040: .'</span><br />';
13041: next;
13042: } else {
13043: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13044: $path.$fname.'</span>').'<br />';
13045: if ($context eq 'syllabus') {
13046: &Apache::lonnet::make_public_indefinitely($result);
13047: }
13048: }
13049: } else {
13050: # Save the file
13051: my $target = $env{'form.embedded_item_'.$i};
13052: my $fullpath = $dir_root.$dirpath.'/'.$path;
13053: my $dest = $fullpath.$fname;
13054: my $url = $url_root.$dirpath.'/'.$path.$fname;
13055: my @parts=split(/\//,"$dirpath/$path");
13056: my $count;
13057: my $filepath = $dir_root;
13058: foreach my $subdir (@parts) {
13059: $filepath .= "/$subdir";
13060: if (!-e $filepath) {
13061: mkdir($filepath,0770);
13062: }
13063: }
13064: my $fh;
13065: if (!open($fh,'>'.$dest)) {
13066: &Apache::lonnet::logthis('Failed to create '.$dest);
13067: $output .= '<span class="LC_error">'.
13068: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
13069: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13070: '</span><br />';
13071: } else {
13072: if (!print $fh $env{'form.embedded_item_'.$i}) {
13073: &Apache::lonnet::logthis('Failed to write to '.$dest);
13074: $output .= '<span class="LC_error">'.
13075: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
13076: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
13077: '</span><br />';
13078: } else {
13079: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
13080: $url.'</span>').'<br />';
13081: unless ($context eq 'testbank') {
13082: $footer .= &mt('View embedded file: [_1]',
13083: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
13084: }
13085: }
13086: close($fh);
13087: }
13088: }
13089: if ($env{'form.embedded_ref_'.$i}) {
13090: $pathchange{$i} = 1;
13091: }
13092: }
13093: if ($output) {
13094: $output = '<p>'.$output.'</p>';
13095: }
13096: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
13097: $returnflag = 'ok';
13098: my $numpathchgs = scalar(keys(%pathchange));
13099: if ($numpathchgs > 0) {
13100: if ($context eq 'portfolio') {
13101: $output .= '<p>'.&mt('or').'</p>';
13102: } elsif ($context eq 'testbank') {
13103: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
13104: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
13105: $returnflag = 'modify_orightml';
13106: }
13107: }
13108: return ($output.$footer,$returnflag,$numpathchgs);
13109: }
13110:
13111: sub modify_html_form {
13112: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
13113: my $end = 0;
13114: my $modifyform;
13115: if ($context eq 'upload_embedded') {
13116: return unless (ref($pathchange) eq 'HASH');
13117: if ($env{'form.number_embedded_items'}) {
13118: $end += $env{'form.number_embedded_items'};
13119: }
13120: if ($env{'form.number_pathchange_items'}) {
13121: $end += $env{'form.number_pathchange_items'};
13122: }
13123: if ($end) {
13124: for (my $i=0; $i<$end; $i++) {
13125: if ($i < $env{'form.number_embedded_items'}) {
13126: next unless($pathchange->{$i});
13127: }
13128: $modifyform .=
13129: &start_data_table_row().
13130: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
13131: 'checked="checked" /></td>'.
13132: '<td>'.$env{'form.embedded_ref_'.$i}.
13133: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
13134: &escape($env{'form.embedded_ref_'.$i}).'" />'.
13135: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
13136: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
13137: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
13138: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
13139: '<td>'.$env{'form.embedded_orig_'.$i}.
13140: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
13141: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
13142: &end_data_table_row();
13143: }
13144: }
13145: } else {
13146: $modifyform = $pathchgtable;
13147: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
13148: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
13149: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
13150: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
13151: }
13152: }
13153: if ($modifyform) {
13154: if ($actionurl eq '/adm/dependencies') {
13155: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
13156: }
13157: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
13158: '<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".
13159: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
13160: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
13161: '</ol></p>'."\n".'<p>'.
13162: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
13163: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
13164: &start_data_table()."\n".
13165: &start_data_table_header_row().
13166: '<th>'.&mt('Change?').'</th>'.
13167: '<th>'.&mt('Current reference').'</th>'.
13168: '<th>'.&mt('Required reference').'</th>'.
13169: &end_data_table_header_row()."\n".
13170: $modifyform.
13171: &end_data_table().'<br />'."\n".$hiddenstate.
13172: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
13173: '</form>'."\n";
13174: }
13175: return;
13176: }
13177:
13178: sub modify_html_refs {
13179: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
13180: my $container;
13181: if ($context eq 'portfolio') {
13182: $container = $env{'form.container'};
13183: } elsif ($context eq 'coursedoc') {
13184: $container = $env{'form.primaryurl'};
13185: } elsif ($context eq 'manage_dependencies') {
13186: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
13187: $container = "/$container";
13188: } elsif ($context eq 'syllabus') {
13189: $container = $url;
13190: } else {
13191: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
13192: }
13193: my (%allfiles,%codebase,$output,$content);
13194: my @changes = &get_env_multiple('form.namechange');
13195: unless ((@changes > 0) || ($context eq 'syllabus')) {
13196: if (wantarray) {
13197: return ('',0,0);
13198: } else {
13199: return;
13200: }
13201: }
13202: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
13203: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13204: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
13205: if (wantarray) {
13206: return ('',0,0);
13207: } else {
13208: return;
13209: }
13210: }
13211: $content = &Apache::lonnet::getfile($container);
13212: if ($content eq '-1') {
13213: if (wantarray) {
13214: return ('',0,0);
13215: } else {
13216: return;
13217: }
13218: }
13219: } else {
13220: unless ($container =~ /^\Q$dir_root\E/) {
13221: if (wantarray) {
13222: return ('',0,0);
13223: } else {
13224: return;
13225: }
13226: }
13227: if (open(my $fh,'<',$container)) {
13228: $content = join('', <$fh>);
13229: close($fh);
13230: } else {
13231: if (wantarray) {
13232: return ('',0,0);
13233: } else {
13234: return;
13235: }
13236: }
13237: }
13238: my ($count,$codebasecount) = (0,0);
13239: my $mm = new File::MMagic;
13240: my $mime_type = $mm->checktype_contents($content);
13241: if ($mime_type eq 'text/html') {
13242: my $parse_result =
13243: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
13244: \%codebase,\$content);
13245: if ($parse_result eq 'ok') {
13246: foreach my $i (@changes) {
13247: my $orig = &unescape($env{'form.embedded_orig_'.$i});
13248: my $ref = &unescape($env{'form.embedded_ref_'.$i});
13249: if ($allfiles{$ref}) {
13250: my $newname = $orig;
13251: my ($attrib_regexp,$codebase);
13252: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
13253: if ($attrib_regexp =~ /:/) {
13254: $attrib_regexp =~ s/\:/|/g;
13255: }
13256: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13257: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13258: $count += $numchg;
13259: $allfiles{$newname} = $allfiles{$ref};
13260: delete($allfiles{$ref});
13261: }
13262: if ($env{'form.embedded_codebase_'.$i} ne '') {
13263: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
13264: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
13265: $codebasecount ++;
13266: }
13267: }
13268: }
13269: my $skiprewrites;
13270: if ($count || $codebasecount) {
13271: my $saveresult;
13272: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
13273: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
13274: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13275: if ($url eq $container) {
13276: my ($fname) = ($container =~ m{/([^/]+)$});
13277: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13278: $count,'<span class="LC_filename">'.
13279: $fname.'</span>').'</p>';
13280: } else {
13281: $output = '<p class="LC_error">'.
13282: &mt('Error: update failed for: [_1].',
13283: '<span class="LC_filename">'.
13284: $container.'</span>').'</p>';
13285: }
13286: if ($context eq 'syllabus') {
13287: unless ($saveresult eq 'ok') {
13288: $skiprewrites = 1;
13289: }
13290: }
13291: } else {
13292: if (open(my $fh,'>',$container)) {
13293: print $fh $content;
13294: close($fh);
13295: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
13296: $count,'<span class="LC_filename">'.
13297: $container.'</span>').'</p>';
13298: } else {
13299: $output = '<p class="LC_error">'.
13300: &mt('Error: could not update [_1].',
13301: '<span class="LC_filename">'.
13302: $container.'</span>').'</p>';
13303: }
13304: }
13305: }
13306: if (($context eq 'syllabus') && (!$skiprewrites)) {
13307: my ($actionurl,$state);
13308: $actionurl = "/public/$udom/$uname/syllabus";
13309: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
13310: &ask_for_embedded_content($actionurl,$state,\%allfiles,
13311: \%codebase,
13312: {'context' => 'rewrites',
13313: 'ignore_remote_references' => 1,});
13314: if (ref($mapping) eq 'HASH') {
13315: my $rewrites = 0;
13316: foreach my $key (keys(%{$mapping})) {
13317: next if ($key =~ m{^https?://});
13318: my $ref = $mapping->{$key};
13319: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
13320: my $attrib;
13321: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
13322: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
13323: }
13324: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
13325: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
13326: $rewrites += $numchg;
13327: }
13328: }
13329: if ($rewrites) {
13330: my $saveresult;
13331: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
13332: if ($url eq $container) {
13333: my ($fname) = ($container =~ m{/([^/]+)$});
13334: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
13335: $count,'<span class="LC_filename">'.
13336: $fname.'</span>').'</p>';
13337: } else {
13338: $output .= '<p class="LC_error">'.
13339: &mt('Error: could not update links in [_1].',
13340: '<span class="LC_filename">'.
13341: $container.'</span>').'</p>';
13342:
13343: }
13344: }
13345: }
13346: }
13347: } else {
13348: &logthis('Failed to parse '.$container.
13349: ' to modify references: '.$parse_result);
13350: }
13351: }
13352: if (wantarray) {
13353: return ($output,$count,$codebasecount);
13354: } else {
13355: return $output;
13356: }
13357: }
13358:
13359: sub check_for_existing {
13360: my ($path,$fname,$element) = @_;
13361: my ($state,$msg);
13362: if (-d $path.'/'.$fname) {
13363: $state = 'exists';
13364: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13365: } elsif (-e $path.'/'.$fname) {
13366: $state = 'exists';
13367: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
13368: }
13369: if ($state eq 'exists') {
13370: $msg = '<span class="LC_error">'.$msg.'</span><br />';
13371: }
13372: return ($state,$msg);
13373: }
13374:
13375: sub check_for_upload {
13376: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
13377: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
13378: my $filesize = length($env{'form.'.$element});
13379: if (!$filesize) {
13380: my $msg = '<span class="LC_error">'.
13381: &mt('Unable to upload [_1]. (size = [_2] bytes)',
13382: '<span class="LC_filename">'.$fname.'</span>',
13383: $filesize).'<br />'.
13384: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
13385: '</span>';
13386: return ('zero_bytes',$msg);
13387: }
13388: $filesize = $filesize/1000; #express in k (1024?)
13389: my $getpropath = 1;
13390: my ($dirlistref,$listerror) =
13391: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
13392: my $found_file = 0;
13393: my $locked_file = 0;
13394: my @lockers;
13395: my $navmap;
13396: if ($env{'request.course.id'}) {
13397: $navmap = Apache::lonnavmaps::navmap->new();
13398: }
13399: if (ref($dirlistref) eq 'ARRAY') {
13400: foreach my $line (@{$dirlistref}) {
13401: my ($file_name,$rest)=split(/\&/,$line,2);
13402: if ($file_name eq $fname){
13403: $file_name = $path.$file_name;
13404: if ($group ne '') {
13405: $file_name = $group.$file_name;
13406: }
13407: $found_file = 1;
13408: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
13409: foreach my $lock (@lockers) {
13410: if (ref($lock) eq 'ARRAY') {
13411: my ($symb,$crsid) = @{$lock};
13412: if ($crsid eq $env{'request.course.id'}) {
13413: if (ref($navmap)) {
13414: my $res = $navmap->getBySymb($symb);
13415: foreach my $part (@{$res->parts()}) {
13416: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
13417: unless (($slot_status == $res->RESERVED) ||
13418: ($slot_status == $res->RESERVED_LOCATION)) {
13419: $locked_file = 1;
13420: }
13421: }
13422: } else {
13423: $locked_file = 1;
13424: }
13425: } else {
13426: $locked_file = 1;
13427: }
13428: }
13429: }
13430: } else {
13431: my @info = split(/\&/,$rest);
13432: my $currsize = $info[6]/1000;
13433: if ($currsize < $filesize) {
13434: my $extra = $filesize - $currsize;
13435: if (($current_disk_usage + $extra) > $disk_quota) {
13436: my $msg = '<p class="LC_warning">'.
13437: &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.',
13438: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
13439: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
13440: $disk_quota,$current_disk_usage).'</p>';
13441: return ('will_exceed_quota',$msg);
13442: }
13443: }
13444: }
13445: }
13446: }
13447: }
13448: if (($current_disk_usage + $filesize) > $disk_quota){
13449: my $msg = '<p class="LC_warning">'.
13450: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
13451: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
13452: return ('will_exceed_quota',$msg);
13453: } elsif ($found_file) {
13454: if ($locked_file) {
13455: my $msg = '<p class="LC_warning">';
13456: $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>');
13457: $msg .= '</p>';
13458: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
13459: return ('file_locked',$msg);
13460: } else {
13461: my $msg = '<p class="LC_error">';
13462: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
13463: $msg .= '</p>';
13464: return ('existingfile',$msg);
13465: }
13466: }
13467: }
13468:
13469: sub check_for_traversal {
13470: my ($path,$url,$toplevel) = @_;
13471: my @parts=split(/\//,$path);
13472: my $cleanpath;
13473: my $fullpath = $url;
13474: for (my $i=0;$i<@parts;$i++) {
13475: next if ($parts[$i] eq '.');
13476: if ($parts[$i] eq '..') {
13477: $fullpath =~ s{([^/]+/)$}{};
13478: } else {
13479: $fullpath .= $parts[$i].'/';
13480: }
13481: }
13482: if ($fullpath =~ /^\Q$url\E(.*)$/) {
13483: $cleanpath = $1;
13484: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
13485: my $curr_toprel = $1;
13486: my @parts = split(/\//,$curr_toprel);
13487: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
13488: my @urlparts = split(/\//,$url_toprel);
13489: my $doubledots;
13490: my $startdiff = -1;
13491: for (my $i=0; $i<@urlparts; $i++) {
13492: if ($startdiff == -1) {
13493: unless ($urlparts[$i] eq $parts[$i]) {
13494: $startdiff = $i;
13495: $doubledots .= '../';
13496: }
13497: } else {
13498: $doubledots .= '../';
13499: }
13500: }
13501: if ($startdiff > -1) {
13502: $cleanpath = $doubledots;
13503: for (my $i=$startdiff; $i<@parts; $i++) {
13504: $cleanpath .= $parts[$i].'/';
13505: }
13506: }
13507: }
13508: $cleanpath =~ s{(/)$}{};
13509: return $cleanpath;
13510: }
13511:
13512: sub is_archive_file {
13513: my ($mimetype) = @_;
13514: if (($mimetype eq 'application/octet-stream') ||
13515: ($mimetype eq 'application/x-stuffit') ||
13516: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
13517: return 1;
13518: }
13519: return;
13520: }
13521:
13522: sub decompress_form {
13523: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
13524: my %lt = &Apache::lonlocal::texthash (
13525: this => 'This file is an archive file.',
13526: camt => 'This file is a Camtasia archive file.',
13527: itsc => 'Its contents are as follows:',
13528: youm => 'You may wish to extract its contents.',
13529: extr => 'Extract contents',
13530: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
13531: proa => 'Process automatically?',
13532: yes => 'Yes',
13533: no => 'No',
13534: fold => 'Title for folder containing movie',
13535: movi => 'Title for page containing embedded movie',
13536: );
13537: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
13538: my ($is_camtasia,$topdir,%toplevel,@paths);
13539: my $info = &list_archive_contents($fileloc,\@paths);
13540: if (@paths) {
13541: foreach my $path (@paths) {
13542: $path =~ s{^/}{};
13543: if ($path =~ m{^([^/]+)/$}) {
13544: $topdir = $1;
13545: }
13546: if ($path =~ m{^([^/]+)/}) {
13547: $toplevel{$1} = $path;
13548: } else {
13549: $toplevel{$path} = $path;
13550: }
13551: }
13552: }
13553: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
13554: my @camtasia6 = ("$topdir/","$topdir/index.html",
13555: "$topdir/media/",
13556: "$topdir/media/$topdir.mp4",
13557: "$topdir/media/FirstFrame.png",
13558: "$topdir/media/player.swf",
13559: "$topdir/media/swfobject.js",
13560: "$topdir/media/expressInstall.swf");
13561: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
13562: "$topdir/$topdir.mp4",
13563: "$topdir/$topdir\_config.xml",
13564: "$topdir/$topdir\_controller.swf",
13565: "$topdir/$topdir\_embed.css",
13566: "$topdir/$topdir\_First_Frame.png",
13567: "$topdir/$topdir\_player.html",
13568: "$topdir/$topdir\_Thumbnails.png",
13569: "$topdir/playerProductInstall.swf",
13570: "$topdir/scripts/",
13571: "$topdir/scripts/config_xml.js",
13572: "$topdir/scripts/handlebars.js",
13573: "$topdir/scripts/jquery-1.7.1.min.js",
13574: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
13575: "$topdir/scripts/modernizr.js",
13576: "$topdir/scripts/player-min.js",
13577: "$topdir/scripts/swfobject.js",
13578: "$topdir/skins/",
13579: "$topdir/skins/configuration_express.xml",
13580: "$topdir/skins/express_show/",
13581: "$topdir/skins/express_show/player-min.css",
13582: "$topdir/skins/express_show/spritesheet.png");
13583: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
13584: "$topdir/$topdir.mp4",
13585: "$topdir/$topdir\_config.xml",
13586: "$topdir/$topdir\_controller.swf",
13587: "$topdir/$topdir\_embed.css",
13588: "$topdir/$topdir\_First_Frame.png",
13589: "$topdir/$topdir\_player.html",
13590: "$topdir/$topdir\_Thumbnails.png",
13591: "$topdir/playerProductInstall.swf",
13592: "$topdir/scripts/",
13593: "$topdir/scripts/config_xml.js",
13594: "$topdir/scripts/techsmith-smart-player.min.js",
13595: "$topdir/skins/",
13596: "$topdir/skins/configuration_express.xml",
13597: "$topdir/skins/express_show/",
13598: "$topdir/skins/express_show/spritesheet.min.css",
13599: "$topdir/skins/express_show/spritesheet.png",
13600: "$topdir/skins/express_show/techsmith-smart-player.min.css");
13601: my @diffs = &compare_arrays(\@paths,\@camtasia6);
13602: if (@diffs == 0) {
13603: $is_camtasia = 6;
13604: } else {
13605: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
13606: if (@diffs == 0) {
13607: $is_camtasia = 8;
13608: } else {
13609: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
13610: if (@diffs == 0) {
13611: $is_camtasia = 8;
13612: }
13613: }
13614: }
13615: }
13616: my $output;
13617: if ($is_camtasia) {
13618: $output = <<"ENDCAM";
13619: <script type="text/javascript" language="Javascript">
13620: // <![CDATA[
13621:
13622: function camtasiaToggle() {
13623: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
13624: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
13625: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
13626: document.getElementById('camtasia_titles').style.display='block';
13627: } else {
13628: document.getElementById('camtasia_titles').style.display='none';
13629: }
13630: }
13631: }
13632: return;
13633: }
13634:
13635: // ]]>
13636: </script>
13637: <p>$lt{'camt'}</p>
13638: ENDCAM
13639: } else {
13640: $output = '<p>'.$lt{'this'};
13641: if ($info eq '') {
13642: $output .= ' '.$lt{'youm'}.'</p>'."\n";
13643: } else {
13644: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
13645: '<div><pre>'.$info.'</pre></div>';
13646: }
13647: }
13648: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
13649: my $duplicates;
13650: my $num = 0;
13651: if (ref($dirlist) eq 'ARRAY') {
13652: foreach my $item (@{$dirlist}) {
13653: if (ref($item) eq 'ARRAY') {
13654: if (exists($toplevel{$item->[0]})) {
13655: $duplicates .=
13656: &start_data_table_row().
13657: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
13658: 'value="0" checked="checked" />'.&mt('No').'</label>'.
13659: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
13660: 'value="1" />'.&mt('Yes').'</label>'.
13661: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
13662: '<td>'.$item->[0].'</td>';
13663: if ($item->[2]) {
13664: $duplicates .= '<td>'.&mt('Directory').'</td>';
13665: } else {
13666: $duplicates .= '<td>'.&mt('File').'</td>';
13667: }
13668: $duplicates .= '<td>'.$item->[3].'</td>'.
13669: '<td>'.
13670: &Apache::lonlocal::locallocaltime($item->[4]).
13671: '</td>'.
13672: &end_data_table_row();
13673: $num ++;
13674: }
13675: }
13676: }
13677: }
13678: my $itemcount;
13679: if (@paths > 0) {
13680: $itemcount = scalar(@paths);
13681: } else {
13682: $itemcount = 1;
13683: }
13684: if ($is_camtasia) {
13685: $output .= $lt{'auto'}.'<br />'.
13686: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
13687: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
13688: $lt{'yes'}.'</label> <label>'.
13689: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
13690: $lt{'no'}.'</label></span><br />'.
13691: '<div id="camtasia_titles" style="display:block">'.
13692: &Apache::lonhtmlcommon::start_pick_box().
13693: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
13694: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
13695: &Apache::lonhtmlcommon::row_closure().
13696: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
13697: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
13698: &Apache::lonhtmlcommon::row_closure(1).
13699: &Apache::lonhtmlcommon::end_pick_box().
13700: '</div>';
13701: }
13702: $output .=
13703: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
13704: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
13705: "\n";
13706: if ($duplicates ne '') {
13707: $output .= '<p><span class="LC_warning">'.
13708: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
13709: &start_data_table().
13710: &start_data_table_header_row().
13711: '<th>'.&mt('Overwrite?').'</th>'.
13712: '<th>'.&mt('Name').'</th>'.
13713: '<th>'.&mt('Type').'</th>'.
13714: '<th>'.&mt('Size').'</th>'.
13715: '<th>'.&mt('Last modified').'</th>'.
13716: &end_data_table_header_row().
13717: $duplicates.
13718: &end_data_table().
13719: '</p>';
13720: }
13721: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
13722: if (ref($hiddenelements) eq 'HASH') {
13723: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
13724: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
13725: }
13726: }
13727: $output .= <<"END";
13728: <br />
13729: <input type="submit" name="decompress" value="$lt{'extr'}" />
13730: </form>
13731: $noextract
13732: END
13733: return $output;
13734: }
13735:
13736: sub decompression_utility {
13737: my ($program) = @_;
13738: my @utilities = ('tar','gunzip','bunzip2','unzip');
13739: my $location;
13740: if (grep(/^\Q$program\E$/,@utilities)) {
13741: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
13742: '/usr/sbin/') {
13743: if (-x $dir.$program) {
13744: $location = $dir.$program;
13745: last;
13746: }
13747: }
13748: }
13749: return $location;
13750: }
13751:
13752: sub list_archive_contents {
13753: my ($file,$pathsref) = @_;
13754: my (@cmd,$output);
13755: my $needsregexp;
13756: if ($file =~ /\.zip$/) {
13757: @cmd = (&decompression_utility('unzip'),"-l");
13758: $needsregexp = 1;
13759: } elsif (($file =~ m/\.tar\.gz$/) ||
13760: ($file =~ /\.tgz$/)) {
13761: @cmd = (&decompression_utility('tar'),"-ztf");
13762: } elsif ($file =~ /\.tar\.bz2$/) {
13763: @cmd = (&decompression_utility('tar'),"-jtf");
13764: } elsif ($file =~ m|\.tar$|) {
13765: @cmd = (&decompression_utility('tar'),"-tf");
13766: }
13767: if (@cmd) {
13768: undef($!);
13769: undef($@);
13770: if (open(my $fh,"-|", @cmd, $file)) {
13771: while (my $line = <$fh>) {
13772: $output .= $line;
13773: chomp($line);
13774: my $item;
13775: if ($needsregexp) {
13776: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
13777: } else {
13778: $item = $line;
13779: }
13780: if ($item ne '') {
13781: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
13782: push(@{$pathsref},$item);
13783: }
13784: }
13785: }
13786: close($fh);
13787: }
13788: }
13789: return $output;
13790: }
13791:
13792: sub decompress_uploaded_file {
13793: my ($file,$dir) = @_;
13794: &Apache::lonnet::appenv({'cgi.file' => $file});
13795: &Apache::lonnet::appenv({'cgi.dir' => $dir});
13796: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
13797: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
13798: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
13799: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
13800: my $decompressed = $env{'cgi.decompressed'};
13801: &Apache::lonnet::delenv('cgi.file');
13802: &Apache::lonnet::delenv('cgi.dir');
13803: &Apache::lonnet::delenv('cgi.decompressed');
13804: return ($decompressed,$result);
13805: }
13806:
13807: sub process_decompression {
13808: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
13809: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
13810: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13811: &mt('Unexpected file path.').'</p>'."\n";
13812: }
13813: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
13814: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13815: &mt('Unexpected course context.').'</p>'."\n";
13816: }
13817: unless ($file eq &Apache::lonnet::clean_filename($file)) {
13818: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13819: &mt('Filename contained unexpected characters.').'</p>'."\n";
13820: }
13821: my ($dir,$error,$warning,$output);
13822: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13823: $error = &mt('Filename not a supported archive file type.').
13824: '<br />'.&mt('Filename should end with one of: [_1].',
13825: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13826: } else {
13827: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13828: if ($docuhome eq 'no_host') {
13829: $error = &mt('Could not determine home server for course.');
13830: } else {
13831: my @ids=&Apache::lonnet::current_machine_ids();
13832: my $currdir = "$dir_root/$destination";
13833: if (grep(/^\Q$docuhome\E$/,@ids)) {
13834: $dir = &LONCAPA::propath($docudom,$docuname).
13835: "$dir_root/$destination";
13836: } else {
13837: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13838: "$dir_root/$docudom/$docuname/$destination";
13839: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13840: $error = &mt('Archive file not found.');
13841: }
13842: }
13843: my (@to_overwrite,@to_skip);
13844: if ($env{'form.archive_overwrite_total'} > 0) {
13845: my $total = $env{'form.archive_overwrite_total'};
13846: for (my $i=0; $i<$total; $i++) {
13847: if ($env{'form.archive_overwrite_'.$i} == 1) {
13848: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13849: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13850: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13851: }
13852: }
13853: }
13854: my $numskip = scalar(@to_skip);
13855: my $numoverwrite = scalar(@to_overwrite);
13856: if (($numskip) && (!$numoverwrite)) {
13857: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
13858: } elsif ($dir eq '') {
13859: $error = &mt('Directory containing archive file unavailable.');
13860: } elsif (!$error) {
13861: my ($decompressed,$display);
13862: if (($numskip) || ($numoverwrite)) {
13863: my $tempdir = time.'_'.$$.int(rand(10000));
13864: mkdir("$dir/$tempdir",0755);
13865: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13866: ($decompressed,$display) =
13867: &decompress_uploaded_file($file,"$dir/$tempdir");
13868: foreach my $item (@to_skip) {
13869: if (($item ne '') && ($item !~ /\.\./)) {
13870: if (-f "$dir/$tempdir/$item") {
13871: unlink("$dir/$tempdir/$item");
13872: } elsif (-d "$dir/$tempdir/$item") {
13873: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13874: }
13875: }
13876: }
13877: foreach my $item (@to_overwrite) {
13878: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13879: if (($item ne '') && ($item !~ /\.\./)) {
13880: if (-f "$dir/$item") {
13881: unlink("$dir/$item");
13882: } elsif (-d "$dir/$item") {
13883: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13884: }
13885: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13886: }
13887: }
13888: }
13889: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13890: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13891: }
13892: }
13893: } else {
13894: ($decompressed,$display) =
13895: &decompress_uploaded_file($file,$dir);
13896: }
13897: if ($decompressed eq 'ok') {
13898: $output = '<p class="LC_info">'.
13899: &mt('Files extracted successfully from archive.').
13900: '</p>'."\n";
13901: my ($warning,$result,@contents);
13902: my ($newdirlistref,$newlisterror) =
13903: &Apache::lonnet::dirlist($currdir,$docudom,
13904: $docuname,1);
13905: my (%is_dir,%changes,@newitems);
13906: my $dirptr = 16384;
13907: if (ref($newdirlistref) eq 'ARRAY') {
13908: foreach my $dir_line (@{$newdirlistref}) {
13909: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13910: unless (($item =~ /^\.+$/) || ($item eq $file)) {
13911: push(@newitems,$item);
13912: if ($dirptr&$testdir) {
13913: $is_dir{$item} = 1;
13914: }
13915: $changes{$item} = 1;
13916: }
13917: }
13918: }
13919: if (keys(%changes) > 0) {
13920: foreach my $item (sort(@newitems)) {
13921: if ($changes{$item}) {
13922: push(@contents,$item);
13923: }
13924: }
13925: }
13926: if (@contents > 0) {
13927: my $wantform;
13928: unless ($env{'form.autoextract_camtasia'}) {
13929: $wantform = 1;
13930: }
13931: my (%children,%parent,%dirorder,%titles);
13932: my ($count,$datatable) = &get_extracted($docudom,$docuname,
13933: $currdir,\%is_dir,
13934: \%children,\%parent,
13935: \@contents,\%dirorder,
13936: \%titles,$wantform);
13937: if ($datatable ne '') {
13938: $output .= &archive_options_form('decompressed',$datatable,
13939: $count,$hiddenelem);
13940: my $startcount = 6;
13941: $output .= &archive_javascript($startcount,$count,
13942: \%titles,\%children);
13943: }
13944: if ($env{'form.autoextract_camtasia'}) {
13945: my $version = $env{'form.autoextract_camtasia'};
13946: my %displayed;
13947: my $total = 1;
13948: $env{'form.archive_directory'} = [];
13949: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13950: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13951: $path =~ s{/$}{};
13952: my $item;
13953: if ($path ne '') {
13954: $item = "$path/$titles{$i}";
13955: } else {
13956: $item = $titles{$i};
13957: }
13958: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13959: if ($item eq $contents[0]) {
13960: push(@{$env{'form.archive_directory'}},$i);
13961: $env{'form.archive_'.$i} = 'display';
13962: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13963: $displayed{'folder'} = $i;
13964: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13965: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13966: $env{'form.archive_'.$i} = 'display';
13967: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13968: $displayed{'web'} = $i;
13969: } else {
13970: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13971: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13972: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13973: push(@{$env{'form.archive_directory'}},$i);
13974: }
13975: $env{'form.archive_'.$i} = 'dependency';
13976: }
13977: $total ++;
13978: }
13979: for (my $i=1; $i<$total; $i++) {
13980: next if ($i == $displayed{'web'});
13981: next if ($i == $displayed{'folder'});
13982: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13983: }
13984: $env{'form.phase'} = 'decompress_cleanup';
13985: $env{'form.archivedelete'} = 1;
13986: $env{'form.archive_count'} = $total-1;
13987: $output .=
13988: &process_extracted_files('coursedocs',$docudom,
13989: $docuname,$destination,
13990: $dir_root,$hiddenelem);
13991: }
13992: } else {
13993: $warning = &mt('No new items extracted from archive file.');
13994: }
13995: } else {
13996: $output = $display;
13997: $error = &mt('An error occurred during extraction from the archive file.');
13998: }
13999: }
14000: }
14001: }
14002: if ($error) {
14003: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14004: $error.'</p>'."\n";
14005: }
14006: if ($warning) {
14007: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14008: }
14009: return $output;
14010: }
14011:
14012: sub get_extracted {
14013: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
14014: $titles,$wantform) = @_;
14015: my $count = 0;
14016: my $depth = 0;
14017: my $datatable;
14018: my @hierarchy;
14019: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
14020: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
14021: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
14022: foreach my $item (@{$contents}) {
14023: $count ++;
14024: @{$dirorder->{$count}} = @hierarchy;
14025: $titles->{$count} = $item;
14026: &archive_hierarchy($depth,$count,$parent,$children);
14027: if ($wantform) {
14028: $datatable .= &archive_row($is_dir->{$item},$item,
14029: $currdir,$depth,$count);
14030: }
14031: if ($is_dir->{$item}) {
14032: $depth ++;
14033: push(@hierarchy,$count);
14034: $parent->{$depth} = $count;
14035: $datatable .=
14036: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
14037: \$depth,\$count,\@hierarchy,$dirorder,
14038: $children,$parent,$titles,$wantform);
14039: $depth --;
14040: pop(@hierarchy);
14041: }
14042: }
14043: return ($count,$datatable);
14044: }
14045:
14046: sub recurse_extracted_archive {
14047: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
14048: $children,$parent,$titles,$wantform) = @_;
14049: my $result='';
14050: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
14051: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
14052: (ref($dirorder) eq 'HASH')) {
14053: return $result;
14054: }
14055: my $dirptr = 16384;
14056: my ($newdirlistref,$newlisterror) =
14057: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
14058: if (ref($newdirlistref) eq 'ARRAY') {
14059: foreach my $dir_line (@{$newdirlistref}) {
14060: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
14061: unless ($item =~ /^\.+$/) {
14062: $$count ++;
14063: @{$dirorder->{$$count}} = @{$hierarchy};
14064: $titles->{$$count} = $item;
14065: &archive_hierarchy($$depth,$$count,$parent,$children);
14066:
14067: my $is_dir;
14068: if ($dirptr&$testdir) {
14069: $is_dir = 1;
14070: }
14071: if ($wantform) {
14072: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
14073: }
14074: if ($is_dir) {
14075: $$depth ++;
14076: push(@{$hierarchy},$$count);
14077: $parent->{$$depth} = $$count;
14078: $result .=
14079: &recurse_extracted_archive("$currdir/$item",$docudom,
14080: $docuname,$depth,$count,
14081: $hierarchy,$dirorder,$children,
14082: $parent,$titles,$wantform);
14083: $$depth --;
14084: pop(@{$hierarchy});
14085: }
14086: }
14087: }
14088: }
14089: return $result;
14090: }
14091:
14092: sub archive_hierarchy {
14093: my ($depth,$count,$parent,$children) =@_;
14094: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
14095: if (exists($parent->{$depth})) {
14096: $children->{$parent->{$depth}} .= $count.':';
14097: }
14098: }
14099: return;
14100: }
14101:
14102: sub archive_row {
14103: my ($is_dir,$item,$currdir,$depth,$count) = @_;
14104: my ($name) = ($item =~ m{([^/]+)$});
14105: my %choices = &Apache::lonlocal::texthash (
14106: 'display' => 'Add as file',
14107: 'dependency' => 'Include as dependency',
14108: 'discard' => 'Discard',
14109: );
14110: if ($is_dir) {
14111: $choices{'display'} = &mt('Add as folder');
14112: }
14113: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
14114: my $offset = 0;
14115: foreach my $action ('display','dependency','discard') {
14116: $offset ++;
14117: if ($action ne 'display') {
14118: $offset ++;
14119: }
14120: $output .= '<td><span class="LC_nobreak">'.
14121: '<label><input type="radio" name="archive_'.$count.
14122: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
14123: my $text = $choices{$action};
14124: if ($is_dir) {
14125: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
14126: if ($action eq 'display') {
14127: $text = &mt('Add as folder');
14128: }
14129: } else {
14130: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
14131:
14132: }
14133: $output .= ' /> '.$choices{$action}.'</label></span>';
14134: if ($action eq 'dependency') {
14135: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
14136: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
14137: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
14138: '<option value=""></option>'."\n".
14139: '</select>'."\n".
14140: '</div>';
14141: } elsif ($action eq 'display') {
14142: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
14143: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
14144: '</div>';
14145: }
14146: $output .= '</td>';
14147: }
14148: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
14149: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
14150: for (my $i=0; $i<$depth; $i++) {
14151: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
14152: }
14153: if ($is_dir) {
14154: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
14155: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
14156: } else {
14157: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
14158: }
14159: $output .= ' '.$name.'</td>'."\n".
14160: &end_data_table_row();
14161: return $output;
14162: }
14163:
14164: sub archive_options_form {
14165: my ($form,$display,$count,$hiddenelem) = @_;
14166: my %lt = &Apache::lonlocal::texthash(
14167: perm => 'Permanently remove archive file?',
14168: hows => 'How should each extracted item be incorporated in the course?',
14169: cont => 'Content actions for all',
14170: addf => 'Add as folder/file',
14171: incd => 'Include as dependency for a displayed file',
14172: disc => 'Discard',
14173: no => 'No',
14174: yes => 'Yes',
14175: save => 'Save',
14176: );
14177: my $output = <<"END";
14178: <form name="$form" method="post" action="">
14179: <p><span class="LC_nobreak">$lt{'perm'}
14180: <label>
14181: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
14182: </label>
14183:
14184: <label>
14185: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
14186: </span>
14187: </p>
14188: <input type="hidden" name="phase" value="decompress_cleanup" />
14189: <br />$lt{'hows'}
14190: <div class="LC_columnSection">
14191: <fieldset>
14192: <legend>$lt{'cont'}</legend>
14193: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
14194: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
14195: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
14196: </fieldset>
14197: </div>
14198: END
14199: return $output.
14200: &start_data_table()."\n".
14201: $display."\n".
14202: &end_data_table()."\n".
14203: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
14204: $hiddenelem.
14205: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
14206: '</form>';
14207: }
14208:
14209: sub archive_javascript {
14210: my ($startcount,$numitems,$titles,$children) = @_;
14211: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
14212: my $maintitle = $env{'form.comment'};
14213: my $scripttag = <<START;
14214: <script type="text/javascript">
14215: // <![CDATA[
14216:
14217: function checkAll(form,prefix) {
14218: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
14219: for (var i=0; i < form.elements.length; i++) {
14220: var id = form.elements[i].id;
14221: if ((id != '') && (id != undefined)) {
14222: if (idstr.test(id)) {
14223: if (form.elements[i].type == 'radio') {
14224: form.elements[i].checked = true;
14225: var nostart = i-$startcount;
14226: var offset = nostart%7;
14227: var count = (nostart-offset)/7;
14228: dependencyCheck(form,count,offset);
14229: }
14230: }
14231: }
14232: }
14233: }
14234:
14235: function propagateCheck(form,count) {
14236: if (count > 0) {
14237: var startelement = $startcount + ((count-1) * 7);
14238: for (var j=1; j<6; j++) {
14239: if ((j != 2) && (j != 4)) {
14240: var item = startelement + j;
14241: if (form.elements[item].type == 'radio') {
14242: if (form.elements[item].checked) {
14243: containerCheck(form,count,j);
14244: break;
14245: }
14246: }
14247: }
14248: }
14249: }
14250: }
14251:
14252: numitems = $numitems
14253: var titles = new Array(numitems);
14254: var parents = new Array(numitems);
14255: for (var i=0; i<numitems; i++) {
14256: parents[i] = new Array;
14257: }
14258: var maintitle = '$maintitle';
14259:
14260: START
14261:
14262: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
14263: my @contents = split(/:/,$children->{$container});
14264: for (my $i=0; $i<@contents; $i ++) {
14265: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
14266: }
14267: }
14268:
14269: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
14270: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
14271: }
14272:
14273: $scripttag .= <<END;
14274:
14275: function containerCheck(form,count,offset) {
14276: if (count > 0) {
14277: dependencyCheck(form,count,offset);
14278: var item = (offset+$startcount)+7*(count-1);
14279: form.elements[item].checked = true;
14280: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
14281: if (parents[count].length > 0) {
14282: for (var j=0; j<parents[count].length; j++) {
14283: containerCheck(form,parents[count][j],offset);
14284: }
14285: }
14286: }
14287: }
14288: }
14289:
14290: function dependencyCheck(form,count,offset) {
14291: if (count > 0) {
14292: var chosen = (offset+$startcount)+7*(count-1);
14293: var depitem = $startcount + ((count-1) * 7) + 4;
14294: var currtype = form.elements[depitem].type;
14295: if (form.elements[chosen].value == 'dependency') {
14296: document.getElementById('arc_depon_'+count).style.display='block';
14297: form.elements[depitem].options.length = 0;
14298: form.elements[depitem].options[0] = new Option('Select','',true,true);
14299: for (var i=1; i<=numitems; i++) {
14300: if (i == count) {
14301: continue;
14302: }
14303: var startelement = $startcount + (i-1) * 7;
14304: for (var j=1; j<6; j++) {
14305: if ((j != 2) && (j!= 4)) {
14306: var item = startelement + j;
14307: if (form.elements[item].type == 'radio') {
14308: if (form.elements[item].checked) {
14309: if (form.elements[item].value == 'display') {
14310: var n = form.elements[depitem].options.length;
14311: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
14312: }
14313: }
14314: }
14315: }
14316: }
14317: }
14318: } else {
14319: document.getElementById('arc_depon_'+count).style.display='none';
14320: form.elements[depitem].options.length = 0;
14321: form.elements[depitem].options[0] = new Option('Select','',true,true);
14322: }
14323: titleCheck(form,count,offset);
14324: }
14325: }
14326:
14327: function propagateSelect(form,count,offset) {
14328: if (count > 0) {
14329: var item = (1+offset+$startcount)+7*(count-1);
14330: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
14331: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14332: if (parents[count].length > 0) {
14333: for (var j=0; j<parents[count].length; j++) {
14334: containerSelect(form,parents[count][j],offset,picked);
14335: }
14336: }
14337: }
14338: }
14339: }
14340:
14341: function containerSelect(form,count,offset,picked) {
14342: if (count > 0) {
14343: var item = (offset+$startcount)+7*(count-1);
14344: if (form.elements[item].type == 'radio') {
14345: if (form.elements[item].value == 'dependency') {
14346: if (form.elements[item+1].type == 'select-one') {
14347: for (var i=0; i<form.elements[item+1].options.length; i++) {
14348: if (form.elements[item+1].options[i].value == picked) {
14349: form.elements[item+1].selectedIndex = i;
14350: break;
14351: }
14352: }
14353: }
14354: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
14355: if (parents[count].length > 0) {
14356: for (var j=0; j<parents[count].length; j++) {
14357: containerSelect(form,parents[count][j],offset,picked);
14358: }
14359: }
14360: }
14361: }
14362: }
14363: }
14364: }
14365:
14366: function titleCheck(form,count,offset) {
14367: if (count > 0) {
14368: var chosen = (offset+$startcount)+7*(count-1);
14369: var depitem = $startcount + ((count-1) * 7) + 2;
14370: var currtype = form.elements[depitem].type;
14371: if (form.elements[chosen].value == 'display') {
14372: document.getElementById('arc_title_'+count).style.display='block';
14373: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
14374: document.getElementById('archive_title_'+count).value=maintitle;
14375: }
14376: } else {
14377: document.getElementById('arc_title_'+count).style.display='none';
14378: if (currtype == 'text') {
14379: document.getElementById('archive_title_'+count).value='';
14380: }
14381: }
14382: }
14383: return;
14384: }
14385:
14386: // ]]>
14387: </script>
14388: END
14389: return $scripttag;
14390: }
14391:
14392: sub process_extracted_files {
14393: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
14394: my $numitems = $env{'form.archive_count'};
14395: return if ((!$numitems) || ($numitems =~ /\D/));
14396: my @ids=&Apache::lonnet::current_machine_ids();
14397: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
14398: %folders,%containers,%mapinner,%prompttofetch);
14399: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
14400: if (grep(/^\Q$docuhome\E$/,@ids)) {
14401: $prefix = &LONCAPA::propath($docudom,$docuname);
14402: $pathtocheck = "$dir_root/$destination";
14403: $dir = $dir_root;
14404: $ishome = 1;
14405: } else {
14406: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
14407: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
14408: $dir = "$dir_root/$docudom/$docuname";
14409: }
14410: my $currdir = "$dir_root/$destination";
14411: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
14412: if ($env{'form.folderpath'}) {
14413: my @items = split('&',$env{'form.folderpath'});
14414: $folders{'0'} = $items[-2];
14415: if ($env{'form.folderpath'} =~ /\:1$/) {
14416: $containers{'0'}='page';
14417: } else {
14418: $containers{'0'}='sequence';
14419: }
14420: }
14421: my @archdirs = &get_env_multiple('form.archive_directory');
14422: if ($numitems) {
14423: for (my $i=1; $i<=$numitems; $i++) {
14424: my $path = $env{'form.archive_content_'.$i};
14425: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
14426: my $item = $1;
14427: $toplevelitems{$item} = $i;
14428: if (grep(/^\Q$i\E$/,@archdirs)) {
14429: $is_dir{$item} = 1;
14430: }
14431: }
14432: }
14433: }
14434: my ($output,%children,%parent,%titles,%dirorder,$result);
14435: if (keys(%toplevelitems) > 0) {
14436: my @contents = sort(keys(%toplevelitems));
14437: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
14438: \%parent,\@contents,\%dirorder,\%titles);
14439: }
14440: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
14441: if ($numitems) {
14442: for (my $i=1; $i<=$numitems; $i++) {
14443: next if ($env{'form.archive_'.$i} eq 'dependency');
14444: my $path = $env{'form.archive_content_'.$i};
14445: if ($path =~ /^\Q$pathtocheck\E/) {
14446: if ($env{'form.archive_'.$i} eq 'discard') {
14447: if ($prefix ne '' && $path ne '') {
14448: if (-e $prefix.$path) {
14449: if ((@archdirs > 0) &&
14450: (grep(/^\Q$i\E$/,@archdirs))) {
14451: $todeletedir{$prefix.$path} = 1;
14452: } else {
14453: $todelete{$prefix.$path} = 1;
14454: }
14455: }
14456: }
14457: } elsif ($env{'form.archive_'.$i} eq 'display') {
14458: my ($docstitle,$title,$url,$outer);
14459: ($title) = ($path =~ m{/([^/]+)$});
14460: $docstitle = $env{'form.archive_title_'.$i};
14461: if ($docstitle eq '') {
14462: $docstitle = $title;
14463: }
14464: $outer = 0;
14465: if (ref($dirorder{$i}) eq 'ARRAY') {
14466: if (@{$dirorder{$i}} > 0) {
14467: foreach my $item (reverse(@{$dirorder{$i}})) {
14468: if ($env{'form.archive_'.$item} eq 'display') {
14469: $outer = $item;
14470: last;
14471: }
14472: }
14473: }
14474: }
14475: my ($errtext,$fatal) =
14476: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
14477: '/'.$folders{$outer}.'.'.
14478: $containers{$outer});
14479: next if ($fatal);
14480: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
14481: if ($context eq 'coursedocs') {
14482: $mapinner{$i} = time;
14483: $folders{$i} = 'default_'.$mapinner{$i};
14484: $containers{$i} = 'sequence';
14485: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14486: $folders{$i}.'.'.$containers{$i};
14487: my $newidx = &LONCAPA::map::getresidx();
14488: $LONCAPA::map::resources[$newidx]=
14489: $docstitle.':'.$url.':false:normal:res';
14490: push(@LONCAPA::map::order,$newidx);
14491: my ($outtext,$errtext) =
14492: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14493: $docuname.'/'.$folders{$outer}.
14494: '.'.$containers{$outer},1,1);
14495: $newseqid{$i} = $newidx;
14496: unless ($errtext) {
14497: $result .= '<li>'.&mt('Folder: [_1] added to course',
14498: &HTML::Entities::encode($docstitle,'<>&"')).
14499: '</li>'."\n";
14500: }
14501: }
14502: } else {
14503: if ($context eq 'coursedocs') {
14504: my $newidx=&LONCAPA::map::getresidx();
14505: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
14506: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
14507: $title;
14508: if (($outer !~ /\D/) &&
14509: (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
14510: ($newidx !~ /\D/)) {
14511: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
14512: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
14513: }
14514: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14515: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
14516: }
14517: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
14518: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
14519: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
14520: unless ($ishome) {
14521: my $fetch = "$newdest{$i}/$title";
14522: $fetch =~ s/^\Q$prefix$dir\E//;
14523: $prompttofetch{$fetch} = 1;
14524: }
14525: }
14526: }
14527: $LONCAPA::map::resources[$newidx]=
14528: $docstitle.':'.$url.':false:normal:res';
14529: push(@LONCAPA::map::order, $newidx);
14530: my ($outtext,$errtext)=
14531: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
14532: $docuname.'/'.$folders{$outer}.
14533: '.'.$containers{$outer},1,1);
14534: unless ($errtext) {
14535: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
14536: $result .= '<li>'.&mt('File: [_1] added to course',
14537: &HTML::Entities::encode($docstitle,'<>&"')).
14538: '</li>'."\n";
14539: }
14540: }
14541: } else {
14542: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14543: &HTML::Entities::encode($path,'<>&"')).'<br />';
14544: }
14545: }
14546: }
14547: }
14548: } else {
14549: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14550: &HTML::Entities::encode($path,'<>&"')).'<br />';
14551: }
14552: }
14553: for (my $i=1; $i<=$numitems; $i++) {
14554: next unless ($env{'form.archive_'.$i} eq 'dependency');
14555: my $path = $env{'form.archive_content_'.$i};
14556: if ($path =~ /^\Q$pathtocheck\E/) {
14557: my ($title) = ($path =~ m{/([^/]+)$});
14558: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
14559: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
14560: if (ref($dirorder{$i}) eq 'ARRAY') {
14561: my ($itemidx,$fullpath,$relpath);
14562: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
14563: my $container = $dirorder{$referrer{$i}}->[-1];
14564: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
14565: if ($dirorder{$i}->[$j] eq $container) {
14566: $itemidx = $j;
14567: }
14568: }
14569: }
14570: if ($itemidx eq '') {
14571: $itemidx = 0;
14572: }
14573: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
14574: if ($mapinner{$referrer{$i}}) {
14575: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
14576: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14577: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14578: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14579: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14580: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14581: if (!-e $fullpath) {
14582: mkdir($fullpath,0755);
14583: }
14584: }
14585: } else {
14586: last;
14587: }
14588: }
14589: }
14590: } elsif ($newdest{$referrer{$i}}) {
14591: $fullpath = $newdest{$referrer{$i}};
14592: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
14593: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
14594: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
14595: last;
14596: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
14597: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
14598: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
14599: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
14600: if (!-e $fullpath) {
14601: mkdir($fullpath,0755);
14602: }
14603: }
14604: } else {
14605: last;
14606: }
14607: }
14608: }
14609: if ($fullpath ne '') {
14610: if (-e "$prefix$path") {
14611: unless (rename("$prefix$path","$fullpath/$title")) {
14612: $warning .= &mt('Failed to rename dependency').'<br />';
14613: }
14614: }
14615: if (-e "$fullpath/$title") {
14616: my $showpath;
14617: if ($relpath ne '') {
14618: $showpath = "$relpath/$title";
14619: } else {
14620: $showpath = "/$title";
14621: }
14622: $result .= '<li>'.&mt('[_1] included as a dependency',
14623: &HTML::Entities::encode($showpath,'<>&"')).
14624: '</li>'."\n";
14625: unless ($ishome) {
14626: my $fetch = "$fullpath/$title";
14627: $fetch =~ s/^\Q$prefix$dir\E//;
14628: $prompttofetch{$fetch} = 1;
14629: }
14630: }
14631: }
14632: }
14633: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
14634: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
14635: &HTML::Entities::encode($path,'<>&"'),
14636: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
14637: '<br />';
14638: }
14639: } else {
14640: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
14641: &HTML::Entities::encode($path)).'<br />';
14642: }
14643: }
14644: if (keys(%todelete)) {
14645: foreach my $key (keys(%todelete)) {
14646: unlink($key);
14647: }
14648: }
14649: if (keys(%todeletedir)) {
14650: foreach my $key (keys(%todeletedir)) {
14651: rmdir($key);
14652: }
14653: }
14654: foreach my $dir (sort(keys(%is_dir))) {
14655: if (($pathtocheck ne '') && ($dir ne '')) {
14656: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
14657: }
14658: }
14659: if ($result ne '') {
14660: $output .= '<ul>'."\n".
14661: $result."\n".
14662: '</ul>';
14663: }
14664: unless ($ishome) {
14665: my $replicationfail;
14666: foreach my $item (keys(%prompttofetch)) {
14667: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
14668: unless ($fetchresult eq 'ok') {
14669: $replicationfail .= '<li>'.$item.'</li>'."\n";
14670: }
14671: }
14672: if ($replicationfail) {
14673: $output .= '<p class="LC_error">'.
14674: &mt('Course home server failed to retrieve:').'<ul>'.
14675: $replicationfail.
14676: '</ul></p>';
14677: }
14678: }
14679: } else {
14680: $warning = &mt('No items found in archive.');
14681: }
14682: if ($error) {
14683: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
14684: $error.'</p>'."\n";
14685: }
14686: if ($warning) {
14687: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
14688: }
14689: return $output;
14690: }
14691:
14692: sub cleanup_empty_dirs {
14693: my ($path) = @_;
14694: if (($path ne '') && (-d $path)) {
14695: if (opendir(my $dirh,$path)) {
14696: my @dircontents = grep(!/^\./,readdir($dirh));
14697: my $numitems = 0;
14698: foreach my $item (@dircontents) {
14699: if (-d "$path/$item") {
14700: &cleanup_empty_dirs("$path/$item");
14701: if (-e "$path/$item") {
14702: $numitems ++;
14703: }
14704: } else {
14705: $numitems ++;
14706: }
14707: }
14708: if ($numitems == 0) {
14709: rmdir($path);
14710: }
14711: closedir($dirh);
14712: }
14713: }
14714: return;
14715: }
14716:
14717: =pod
14718:
14719: =item * &get_folder_hierarchy()
14720:
14721: Provides hierarchy of names of folders/sub-folders containing the current
14722: item,
14723:
14724: Inputs: 3
14725: - $navmap - navmaps object
14726:
14727: - $map - url for map (either the trigger itself, or map containing
14728: the resource, which is the trigger).
14729:
14730: - $showitem - 1 => show title for map itself; 0 => do not show.
14731:
14732: Outputs: 1 @pathitems - array of folder/subfolder names.
14733:
14734: =cut
14735:
14736: sub get_folder_hierarchy {
14737: my ($navmap,$map,$showitem) = @_;
14738: my @pathitems;
14739: if (ref($navmap)) {
14740: my $mapres = $navmap->getResourceByUrl($map);
14741: if (ref($mapres)) {
14742: my $pcslist = $mapres->map_hierarchy();
14743: if ($pcslist ne '') {
14744: my @pcs = split(/,/,$pcslist);
14745: foreach my $pc (@pcs) {
14746: if ($pc == 1) {
14747: push(@pathitems,&mt('Main Content'));
14748: } else {
14749: my $res = $navmap->getByMapPc($pc);
14750: if (ref($res)) {
14751: my $title = $res->compTitle();
14752: $title =~ s/\W+/_/g;
14753: if ($title ne '') {
14754: push(@pathitems,$title);
14755: }
14756: }
14757: }
14758: }
14759: }
14760: if ($showitem) {
14761: if ($mapres->{ID} eq '0.0') {
14762: push(@pathitems,&mt('Main Content'));
14763: } else {
14764: my $maptitle = $mapres->compTitle();
14765: $maptitle =~ s/\W+/_/g;
14766: if ($maptitle ne '') {
14767: push(@pathitems,$maptitle);
14768: }
14769: }
14770: }
14771: }
14772: }
14773: return @pathitems;
14774: }
14775:
14776: =pod
14777:
14778: =item * &get_turnedin_filepath()
14779:
14780: Determines path in a user's portfolio file for storage of files uploaded
14781: to a specific essayresponse or dropbox item.
14782:
14783: Inputs: 3 required + 1 optional.
14784: $symb is symb for resource, $uname and $udom are for current user (required).
14785: $caller is optional (can be "submission", if routine is called when storing
14786: an upoaded file when "Submit Answer" button was pressed).
14787:
14788: Returns array containing $path and $multiresp.
14789: $path is path in portfolio. $multiresp is 1 if this resource contains more
14790: than one file upload item. Callers of routine should append partid as a
14791: subdirectory to $path in cases where $multiresp is 1.
14792:
14793: Called by: homework/essayresponse.pm and homework/structuretags.pm
14794:
14795: =cut
14796:
14797: sub get_turnedin_filepath {
14798: my ($symb,$uname,$udom,$caller) = @_;
14799: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
14800: my $turnindir;
14801: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
14802: $turnindir = $userhash{'turnindir'};
14803: my ($path,$multiresp);
14804: if ($turnindir eq '') {
14805: if ($caller eq 'submission') {
14806: $turnindir = &mt('turned in');
14807: $turnindir =~ s/\W+/_/g;
14808: my %newhash = (
14809: 'turnindir' => $turnindir,
14810: );
14811: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
14812: }
14813: }
14814: if ($turnindir ne '') {
14815: $path = '/'.$turnindir.'/';
14816: my ($multipart,$turnin,@pathitems);
14817: my $navmap = Apache::lonnavmaps::navmap->new();
14818: if (defined($navmap)) {
14819: my $mapres = $navmap->getResourceByUrl($map);
14820: if (ref($mapres)) {
14821: my $pcslist = $mapres->map_hierarchy();
14822: if ($pcslist ne '') {
14823: foreach my $pc (split(/,/,$pcslist)) {
14824: my $res = $navmap->getByMapPc($pc);
14825: if (ref($res)) {
14826: my $title = $res->compTitle();
14827: $title =~ s/\W+/_/g;
14828: if ($title ne '') {
14829: if (($pc > 1) && (length($title) > 12)) {
14830: $title = substr($title,0,12);
14831: }
14832: push(@pathitems,$title);
14833: }
14834: }
14835: }
14836: }
14837: my $maptitle = $mapres->compTitle();
14838: $maptitle =~ s/\W+/_/g;
14839: if ($maptitle ne '') {
14840: if (length($maptitle) > 12) {
14841: $maptitle = substr($maptitle,0,12);
14842: }
14843: push(@pathitems,$maptitle);
14844: }
14845: unless ($env{'request.state'} eq 'construct') {
14846: my $res = $navmap->getBySymb($symb);
14847: if (ref($res)) {
14848: my $partlist = $res->parts();
14849: my $totaluploads = 0;
14850: if (ref($partlist) eq 'ARRAY') {
14851: foreach my $part (@{$partlist}) {
14852: my @types = $res->responseType($part);
14853: my @ids = $res->responseIds($part);
14854: for (my $i=0; $i < scalar(@ids); $i++) {
14855: if ($types[$i] eq 'essay') {
14856: my $partid = $part.'_'.$ids[$i];
14857: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14858: $totaluploads ++;
14859: }
14860: }
14861: }
14862: }
14863: if ($totaluploads > 1) {
14864: $multiresp = 1;
14865: }
14866: }
14867: }
14868: }
14869: } else {
14870: return;
14871: }
14872: } else {
14873: return;
14874: }
14875: my $restitle=&Apache::lonnet::gettitle($symb);
14876: $restitle =~ s/\W+/_/g;
14877: if ($restitle eq '') {
14878: $restitle = ($resurl =~ m{/[^/]+$});
14879: if ($restitle eq '') {
14880: $restitle = time;
14881: }
14882: }
14883: if (length($restitle) > 12) {
14884: $restitle = substr($restitle,0,12);
14885: }
14886: push(@pathitems,$restitle);
14887: $path .= join('/',@pathitems);
14888: }
14889: return ($path,$multiresp);
14890: }
14891:
14892: =pod
14893:
14894: =back
14895:
14896: =head1 CSV Upload/Handling functions
14897:
14898: =over 4
14899:
14900: =item * &upfile_store($r)
14901:
14902: Store uploaded file, $r should be the HTTP Request object,
14903: needs $env{'form.upfile'}
14904: returns $datatoken to be put into hidden field
14905:
14906: =cut
14907:
14908: sub upfile_store {
14909: my $r=shift;
14910: $env{'form.upfile'}=~s/\r/\n/gs;
14911: $env{'form.upfile'}=~s/\f/\n/gs;
14912: $env{'form.upfile'}=~s/\n+/\n/gs;
14913: $env{'form.upfile'}=~s/\n+$//gs;
14914:
14915: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14916: '_enroll_'.$env{'request.course.id'}.'_'.
14917: time.'_'.$$);
14918: return if ($datatoken eq '');
14919:
14920: {
14921: my $datafile = $r->dir_config('lonDaemons').
14922: '/tmp/'.$datatoken.'.tmp';
14923: if ( open(my $fh,'>',$datafile) ) {
14924: print $fh $env{'form.upfile'};
14925: close($fh);
14926: }
14927: }
14928: return $datatoken;
14929: }
14930:
14931: =pod
14932:
14933: =item * &load_tmp_file($r,$datatoken)
14934:
14935: Load uploaded file from tmp, $r should be the HTTP Request object,
14936: $datatoken is the name to assign to the temporary file.
14937: sets $env{'form.upfile'} to the contents of the file
14938:
14939: =cut
14940:
14941: sub load_tmp_file {
14942: my ($r,$datatoken) = @_;
14943: return if ($datatoken eq '');
14944: my @studentdata=();
14945: {
14946: my $studentfile = $r->dir_config('lonDaemons').
14947: '/tmp/'.$datatoken.'.tmp';
14948: if ( open(my $fh,'<',$studentfile) ) {
14949: @studentdata=<$fh>;
14950: close($fh);
14951: }
14952: }
14953: $env{'form.upfile'}=join('',@studentdata);
14954: }
14955:
14956: sub valid_datatoken {
14957: my ($datatoken) = @_;
14958: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14959: return $datatoken;
14960: }
14961: return;
14962: }
14963:
14964: =pod
14965:
14966: =item * &upfile_record_sep()
14967:
14968: Separate uploaded file into records
14969: returns array of records,
14970: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14971:
14972: =cut
14973:
14974: sub upfile_record_sep {
14975: if ($env{'form.upfiletype'} eq 'xml') {
14976: } else {
14977: my @records;
14978: foreach my $line (split(/\n/,$env{'form.upfile'})) {
14979: if ($line=~/^\s*$/) { next; }
14980: push(@records,$line);
14981: }
14982: return @records;
14983: }
14984: }
14985:
14986: =pod
14987:
14988: =item * &record_sep($record)
14989:
14990: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14991:
14992: =cut
14993:
14994: sub takeleft {
14995: my $index=shift;
14996: return substr('0000'.$index,-4,4);
14997: }
14998:
14999: sub record_sep {
15000: my $record=shift;
15001: my %components=();
15002: if ($env{'form.upfiletype'} eq 'xml') {
15003: } elsif ($env{'form.upfiletype'} eq 'space') {
15004: my $i=0;
15005: foreach my $field (split(/\s+/,$record)) {
15006: $field=~s/^(\"|\')//;
15007: $field=~s/(\"|\')$//;
15008: $components{&takeleft($i)}=$field;
15009: $i++;
15010: }
15011: } elsif ($env{'form.upfiletype'} eq 'tab') {
15012: my $i=0;
15013: foreach my $field (split(/\t/,$record)) {
15014: $field=~s/^(\"|\')//;
15015: $field=~s/(\"|\')$//;
15016: $components{&takeleft($i)}=$field;
15017: $i++;
15018: }
15019: } else {
15020: my $separator=',';
15021: if ($env{'form.upfiletype'} eq 'semisv') {
15022: $separator=';';
15023: }
15024: my $i=0;
15025: # the character we are looking for to indicate the end of a quote or a record
15026: my $looking_for=$separator;
15027: # do not add the characters to the fields
15028: my $ignore=0;
15029: # we just encountered a separator (or the beginning of the record)
15030: my $just_found_separator=1;
15031: # store the field we are working on here
15032: my $field='';
15033: # work our way through all characters in record
15034: foreach my $character ($record=~/(.)/g) {
15035: if ($character eq $looking_for) {
15036: if ($character ne $separator) {
15037: # Found the end of a quote, again looking for separator
15038: $looking_for=$separator;
15039: $ignore=1;
15040: } else {
15041: # Found a separator, store away what we got
15042: $components{&takeleft($i)}=$field;
15043: $i++;
15044: $just_found_separator=1;
15045: $ignore=0;
15046: $field='';
15047: }
15048: next;
15049: }
15050: # single or double quotation marks after a separator indicate beginning of a quote
15051: # we are now looking for the end of the quote and need to ignore separators
15052: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
15053: $looking_for=$character;
15054: next;
15055: }
15056: # ignore would be true after we reached the end of a quote
15057: if ($ignore) { next; }
15058: if (($just_found_separator) && ($character=~/\s/)) { next; }
15059: $field.=$character;
15060: $just_found_separator=0;
15061: }
15062: # catch the very last entry, since we never encountered the separator
15063: $components{&takeleft($i)}=$field;
15064: }
15065: return %components;
15066: }
15067:
15068: ######################################################
15069: ######################################################
15070:
15071: =pod
15072:
15073: =item * &upfile_select_html()
15074:
15075: Return HTML code to select a file from the users machine and specify
15076: the file type.
15077:
15078: =cut
15079:
15080: ######################################################
15081: ######################################################
15082: sub upfile_select_html {
15083: my %Types = (
15084: csv => &mt('CSV (comma separated values, spreadsheet)'),
15085: semisv => &mt('Semicolon separated values'),
15086: space => &mt('Space separated'),
15087: tab => &mt('Tabulator separated'),
15088: # xml => &mt('HTML/XML'),
15089: );
15090: my $Str = '<input type="file" name="upfile" size="50" />'.
15091: '<br />'.&mt('Type').': <select name="upfiletype">';
15092: foreach my $type (sort(keys(%Types))) {
15093: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
15094: }
15095: $Str .= "</select>\n";
15096: return $Str;
15097: }
15098:
15099: sub get_samples {
15100: my ($records,$toget) = @_;
15101: my @samples=({});
15102: my $got=0;
15103: foreach my $rec (@$records) {
15104: my %temp = &record_sep($rec);
15105: if (! grep(/\S/, values(%temp))) { next; }
15106: if (%temp) {
15107: $samples[$got]=\%temp;
15108: $got++;
15109: if ($got == $toget) { last; }
15110: }
15111: }
15112: return \@samples;
15113: }
15114:
15115: ######################################################
15116: ######################################################
15117:
15118: =pod
15119:
15120: =item * &csv_print_samples($r,$records)
15121:
15122: Prints a table of sample values from each column uploaded $r is an
15123: Apache Request ref, $records is an arrayref from
15124: &Apache::loncommon::upfile_record_sep
15125:
15126: =cut
15127:
15128: ######################################################
15129: ######################################################
15130: sub csv_print_samples {
15131: my ($r,$records) = @_;
15132: my $samples = &get_samples($records,5);
15133:
15134: $r->print(&mt('Samples').'<br />'.&start_data_table().
15135: &start_data_table_header_row());
15136: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15137: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
15138: $r->print(&end_data_table_header_row());
15139: foreach my $hash (@$samples) {
15140: $r->print(&start_data_table_row());
15141: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15142: $r->print('<td>');
15143: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
15144: $r->print('</td>');
15145: }
15146: $r->print(&end_data_table_row());
15147: }
15148: $r->print(&end_data_table().'<br />'."\n");
15149: }
15150:
15151: ######################################################
15152: ######################################################
15153:
15154: =pod
15155:
15156: =item * &csv_print_select_table($r,$records,$d)
15157:
15158: Prints a table to create associations between values and table columns.
15159:
15160: $r is an Apache Request ref,
15161: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15162: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
15163:
15164: =cut
15165:
15166: ######################################################
15167: ######################################################
15168: sub csv_print_select_table {
15169: my ($r,$records,$d) = @_;
15170: my $i=0;
15171: my $samples = &get_samples($records,1);
15172: $r->print(&mt('Associate columns with student attributes.')."\n".
15173: &start_data_table().&start_data_table_header_row().
15174: '<th>'.&mt('Attribute').'</th>'.
15175: '<th>'.&mt('Column').'</th>'.
15176: &end_data_table_header_row()."\n");
15177: foreach my $array_ref (@$d) {
15178: my ($value,$display,$defaultcol)=@{ $array_ref };
15179: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
15180:
15181: $r->print('<td><select name="f'.$i.'"'.
15182: ' onchange="javascript:flip(this.form,'.$i.');">');
15183: $r->print('<option value="none"></option>');
15184: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
15185: $r->print('<option value="'.$sample.'"'.
15186: ($sample eq $defaultcol ? ' selected="selected" ' : '').
15187: '>'.&mt('Column [_1]',($sample+1)).'</option>');
15188: }
15189: $r->print('</select></td>'.&end_data_table_row()."\n");
15190: $i++;
15191: }
15192: $r->print(&end_data_table());
15193: $i--;
15194: return $i;
15195: }
15196:
15197: ######################################################
15198: ######################################################
15199:
15200: =pod
15201:
15202: =item * &csv_samples_select_table($r,$records,$d)
15203:
15204: Prints a table of sample values from the upload and can make associate samples to internal names.
15205:
15206: $r is an Apache Request ref,
15207: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
15208: $d is an array of 2 element arrays (internal name, displayed name)
15209:
15210: =cut
15211:
15212: ######################################################
15213: ######################################################
15214: sub csv_samples_select_table {
15215: my ($r,$records,$d) = @_;
15216: my $i=0;
15217: #
15218: my $max_samples = 5;
15219: my $samples = &get_samples($records,$max_samples);
15220: $r->print(&start_data_table().
15221: &start_data_table_header_row().'<th>'.
15222: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
15223: &end_data_table_header_row());
15224:
15225: foreach my $key (sort(keys(%{ $samples->[0] }))) {
15226: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
15227: ' onchange="javascript:flip(this.form,'.$i.');">');
15228: foreach my $option (@$d) {
15229: my ($value,$display,$defaultcol)=@{ $option };
15230: $r->print('<option value="'.$value.'"'.
15231: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
15232: $display.'</option>');
15233: }
15234: $r->print('</select></td><td>');
15235: foreach my $line (0..($max_samples-1)) {
15236: if (defined($samples->[$line]{$key})) {
15237: $r->print($samples->[$line]{$key}."<br />\n");
15238: }
15239: }
15240: $r->print('</td>'.&end_data_table_row());
15241: $i++;
15242: }
15243: $r->print(&end_data_table());
15244: $i--;
15245: return($i);
15246: }
15247:
15248: ######################################################
15249: ######################################################
15250:
15251: =pod
15252:
15253: =item * &clean_excel_name($name)
15254:
15255: Returns a replacement for $name which does not contain any illegal characters.
15256:
15257: =cut
15258:
15259: ######################################################
15260: ######################################################
15261: sub clean_excel_name {
15262: my ($name) = @_;
15263: $name =~ s/[:\*\?\/\\]//g;
15264: if (length($name) > 31) {
15265: $name = substr($name,0,31);
15266: }
15267: return $name;
15268: }
15269:
15270: =pod
15271:
15272: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
15273:
15274: Returns either 1 or undef
15275:
15276: 1 if the part is to be hidden, undef if it is to be shown
15277:
15278: Arguments are:
15279:
15280: $id the id of the part to be checked
15281: $symb, optional the symb of the resource to check
15282: $udom, optional the domain of the user to check for
15283: $uname, optional the username of the user to check for
15284:
15285: =cut
15286:
15287: sub check_if_partid_hidden {
15288: my ($id,$symb,$udom,$uname) = @_;
15289: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
15290: $symb,$udom,$uname);
15291: my $truth=1;
15292: #if the string starts with !, then the list is the list to show not hide
15293: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
15294: my @hiddenlist=split(/,/,$hiddenparts);
15295: foreach my $checkid (@hiddenlist) {
15296: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
15297: }
15298: return !$truth;
15299: }
15300:
15301:
15302: ############################################################
15303: ############################################################
15304:
15305: =pod
15306:
15307: =back
15308:
15309: =head1 cgi-bin script and graphing routines
15310:
15311: =over 4
15312:
15313: =item * &get_cgi_id()
15314:
15315: Inputs: none
15316:
15317: Returns an id which can be used to pass environment variables
15318: to various cgi-bin scripts. These environment variables will
15319: be removed from the users environment after a given time by
15320: the routine &Apache::lonnet::transfer_profile_to_env.
15321:
15322: =cut
15323:
15324: ############################################################
15325: ############################################################
15326: my $uniq=0;
15327: sub get_cgi_id {
15328: $uniq=($uniq+1)%100000;
15329: return (time.'_'.$$.'_'.$uniq);
15330: }
15331:
15332: ############################################################
15333: ############################################################
15334:
15335: =pod
15336:
15337: =item * &DrawBarGraph()
15338:
15339: Facilitates the plotting of data in a (stacked) bar graph.
15340: Puts plot definition data into the users environment in order for
15341: graph.png to plot it. Returns an <img> tag for the plot.
15342: The bars on the plot are labeled '1','2',...,'n'.
15343:
15344: Inputs:
15345:
15346: =over 4
15347:
15348: =item $Title: string, the title of the plot
15349:
15350: =item $xlabel: string, text describing the X-axis of the plot
15351:
15352: =item $ylabel: string, text describing the Y-axis of the plot
15353:
15354: =item $Max: scalar, the maximum Y value to use in the plot
15355: If $Max is < any data point, the graph will not be rendered.
15356:
15357: =item $colors: array ref holding the colors to be used for the data sets when
15358: they are plotted. If undefined, default values will be used.
15359:
15360: =item $labels: array ref holding the labels to use on the x-axis for the bars.
15361:
15362: =item @Values: An array of array references. Each array reference holds data
15363: to be plotted in a stacked bar chart.
15364:
15365: =item If the final element of @Values is a hash reference the key/value
15366: pairs will be added to the graph definition.
15367:
15368: =back
15369:
15370: Returns:
15371:
15372: An <img> tag which references graph.png and the appropriate identifying
15373: information for the plot.
15374:
15375: =cut
15376:
15377: ############################################################
15378: ############################################################
15379: sub DrawBarGraph {
15380: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
15381: #
15382: if (! defined($colors)) {
15383: $colors = ['#33ff00',
15384: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
15385: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
15386: ];
15387: }
15388: my $extra_settings = {};
15389: if (ref($Values[-1]) eq 'HASH') {
15390: $extra_settings = pop(@Values);
15391: }
15392: #
15393: my $identifier = &get_cgi_id();
15394: my $id = 'cgi.'.$identifier;
15395: if (! @Values || ref($Values[0]) ne 'ARRAY') {
15396: return '';
15397: }
15398: #
15399: my @Labels;
15400: if (defined($labels)) {
15401: @Labels = @$labels;
15402: } else {
15403: for (my $i=0;$i<@{$Values[0]};$i++) {
15404: push(@Labels,$i+1);
15405: }
15406: }
15407: #
15408: my $NumBars = scalar(@{$Values[0]});
15409: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
15410: my %ValuesHash;
15411: my $NumSets=1;
15412: foreach my $array (@Values) {
15413: next if (! ref($array));
15414: $ValuesHash{$id.'.data.'.$NumSets++} =
15415: join(',',@$array);
15416: }
15417: #
15418: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
15419: if ($NumBars < 3) {
15420: $width = 120+$NumBars*32;
15421: $xskip = 1;
15422: $bar_width = 30;
15423: } elsif ($NumBars < 5) {
15424: $width = 120+$NumBars*20;
15425: $xskip = 1;
15426: $bar_width = 20;
15427: } elsif ($NumBars < 10) {
15428: $width = 120+$NumBars*15;
15429: $xskip = 1;
15430: $bar_width = 15;
15431: } elsif ($NumBars <= 25) {
15432: $width = 120+$NumBars*11;
15433: $xskip = 5;
15434: $bar_width = 8;
15435: } elsif ($NumBars <= 50) {
15436: $width = 120+$NumBars*8;
15437: $xskip = 5;
15438: $bar_width = 4;
15439: } else {
15440: $width = 120+$NumBars*8;
15441: $xskip = 5;
15442: $bar_width = 4;
15443: }
15444: #
15445: $Max = 1 if ($Max < 1);
15446: if ( int($Max) < $Max ) {
15447: $Max++;
15448: $Max = int($Max);
15449: }
15450: $Title = '' if (! defined($Title));
15451: $xlabel = '' if (! defined($xlabel));
15452: $ylabel = '' if (! defined($ylabel));
15453: $ValuesHash{$id.'.title'} = &escape($Title);
15454: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
15455: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
15456: $ValuesHash{$id.'.y_max_value'} = $Max;
15457: $ValuesHash{$id.'.NumBars'} = $NumBars;
15458: $ValuesHash{$id.'.NumSets'} = $NumSets;
15459: $ValuesHash{$id.'.PlotType'} = 'bar';
15460: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15461: $ValuesHash{$id.'.height'} = $height;
15462: $ValuesHash{$id.'.width'} = $width;
15463: $ValuesHash{$id.'.xskip'} = $xskip;
15464: $ValuesHash{$id.'.bar_width'} = $bar_width;
15465: $ValuesHash{$id.'.labels'} = join(',',@Labels);
15466: #
15467: # Deal with other parameters
15468: while (my ($key,$value) = each(%$extra_settings)) {
15469: $ValuesHash{$id.'.'.$key} = $value;
15470: }
15471: #
15472: &Apache::lonnet::appenv(\%ValuesHash);
15473: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15474: }
15475:
15476: ############################################################
15477: ############################################################
15478:
15479: =pod
15480:
15481: =item * &DrawXYGraph()
15482:
15483: Facilitates the plotting of data in an XY graph.
15484: Puts plot definition data into the users environment in order for
15485: graph.png to plot it. Returns an <img> tag for the plot.
15486:
15487: Inputs:
15488:
15489: =over 4
15490:
15491: =item $Title: string, the title of the plot
15492:
15493: =item $xlabel: string, text describing the X-axis of the plot
15494:
15495: =item $ylabel: string, text describing the Y-axis of the plot
15496:
15497: =item $Max: scalar, the maximum Y value to use in the plot
15498: If $Max is < any data point, the graph will not be rendered.
15499:
15500: =item $colors: Array ref containing the hex color codes for the data to be
15501: plotted in. If undefined, default values will be used.
15502:
15503: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15504:
15505: =item $Ydata: Array ref containing Array refs.
15506: Each of the contained arrays will be plotted as a separate curve.
15507:
15508: =item %Values: hash indicating or overriding any default values which are
15509: passed to graph.png.
15510: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15511:
15512: =back
15513:
15514: Returns:
15515:
15516: An <img> tag which references graph.png and the appropriate identifying
15517: information for the plot.
15518:
15519: =cut
15520:
15521: ############################################################
15522: ############################################################
15523: sub DrawXYGraph {
15524: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
15525: #
15526: # Create the identifier for the graph
15527: my $identifier = &get_cgi_id();
15528: my $id = 'cgi.'.$identifier;
15529: #
15530: $Title = '' if (! defined($Title));
15531: $xlabel = '' if (! defined($xlabel));
15532: $ylabel = '' if (! defined($ylabel));
15533: my %ValuesHash =
15534: (
15535: $id.'.title' => &escape($Title),
15536: $id.'.xlabel' => &escape($xlabel),
15537: $id.'.ylabel' => &escape($ylabel),
15538: $id.'.y_max_value'=> $Max,
15539: $id.'.labels' => join(',',@$Xlabels),
15540: $id.'.PlotType' => 'XY',
15541: );
15542: #
15543: if (defined($colors) && ref($colors) eq 'ARRAY') {
15544: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15545: }
15546: #
15547: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
15548: return '';
15549: }
15550: my $NumSets=1;
15551: foreach my $array (@{$Ydata}){
15552: next if (! ref($array));
15553: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15554: }
15555: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
15556: #
15557: # Deal with other parameters
15558: while (my ($key,$value) = each(%Values)) {
15559: $ValuesHash{$id.'.'.$key} = $value;
15560: }
15561: #
15562: &Apache::lonnet::appenv(\%ValuesHash);
15563: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15564: }
15565:
15566: ############################################################
15567: ############################################################
15568:
15569: =pod
15570:
15571: =item * &DrawXYYGraph()
15572:
15573: Facilitates the plotting of data in an XY graph with two Y axes.
15574: Puts plot definition data into the users environment in order for
15575: graph.png to plot it. Returns an <img> tag for the plot.
15576:
15577: Inputs:
15578:
15579: =over 4
15580:
15581: =item $Title: string, the title of the plot
15582:
15583: =item $xlabel: string, text describing the X-axis of the plot
15584:
15585: =item $ylabel: string, text describing the Y-axis of the plot
15586:
15587: =item $colors: Array ref containing the hex color codes for the data to be
15588: plotted in. If undefined, default values will be used.
15589:
15590: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
15591:
15592: =item $Ydata1: The first data set
15593:
15594: =item $Min1: The minimum value of the left Y-axis
15595:
15596: =item $Max1: The maximum value of the left Y-axis
15597:
15598: =item $Ydata2: The second data set
15599:
15600: =item $Min2: The minimum value of the right Y-axis
15601:
15602: =item $Max2: The maximum value of the left Y-axis
15603:
15604: =item %Values: hash indicating or overriding any default values which are
15605: passed to graph.png.
15606: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
15607:
15608: =back
15609:
15610: Returns:
15611:
15612: An <img> tag which references graph.png and the appropriate identifying
15613: information for the plot.
15614:
15615: =cut
15616:
15617: ############################################################
15618: ############################################################
15619: sub DrawXYYGraph {
15620: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
15621: $Ydata2,$Min2,$Max2,%Values)=@_;
15622: #
15623: # Create the identifier for the graph
15624: my $identifier = &get_cgi_id();
15625: my $id = 'cgi.'.$identifier;
15626: #
15627: $Title = '' if (! defined($Title));
15628: $xlabel = '' if (! defined($xlabel));
15629: $ylabel = '' if (! defined($ylabel));
15630: my %ValuesHash =
15631: (
15632: $id.'.title' => &escape($Title),
15633: $id.'.xlabel' => &escape($xlabel),
15634: $id.'.ylabel' => &escape($ylabel),
15635: $id.'.labels' => join(',',@$Xlabels),
15636: $id.'.PlotType' => 'XY',
15637: $id.'.NumSets' => 2,
15638: $id.'.two_axes' => 1,
15639: $id.'.y1_max_value' => $Max1,
15640: $id.'.y1_min_value' => $Min1,
15641: $id.'.y2_max_value' => $Max2,
15642: $id.'.y2_min_value' => $Min2,
15643: );
15644: #
15645: if (defined($colors) && ref($colors) eq 'ARRAY') {
15646: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
15647: }
15648: #
15649: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
15650: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
15651: return '';
15652: }
15653: my $NumSets=1;
15654: foreach my $array ($Ydata1,$Ydata2){
15655: next if (! ref($array));
15656: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
15657: }
15658: #
15659: # Deal with other parameters
15660: while (my ($key,$value) = each(%Values)) {
15661: $ValuesHash{$id.'.'.$key} = $value;
15662: }
15663: #
15664: &Apache::lonnet::appenv(\%ValuesHash);
15665: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
15666: }
15667:
15668: ############################################################
15669: ############################################################
15670:
15671: =pod
15672:
15673: =back
15674:
15675: =head1 Statistics helper routines?
15676:
15677: Bad place for them but what the hell.
15678:
15679: =over 4
15680:
15681: =item * &chartlink()
15682:
15683: Returns a link to the chart for a specific student.
15684:
15685: Inputs:
15686:
15687: =over 4
15688:
15689: =item $linktext: The text of the link
15690:
15691: =item $sname: The students username
15692:
15693: =item $sdomain: The students domain
15694:
15695: =back
15696:
15697: =back
15698:
15699: =cut
15700:
15701: ############################################################
15702: ############################################################
15703: sub chartlink {
15704: my ($linktext, $sname, $sdomain) = @_;
15705: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
15706: '&SelectedStudent='.&escape($sname.':'.$sdomain).
15707: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
15708: '">'.$linktext.'</a>';
15709: }
15710:
15711: #######################################################
15712: #######################################################
15713:
15714: =pod
15715:
15716: =head1 Course Environment Routines
15717:
15718: =over 4
15719:
15720: =item * &restore_course_settings()
15721:
15722: =item * &store_course_settings()
15723:
15724: Restores/Store indicated form parameters from the course environment.
15725: Will not overwrite existing values of the form parameters.
15726:
15727: Inputs:
15728: a scalar describing the data (e.g. 'chart', 'problem_analysis')
15729:
15730: a hash ref describing the data to be stored. For example:
15731:
15732: %Save_Parameters = ('Status' => 'scalar',
15733: 'chartoutputmode' => 'scalar',
15734: 'chartoutputdata' => 'scalar',
15735: 'Section' => 'array',
15736: 'Group' => 'array',
15737: 'StudentData' => 'array',
15738: 'Maps' => 'array');
15739:
15740: Returns: both routines return nothing
15741:
15742: =back
15743:
15744: =cut
15745:
15746: #######################################################
15747: #######################################################
15748: sub store_course_settings {
15749: return &store_settings($env{'request.course.id'},@_);
15750: }
15751:
15752: sub store_settings {
15753: # save to the environment
15754: # appenv the same items, just to be safe
15755: my $udom = $env{'user.domain'};
15756: my $uname = $env{'user.name'};
15757: my ($context,$prefix,$Settings) = @_;
15758: my %SaveHash;
15759: my %AppHash;
15760: while (my ($setting,$type) = each(%$Settings)) {
15761: my $basename = join('.','internal',$context,$prefix,$setting);
15762: my $envname = 'environment.'.$basename;
15763: if (exists($env{'form.'.$setting})) {
15764: # Save this value away
15765: if ($type eq 'scalar' &&
15766: (! exists($env{$envname}) ||
15767: $env{$envname} ne $env{'form.'.$setting})) {
15768: $SaveHash{$basename} = $env{'form.'.$setting};
15769: $AppHash{$envname} = $env{'form.'.$setting};
15770: } elsif ($type eq 'array') {
15771: my $stored_form;
15772: if (ref($env{'form.'.$setting})) {
15773: $stored_form = join(',',
15774: map {
15775: &escape($_);
15776: } sort(@{$env{'form.'.$setting}}));
15777: } else {
15778: $stored_form =
15779: &escape($env{'form.'.$setting});
15780: }
15781: # Determine if the array contents are the same.
15782: if ($stored_form ne $env{$envname}) {
15783: $SaveHash{$basename} = $stored_form;
15784: $AppHash{$envname} = $stored_form;
15785: }
15786: }
15787: }
15788: }
15789: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
15790: $udom,$uname);
15791: if ($put_result !~ /^(ok|delayed)/) {
15792: &Apache::lonnet::logthis('unable to save form parameters, '.
15793: 'got error:'.$put_result);
15794: }
15795: # Make sure these settings stick around in this session, too
15796: &Apache::lonnet::appenv(\%AppHash);
15797: return;
15798: }
15799:
15800: sub restore_course_settings {
15801: return &restore_settings($env{'request.course.id'},@_);
15802: }
15803:
15804: sub restore_settings {
15805: my ($context,$prefix,$Settings) = @_;
15806: while (my ($setting,$type) = each(%$Settings)) {
15807: next if (exists($env{'form.'.$setting}));
15808: my $envname = 'environment.internal.'.$context.'.'.$prefix.
15809: '.'.$setting;
15810: if (exists($env{$envname})) {
15811: if ($type eq 'scalar') {
15812: $env{'form.'.$setting} = $env{$envname};
15813: } elsif ($type eq 'array') {
15814: $env{'form.'.$setting} = [
15815: map {
15816: &unescape($_);
15817: } split(',',$env{$envname})
15818: ];
15819: }
15820: }
15821: }
15822: }
15823:
15824: #######################################################
15825: #######################################################
15826:
15827: =pod
15828:
15829: =head1 Domain E-mail Routines
15830:
15831: =over 4
15832:
15833: =item * &build_recipient_list()
15834:
15835: Build recipient lists for following types of e-mail:
15836: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15837: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15838: module change checking, student/employee ID conflict checks, as
15839: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15840: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15841:
15842: Inputs:
15843: defmail (scalar - email address of default recipient),
15844: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15845: requestsmail, updatesmail, or idconflictsmail).
15846:
15847: defdom (domain for which to retrieve configuration settings),
15848:
15849: origmail (scalar - email address of recipient from loncapa.conf,
15850: i.e., predates configuration by DC via domainprefs.pm
15851:
15852: $requname username of requester (if mailing type is helpdeskmail)
15853:
15854: $requdom domain of requester (if mailing type is helpdeskmail)
15855:
15856: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15857:
15858:
15859: Returns: comma separated list of addresses to which to send e-mail.
15860:
15861: =back
15862:
15863: =cut
15864:
15865: ############################################################
15866: ############################################################
15867: sub build_recipient_list {
15868: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15869: my @recipients;
15870: my ($otheremails,$lastresort,$allbcc,$addtext);
15871: my %domconfig =
15872: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15873: if (ref($domconfig{'contacts'}) eq 'HASH') {
15874: if (exists($domconfig{'contacts'}{$mailing})) {
15875: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15876: my @contacts = ('adminemail','supportemail');
15877: foreach my $item (@contacts) {
15878: if ($domconfig{'contacts'}{$mailing}{$item}) {
15879: my $addr = $domconfig{'contacts'}{$item};
15880: if (!grep(/^\Q$addr\E$/,@recipients)) {
15881: push(@recipients,$addr);
15882: }
15883: }
15884: }
15885: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15886: if ($mailing eq 'helpdeskmail') {
15887: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15888: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15889: my @ok_bccs;
15890: foreach my $bcc (@bccs) {
15891: $bcc =~ s/^\s+//g;
15892: $bcc =~ s/\s+$//g;
15893: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15894: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15895: push(@ok_bccs,$bcc);
15896: }
15897: }
15898: }
15899: if (@ok_bccs > 0) {
15900: $allbcc = join(', ',@ok_bccs);
15901: }
15902: }
15903: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15904: }
15905: }
15906: } elsif ($origmail ne '') {
15907: $lastresort = $origmail;
15908: }
15909: if ($mailing eq 'helpdeskmail') {
15910: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15911: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15912: my ($inststatus,$inststatus_checked);
15913: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15914: ($env{'user.domain'} ne 'public')) {
15915: $inststatus_checked = 1;
15916: $inststatus = $env{'environment.inststatus'};
15917: }
15918: unless ($inststatus_checked) {
15919: if (($requname ne '') && ($requdom ne '')) {
15920: if (($requname =~ /^$match_username$/) &&
15921: ($requdom =~ /^$match_domain$/) &&
15922: (&Apache::lonnet::domain($requdom))) {
15923: my $requhome = &Apache::lonnet::homeserver($requname,
15924: $requdom);
15925: unless ($requhome eq 'no_host') {
15926: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15927: $inststatus = $userenv{'inststatus'};
15928: $inststatus_checked = 1;
15929: }
15930: }
15931: }
15932: }
15933: unless ($inststatus_checked) {
15934: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15935: my %srch = (srchby => 'email',
15936: srchdomain => $defdom,
15937: srchterm => $reqemail,
15938: srchtype => 'exact');
15939: my %srch_results = &Apache::lonnet::usersearch(\%srch);
15940: foreach my $uname (keys(%srch_results)) {
15941: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15942: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15943: $inststatus_checked = 1;
15944: last;
15945: }
15946: }
15947: unless ($inststatus_checked) {
15948: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15949: if ($dirsrchres eq 'ok') {
15950: foreach my $uname (keys(%srch_results)) {
15951: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15952: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15953: $inststatus_checked = 1;
15954: last;
15955: }
15956: }
15957: }
15958: }
15959: }
15960: }
15961: if ($inststatus ne '') {
15962: foreach my $status (split(/\:/,$inststatus)) {
15963: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15964: my @contacts = ('adminemail','supportemail');
15965: foreach my $item (@contacts) {
15966: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15967: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15968: if (!grep(/^\Q$addr\E$/,@recipients)) {
15969: push(@recipients,$addr);
15970: }
15971: }
15972: }
15973: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15974: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15975: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15976: my @ok_bccs;
15977: foreach my $bcc (@bccs) {
15978: $bcc =~ s/^\s+//g;
15979: $bcc =~ s/\s+$//g;
15980: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15981: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15982: push(@ok_bccs,$bcc);
15983: }
15984: }
15985: }
15986: if (@ok_bccs > 0) {
15987: $allbcc = join(', ',@ok_bccs);
15988: }
15989: }
15990: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15991: last;
15992: }
15993: }
15994: }
15995: }
15996: }
15997: } elsif ($origmail ne '') {
15998: $lastresort = $origmail;
15999: }
16000: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
16001: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
16002: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
16003: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
16004: my %what = (
16005: perlvar => 1,
16006: );
16007: my $primary = &Apache::lonnet::domain($defdom,'primary');
16008: if ($primary) {
16009: my $gotaddr;
16010: my ($result,$returnhash) =
16011: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
16012: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
16013: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
16014: $lastresort = $returnhash->{'lonSupportEMail'};
16015: $gotaddr = 1;
16016: }
16017: }
16018: unless ($gotaddr) {
16019: my $uintdom = &Apache::lonnet::internet_dom($primary);
16020: my $intdom = &Apache::lonnet::internet_dom($lonhost);
16021: unless ($uintdom eq $intdom) {
16022: my %domconfig =
16023: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
16024: if (ref($domconfig{'contacts'}) eq 'HASH') {
16025: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
16026: my @contacts = ('adminemail','supportemail');
16027: foreach my $item (@contacts) {
16028: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
16029: my $addr = $domconfig{'contacts'}{$item};
16030: if (!grep(/^\Q$addr\E$/,@recipients)) {
16031: push(@recipients,$addr);
16032: }
16033: }
16034: }
16035: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
16036: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
16037: }
16038: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
16039: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
16040: my @ok_bccs;
16041: foreach my $bcc (@bccs) {
16042: $bcc =~ s/^\s+//g;
16043: $bcc =~ s/\s+$//g;
16044: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
16045: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
16046: push(@ok_bccs,$bcc);
16047: }
16048: }
16049: }
16050: if (@ok_bccs > 0) {
16051: $allbcc = join(', ',@ok_bccs);
16052: }
16053: }
16054: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
16055: }
16056: }
16057: }
16058: }
16059: }
16060: }
16061: }
16062: if (defined($defmail)) {
16063: if ($defmail ne '') {
16064: push(@recipients,$defmail);
16065: }
16066: }
16067: if ($otheremails) {
16068: my @others;
16069: if ($otheremails =~ /,/) {
16070: @others = split(/,/,$otheremails);
16071: } else {
16072: push(@others,$otheremails);
16073: }
16074: foreach my $addr (@others) {
16075: if (!grep(/^\Q$addr\E$/,@recipients)) {
16076: push(@recipients,$addr);
16077: }
16078: }
16079: }
16080: if ($mailing eq 'helpdeskmail') {
16081: if ((!@recipients) && ($lastresort ne '')) {
16082: push(@recipients,$lastresort);
16083: }
16084: } elsif ($lastresort ne '') {
16085: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
16086: push(@recipients,$lastresort);
16087: }
16088: }
16089: my $recipientlist = join(',',@recipients);
16090: if (wantarray) {
16091: return ($recipientlist,$allbcc,$addtext);
16092: } else {
16093: return $recipientlist;
16094: }
16095: }
16096:
16097: ############################################################
16098: ############################################################
16099:
16100: =pod
16101:
16102: =over 4
16103:
16104: =item * &mime_email()
16105:
16106: Sends an email with a possible attachment
16107:
16108: Inputs:
16109:
16110: =over 4
16111:
16112: from - Sender's email address
16113:
16114: replyto - Reply-To email address
16115:
16116: to - Email address of recipient
16117:
16118: subject - Subject of email
16119:
16120: body - Body of email
16121:
16122: cc_string - Carbon copy email address
16123:
16124: bcc - Blind carbon copy email address
16125:
16126: attachment_path - Path of file to be attached
16127:
16128: file_name - Name of file to be attached
16129:
16130: attachment_text - The body of an attachment of type "TEXT"
16131:
16132: =back
16133:
16134: =back
16135:
16136: =cut
16137:
16138: ############################################################
16139: ############################################################
16140:
16141: sub mime_email {
16142: my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path,
16143: $file_name,$attachment_text) = @_;
16144:
16145: my $msg = MIME::Lite->new(
16146: From => $from,
16147: To => $to,
16148: Subject => $subject,
16149: Type =>'TEXT',
16150: Data => $body,
16151: );
16152: if ($replyto ne '') {
16153: $msg->add("Reply-To" => $replyto);
16154: }
16155: if ($cc_string ne '') {
16156: $msg->add("Cc" => $cc_string);
16157: }
16158: if ($bcc ne '') {
16159: $msg->add("Bcc" => $bcc);
16160: }
16161: $msg->attr("content-type" => "text/plain");
16162: $msg->attr("content-type.charset" => "UTF-8");
16163: # Attach file if given
16164: if ($attachment_path) {
16165: unless ($file_name) {
16166: if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
16167: }
16168: my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
16169: $msg->attach(Type => $type,
16170: Path => $attachment_path,
16171: Filename => $file_name
16172: );
16173: # Otherwise attach text if given
16174: } elsif ($attachment_text) {
16175: $msg->attach(Type => 'TEXT',
16176: Data => $attachment_text);
16177: }
16178: # Send it
16179: $msg->send('sendmail');
16180: }
16181:
16182: ############################################################
16183: ############################################################
16184:
16185: =pod
16186:
16187: =head1 Course Catalog Routines
16188:
16189: =over 4
16190:
16191: =item * &gather_categories()
16192:
16193: Converts category definitions - keys of categories hash stored in
16194: coursecategories in configuration.db on the primary library server in a
16195: domain - to an array. Also generates javascript and idx hash used to
16196: generate Domain Coordinator interface for editing Course Categories.
16197:
16198: Inputs:
16199:
16200: categories (reference to hash of category definitions).
16201:
16202: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16203: categories and subcategories).
16204:
16205: idx (reference to hash of counters used in Domain Coordinator interface for
16206: editing Course Categories).
16207:
16208: jsarray (reference to array of categories used to create Javascript arrays for
16209: Domain Coordinator interface for editing Course Categories).
16210:
16211: Returns: nothing
16212:
16213: Side effects: populates cats, idx and jsarray.
16214:
16215: =cut
16216:
16217: sub gather_categories {
16218: my ($categories,$cats,$idx,$jsarray) = @_;
16219: my %counters;
16220: my $num = 0;
16221: foreach my $item (keys(%{$categories})) {
16222: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16223: if ($container eq '' && $depth == 0) {
16224: $cats->[$depth][$categories->{$item}] = $cat;
16225: } else {
16226: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
16227: }
16228: my ($escitem,$tail) = split(/:/,$item,2);
16229: if ($counters{$tail} eq '') {
16230: $counters{$tail} = $num;
16231: $num ++;
16232: }
16233: if (ref($idx) eq 'HASH') {
16234: $idx->{$item} = $counters{$tail};
16235: }
16236: if (ref($jsarray) eq 'ARRAY') {
16237: push(@{$jsarray->[$counters{$tail}]},$item);
16238: }
16239: }
16240: return;
16241: }
16242:
16243: =pod
16244:
16245: =item * &extract_categories()
16246:
16247: Used to generate breadcrumb trails for course categories.
16248:
16249: Inputs:
16250:
16251: categories (reference to hash of category definitions).
16252:
16253: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16254: categories and subcategories).
16255:
16256: trails (reference to array of breacrumb trails for each category).
16257:
16258: allitems (reference to hash - key is category key
16259: (format: escaped(name):escaped(parent category):depth in hierarchy).
16260:
16261: idx (reference to hash of counters used in Domain Coordinator interface for
16262: editing Course Categories).
16263:
16264: jsarray (reference to array of categories used to create Javascript arrays for
16265: Domain Coordinator interface for editing Course Categories).
16266:
16267: subcats (reference to hash of arrays containing all subcategories within each
16268: category, -recursive)
16269:
16270: maxd (reference to hash used to hold max depth for all top-level categories).
16271:
16272: Returns: nothing
16273:
16274: Side effects: populates trails and allitems hash references.
16275:
16276: =cut
16277:
16278: sub extract_categories {
16279: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
16280: if (ref($categories) eq 'HASH') {
16281: &gather_categories($categories,$cats,$idx,$jsarray);
16282: if (ref($cats->[0]) eq 'ARRAY') {
16283: for (my $i=0; $i<@{$cats->[0]}; $i++) {
16284: my $name = $cats->[0][$i];
16285: my $item = &escape($name).'::0';
16286: my $trailstr;
16287: if ($name eq 'instcode') {
16288: $trailstr = &mt('Official courses (with institutional codes)');
16289: } elsif ($name eq 'communities') {
16290: $trailstr = &mt('Communities');
16291: } elsif ($name eq 'placement') {
16292: $trailstr = &mt('Placement Tests');
16293: } else {
16294: $trailstr = $name;
16295: }
16296: if ($allitems->{$item} eq '') {
16297: push(@{$trails},$trailstr);
16298: $allitems->{$item} = scalar(@{$trails})-1;
16299: }
16300: my @parents = ($name);
16301: if (ref($cats->[1]{$name}) eq 'ARRAY') {
16302: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
16303: my $category = $cats->[1]{$name}[$j];
16304: if (ref($subcats) eq 'HASH') {
16305: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
16306: }
16307: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
16308: }
16309: } else {
16310: if (ref($subcats) eq 'HASH') {
16311: $subcats->{$item} = [];
16312: }
16313: if (ref($maxd) eq 'HASH') {
16314: $maxd->{$name} = 1;
16315: }
16316: }
16317: }
16318: }
16319: }
16320: return;
16321: }
16322:
16323: =pod
16324:
16325: =item * &recurse_categories()
16326:
16327: Recursively used to generate breadcrumb trails for course categories.
16328:
16329: Inputs:
16330:
16331: cats (reference to array of arrays/hashes which encapsulates hierarchy of
16332: categories and subcategories).
16333:
16334: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
16335:
16336: category (current course category, for which breadcrumb trail is being generated).
16337:
16338: trails (reference to array of breadcrumb trails for each category).
16339:
16340: allitems (reference to hash - key is category key
16341: (format: escaped(name):escaped(parent category):depth in hierarchy).
16342:
16343: parents (array containing containers directories for current category,
16344: back to top level).
16345:
16346: Returns: nothing
16347:
16348: Side effects: populates trails and allitems hash references
16349:
16350: =cut
16351:
16352: sub recurse_categories {
16353: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
16354: my $shallower = $depth - 1;
16355: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
16356: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
16357: my $name = $cats->[$depth]{$category}[$k];
16358: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16359: my $trailstr = join(' » ',(@{$parents},$category));
16360: if ($allitems->{$item} eq '') {
16361: push(@{$trails},$trailstr);
16362: $allitems->{$item} = scalar(@{$trails})-1;
16363: }
16364: my $deeper = $depth+1;
16365: push(@{$parents},$category);
16366: if (ref($subcats) eq 'HASH') {
16367: my $subcat = &escape($name).':'.$category.':'.$depth;
16368: for (my $j=@{$parents}; $j>=0; $j--) {
16369: my $higher;
16370: if ($j > 0) {
16371: $higher = &escape($parents->[$j]).':'.
16372: &escape($parents->[$j-1]).':'.$j;
16373: } else {
16374: $higher = &escape($parents->[$j]).'::'.$j;
16375: }
16376: push(@{$subcats->{$higher}},$subcat);
16377: }
16378: }
16379: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
16380: $subcats,$maxd);
16381: pop(@{$parents});
16382: }
16383: } else {
16384: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
16385: my $trailstr = join(' » ',(@{$parents},$category));
16386: if ($allitems->{$item} eq '') {
16387: push(@{$trails},$trailstr);
16388: $allitems->{$item} = scalar(@{$trails})-1;
16389: }
16390: if (ref($maxd) eq 'HASH') {
16391: if ($depth > $maxd->{$parents->[0]}) {
16392: $maxd->{$parents->[0]} = $depth;
16393: }
16394: }
16395: }
16396: return;
16397: }
16398:
16399: =pod
16400:
16401: =item * &assign_categories_table()
16402:
16403: Create a datatable for display of hierarchical categories in a domain,
16404: with checkboxes to allow a course to be categorized.
16405:
16406: Inputs:
16407:
16408: cathash - reference to hash of categories defined for the domain (from
16409: configuration.db)
16410:
16411: currcat - scalar with an & separated list of categories assigned to a course.
16412:
16413: type - scalar contains course type (Course or Community).
16414:
16415: disabled - scalar (optional) contains disabled="disabled" if input elements are
16416: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16417:
16418: Returns: $output (markup to be displayed)
16419:
16420: =cut
16421:
16422: sub assign_categories_table {
16423: my ($cathash,$currcat,$type,$disabled) = @_;
16424: my $output;
16425: if (ref($cathash) eq 'HASH') {
16426: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
16427: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
16428: $maxdepth = scalar(@cats);
16429: if (@cats > 0) {
16430: my $itemcount = 0;
16431: if (ref($cats[0]) eq 'ARRAY') {
16432: my @currcategories;
16433: if ($currcat ne '') {
16434: @currcategories = split('&',$currcat);
16435: }
16436: my $table;
16437: for (my $i=0; $i<@{$cats[0]}; $i++) {
16438: my $parent = $cats[0][$i];
16439: next if ($parent eq 'instcode');
16440: if ($type eq 'Community') {
16441: next unless ($parent eq 'communities');
16442: } elsif ($type eq 'Placement') {
16443: next unless ($parent eq 'placement');
16444: } else {
16445: next if (($parent eq 'communities') || ($parent eq 'placement'));
16446: }
16447: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16448: my $item = &escape($parent).'::0';
16449: my $checked = '';
16450: if (@currcategories > 0) {
16451: if (grep(/^\Q$item\E$/,@currcategories)) {
16452: $checked = ' checked="checked"';
16453: }
16454: }
16455: my $parent_title = $parent;
16456: if ($parent eq 'communities') {
16457: $parent_title = &mt('Communities');
16458: } elsif ($parent eq 'placement') {
16459: $parent_title = &mt('Placement Tests');
16460: }
16461: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
16462: '<input type="checkbox" name="usecategory" value="'.
16463: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
16464: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
16465: my $depth = 1;
16466: push(@path,$parent);
16467: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
16468: pop(@path);
16469: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
16470: $itemcount ++;
16471: }
16472: if ($itemcount) {
16473: $output = &Apache::loncommon::start_data_table().
16474: $table.
16475: &Apache::loncommon::end_data_table();
16476: }
16477: }
16478: }
16479: }
16480: return $output;
16481: }
16482:
16483: =pod
16484:
16485: =item * &assign_category_rows()
16486:
16487: Create a datatable row for display of nested categories in a domain,
16488: with checkboxes to allow a course to be categorized,called recursively.
16489:
16490: Inputs:
16491:
16492: itemcount - track row number for alternating colors
16493:
16494: cats - reference to array of arrays/hashes which encapsulates hierarchy of
16495: categories and subcategories.
16496:
16497: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
16498:
16499: parent - parent of current category item
16500:
16501: path - Array containing all categories back up through the hierarchy from the
16502: current category to the top level.
16503:
16504: currcategories - reference to array of current categories assigned to the course
16505:
16506: disabled - scalar (optional) contains disabled="disabled" if input elements are
16507: to be readonly (e.g., Domain Helpdesk role viewing course settings).
16508:
16509: Returns: $output (markup to be displayed).
16510:
16511: =cut
16512:
16513: sub assign_category_rows {
16514: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
16515: my ($text,$name,$item,$chgstr);
16516: if (ref($cats) eq 'ARRAY') {
16517: my $maxdepth = scalar(@{$cats});
16518: if (ref($cats->[$depth]) eq 'HASH') {
16519: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
16520: my $numchildren = @{$cats->[$depth]{$parent}};
16521: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
16522: $text .= '<td><table class="LC_data_table">';
16523: for (my $j=0; $j<$numchildren; $j++) {
16524: $name = $cats->[$depth]{$parent}[$j];
16525: $item = &escape($name).':'.&escape($parent).':'.$depth;
16526: my $deeper = $depth+1;
16527: my $checked = '';
16528: if (ref($currcategories) eq 'ARRAY') {
16529: if (@{$currcategories} > 0) {
16530: if (grep(/^\Q$item\E$/,@{$currcategories})) {
16531: $checked = ' checked="checked"';
16532: }
16533: }
16534: }
16535: $text .= '<tr><td><span class="LC_nobreak"><label>'.
16536: '<input type="checkbox" name="usecategory" value="'.
16537: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
16538: '<input type="hidden" name="catname" value="'.$name.'" />'.
16539: '</td><td>';
16540: if (ref($path) eq 'ARRAY') {
16541: push(@{$path},$name);
16542: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
16543: pop(@{$path});
16544: }
16545: $text .= '</td></tr>';
16546: }
16547: $text .= '</table></td>';
16548: }
16549: }
16550: }
16551: return $text;
16552: }
16553:
16554: =pod
16555:
16556: =back
16557:
16558: =cut
16559:
16560: ############################################################
16561: ############################################################
16562:
16563:
16564: sub commit_customrole {
16565: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
16566: my $result = &Apache::lonnet::assigncustomrole(
16567: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
16568: $context,$othdomby,$requester);
16569: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
16570: ($start?', '.&mt('starting').' '.localtime($start):'').
16571: ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
16572: if (wantarray) {
16573: return ($output,$result);
16574: } else {
16575: return $output;
16576: }
16577: }
16578:
16579: sub commit_standardrole {
16580: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
16581: $othdomby,$requester) = @_;
16582: my ($output,$logmsg,$linefeed,$result);
16583: if ($context eq 'auto') {
16584: $linefeed = "\n";
16585: } else {
16586: $linefeed = "<br />\n";
16587: }
16588: if ($three eq 'st') {
16589: $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
16590: $one,$two,$sec,$context,$credits,$othdomby,
16591: $requester);
16592: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
16593: ($result eq 'unknown_course') || ($result eq 'refused')) {
16594: $output = $logmsg.' '.&mt('Error: ').$result."\n";
16595: } else {
16596: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
16597: ($start?', '.&mt('starting').' '.localtime($start):'').
16598: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16599: if ($context eq 'auto') {
16600: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
16601: } else {
16602: $output .= '<b>'.$result.'</b>'.$linefeed.
16603: &mt('Add to classlist').': <b>ok</b>';
16604: }
16605: $output .= $linefeed;
16606: }
16607: } else {
16608: $output = &mt('Assigning').' '.$three.' in '.$url.
16609: ($start?', '.&mt('starting').' '.localtime($start):'').
16610: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
16611: $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
16612: '','',$context,$othdomby,$requester);
16613: if ($context eq 'auto') {
16614: $output .= $result.$linefeed;
16615: } else {
16616: $output .= '<b>'.$result.'</b>'.$linefeed;
16617: }
16618: }
16619: if (wantarray) {
16620: return ($output,$result);
16621: } else {
16622: return $output;
16623: }
16624: }
16625:
16626: sub commit_studentrole {
16627: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
16628: $credits,$othdomby,$requester) = @_;
16629: my ($result,$linefeed,$oldsecurl,$newsecurl);
16630: if ($context eq 'auto') {
16631: $linefeed = "\n";
16632: } else {
16633: $linefeed = '<br />'."\n";
16634: }
16635: if (defined($one) && defined($two)) {
16636: my $cid=$one.'_'.$two;
16637: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
16638: my $secchange = 0;
16639: my $expire_role_result;
16640: my $modify_section_result;
16641: if ($oldsec ne '-1') {
16642: if ($oldsec ne $sec) {
16643: $secchange = 1;
16644: my $now = time;
16645: my $uurl='/'.$cid;
16646: $uurl=~s/\_/\//g;
16647: if ($oldsec) {
16648: $uurl.='/'.$oldsec;
16649: }
16650: $oldsecurl = $uurl;
16651: $expire_role_result =
16652: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
16653: '','','',$context,$othdomby,$requester);
16654: if ($env{'request.course.sec'} ne '') {
16655: if ($expire_role_result eq 'refused') {
16656: my @roles = ('st');
16657: my @statuses = ('previous');
16658: my @roledoms = ($one);
16659: my $withsec = 1;
16660: my %roleshash =
16661: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
16662: \@statuses,\@roles,\@roledoms,$withsec);
16663: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
16664: my ($oldstart,$oldend) =
16665: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
16666: if ($oldend > 0 && $oldend <= $now) {
16667: $expire_role_result = 'ok';
16668: }
16669: }
16670: }
16671: }
16672: $result = $expire_role_result;
16673: }
16674: }
16675: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
16676: $modify_section_result =
16677: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
16678: undef,undef,undef,$sec,
16679: $end,$start,'','',$cid,
16680: '',$context,$credits,'',
16681: $othdomby,$requester);
16682: if ($modify_section_result =~ /^ok/) {
16683: if ($secchange == 1) {
16684: if ($sec eq '') {
16685: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
16686: } else {
16687: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
16688: }
16689: } elsif ($oldsec eq '-1') {
16690: if ($sec eq '') {
16691: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
16692: } else {
16693: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16694: }
16695: } else {
16696: if ($sec eq '') {
16697: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
16698: } else {
16699: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
16700: }
16701: }
16702: } else {
16703: if ($secchange) {
16704: $$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;
16705: } else {
16706: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
16707: }
16708: }
16709: $result = $modify_section_result;
16710: } elsif ($secchange == 1) {
16711: if ($oldsec eq '') {
16712: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
16713: } else {
16714: $$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;
16715: }
16716: if ($expire_role_result eq 'refused') {
16717: my $newsecurl = '/'.$cid;
16718: $newsecurl =~ s/\_/\//g;
16719: if ($sec ne '') {
16720: $newsecurl.='/'.$sec;
16721: }
16722: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
16723: if ($sec eq '') {
16724: $$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;
16725: } else {
16726: $$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;
16727: }
16728: }
16729: }
16730: }
16731: } else {
16732: $$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;
16733: $result = "error: incomplete course id\n";
16734: }
16735: return $result;
16736: }
16737:
16738: sub show_role_extent {
16739: my ($scope,$context,$role) = @_;
16740: $scope =~ s{^/}{};
16741: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
16742: push(@courseroles,'co');
16743: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
16744: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
16745: $scope =~ s{/}{_};
16746: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
16747: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
16748: my ($audom,$auname) = split(/\//,$scope);
16749: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
16750: &Apache::loncommon::plainname($auname,$audom).'</span>');
16751: } else {
16752: $scope =~ s{/$}{};
16753: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
16754: &Apache::lonnet::domain($scope,'description').'</span>');
16755: }
16756: }
16757:
16758: ############################################################
16759: ############################################################
16760:
16761: sub check_clone {
16762: my ($args,$linefeed) = @_;
16763: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
16764: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
16765: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
16766: my $clonetitle;
16767: my @clonemsg;
16768: my $can_clone = 0;
16769: my $lctype = lc($args->{'crstype'});
16770: if ($lctype ne 'community') {
16771: $lctype = 'course';
16772: }
16773: if ($clonehome eq 'no_host') {
16774: if ($args->{'crstype'} eq 'Community') {
16775: push(@clonemsg,({
16776: mt => 'No new community created.',
16777: args => [],
16778: },
16779: {
16780: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
16781: args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
16782: }));
16783: } else {
16784: push(@clonemsg,({
16785: mt => 'No new course created.',
16786: args => [],
16787: },
16788: {
16789: mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
16790: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16791: }));
16792: }
16793: } else {
16794: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
16795: $clonetitle = $clonedesc{'description'};
16796: if ($args->{'crstype'} eq 'Community') {
16797: if ($clonedesc{'type'} ne 'Community') {
16798: push(@clonemsg,({
16799: mt => 'No new community created.',
16800: args => [],
16801: },
16802: {
16803: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
16804: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
16805: }));
16806: return ($can_clone,\@clonemsg,$cloneid,$clonehome);
16807: }
16808: }
16809: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
16810: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
16811: $can_clone = 1;
16812: } else {
16813: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
16814: $args->{'clonedomain'},$args->{'clonecourse'});
16815: if ($clonehash{'cloners'} eq '') {
16816: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
16817: if ($domdefs{'canclone'}) {
16818: unless ($domdefs{'canclone'} eq 'none') {
16819: if ($domdefs{'canclone'} eq 'domain') {
16820: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
16821: $can_clone = 1;
16822: }
16823: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16824: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16825: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
16826: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
16827: $can_clone = 1;
16828: }
16829: }
16830: }
16831: }
16832: } else {
16833: my @cloners = split(/,/,$clonehash{'cloners'});
16834: if (grep(/^\*$/,@cloners)) {
16835: $can_clone = 1;
16836: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16837: $can_clone = 1;
16838: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
16839: $can_clone = 1;
16840: }
16841: unless ($can_clone) {
16842: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
16843: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
16844: my (%gotdomdefaults,%gotcodedefaults);
16845: foreach my $cloner (@cloners) {
16846: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
16847: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
16848: my (%codedefaults,@code_order);
16849: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
16850: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
16851: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
16852: }
16853: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
16854: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
16855: }
16856: } else {
16857: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
16858: \%codedefaults,
16859: \@code_order);
16860: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
16861: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
16862: }
16863: if (@code_order > 0) {
16864: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
16865: $cloner,$clonehash{'internal.coursecode'},
16866: $args->{'crscode'})) {
16867: $can_clone = 1;
16868: last;
16869: }
16870: }
16871: }
16872: }
16873: }
16874: }
16875: }
16876: unless ($can_clone) {
16877: my $ccrole = 'cc';
16878: if ($args->{'crstype'} eq 'Community') {
16879: $ccrole = 'co';
16880: }
16881: my %roleshash =
16882: &Apache::lonnet::get_my_roles($args->{'ccuname'},
16883: $args->{'ccdomain'},
16884: 'userroles',['active'],[$ccrole],
16885: [$args->{'clonedomain'}]);
16886: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
16887: $can_clone = 1;
16888: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
16889: $args->{'ccuname'},$args->{'ccdomain'})) {
16890: $can_clone = 1;
16891: }
16892: }
16893: unless ($can_clone) {
16894: if ($args->{'crstype'} eq 'Community') {
16895: push(@clonemsg,({
16896: mt => 'No new community created.',
16897: args => [],
16898: },
16899: {
16900: 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]).',
16901: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16902: }));
16903: } else {
16904: push(@clonemsg,({
16905: mt => 'No new course created.',
16906: args => [],
16907: },
16908: {
16909: 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]).',
16910: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
16911: }));
16912: }
16913: }
16914: }
16915: }
16916: return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
16917: }
16918:
16919: sub construct_course {
16920: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
16921: $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
16922: my ($outcome,$msgref,$clonemsgref);
16923: my $linefeed = '<br />'."\n";
16924: if ($context eq 'auto') {
16925: $linefeed = "\n";
16926: }
16927:
16928: #
16929: # Are we cloning?
16930: #
16931: my ($can_clone,$cloneid,$clonehome,$clonetitle);
16932: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16933: ($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16934: if (!$can_clone) {
16935: return (0,$outcome,$clonemsgref);
16936: }
16937: }
16938:
16939: #
16940: # Open course
16941: #
16942: my $showncrstype;
16943: if ($args->{'crstype'} eq 'Placement') {
16944: $showncrstype = 'placement test';
16945: } else {
16946: $showncrstype = lc($args->{'crstype'});
16947: }
16948: my %cenv=();
16949: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16950: $args->{'cdescr'},
16951: $args->{'curl'},
16952: $args->{'course_home'},
16953: $args->{'nonstandard'},
16954: $args->{'crscode'},
16955: $args->{'ccuname'}.':'.
16956: $args->{'ccdomain'},
16957: $args->{'crstype'},
16958: $cnum,$context,$category,
16959: $callercontext);
16960:
16961: # Note: The testing routines depend on this being output; see
16962: # Utils::Course. This needs to at least be output as a comment
16963: # if anyone ever decides to not show this, and Utils::Course::new
16964: # will need to be suitably modified.
16965: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16966: $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16967: } else {
16968: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
16969: }
16970: if ($$courseid =~ /^error:/) {
16971: return (0,$outcome,$clonemsgref);
16972: }
16973:
16974: #
16975: # Check if created correctly
16976: #
16977: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16978: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16979: if ($crsuhome eq 'no_host') {
16980: if (($callercontext eq 'auto') && ($user_lh ne '')) {
16981: $outcome .= &mt_user($user_lh,
16982: 'Course creation failed, unrecognized course home server.');
16983: } else {
16984: $outcome .= &mt('Course creation failed, unrecognized course home server.');
16985: }
16986: $outcome .= $linefeed;
16987: return (0,$outcome,$clonemsgref);
16988: }
16989: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16990:
16991: #
16992: # Do the cloning
16993: #
16994: my @clonemsg;
16995: if ($can_clone && $cloneid) {
16996: push(@clonemsg,
16997: {
16998: mt => 'Created [_1] by cloning from [_2]',
16999: args => [$showncrstype,$clonetitle],
17000: });
17001: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
17002: # Copy all files
17003: my @info =
17004: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
17005: $args->{'dateshift'},$args->{'crscode'},
17006: $args->{'ccuname'}.':'.$args->{'ccdomain'},
17007: $args->{'tinyurls'});
17008: if (@info) {
17009: push(@clonemsg,@info);
17010: }
17011: # Restore URL
17012: $cenv{'url'}=$oldcenv{'url'};
17013: # Restore title
17014: $cenv{'description'}=$oldcenv{'description'};
17015: # Restore creation date, creator and creation context.
17016: $cenv{'internal.created'}=$oldcenv{'internal.created'};
17017: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
17018: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
17019: # Mark as cloned
17020: $cenv{'clonedfrom'}=$cloneid;
17021: # Need to clone grading mode
17022: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
17023: $cenv{'grading'}=$newenv{'grading'};
17024: # Do not clone these environment entries
17025: &Apache::lonnet::del('environment',
17026: ['default_enrollment_start_date',
17027: 'default_enrollment_end_date',
17028: 'question.email',
17029: 'policy.email',
17030: 'comment.email',
17031: 'pch.users.denied',
17032: 'plc.users.denied',
17033: 'hidefromcat',
17034: 'checkforpriv',
17035: 'categories'],
17036: $$crsudom,$$crsunum);
17037: if ($args->{'textbook'}) {
17038: $cenv{'internal.textbook'} = $args->{'textbook'};
17039: }
17040: }
17041:
17042: #
17043: # Set environment (will override cloned, if existing)
17044: #
17045: my @sections = ();
17046: my @xlists = ();
17047: if ($args->{'crstype'}) {
17048: $cenv{'type'}=$args->{'crstype'};
17049: }
17050: if ($args->{'lti'}) {
17051: $cenv{'internal.lti'}=$args->{'lti'};
17052: }
17053: if ($args->{'crsid'}) {
17054: $cenv{'courseid'}=$args->{'crsid'};
17055: }
17056: if ($args->{'crscode'}) {
17057: $cenv{'internal.coursecode'}=$args->{'crscode'};
17058: }
17059: if ($args->{'crsquota'} ne '') {
17060: $cenv{'internal.coursequota'}=$args->{'crsquota'};
17061: } else {
17062: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
17063: }
17064: if ($args->{'ccuname'}) {
17065: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
17066: ':'.$args->{'ccdomain'};
17067: } else {
17068: $cenv{'internal.courseowner'} = $args->{'curruser'};
17069: }
17070: if ($args->{'defaultcredits'}) {
17071: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
17072: }
17073: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
17074: my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
17075: if ($args->{'crssections'}) {
17076: $cenv{'internal.sectionnums'} = '';
17077: if ($args->{'crssections'} =~ m/,/) {
17078: @sections = split/,/,$args->{'crssections'};
17079: } else {
17080: $sections[0] = $args->{'crssections'};
17081: }
17082: if (@sections > 0) {
17083: foreach my $item (@sections) {
17084: my ($sec,$gp) = split/:/,$item;
17085: my $class = $args->{'crscode'}.$sec;
17086: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
17087: $cenv{'internal.sectionnums'} .= $item.',';
17088: if ($addcheck eq 'ok') {
17089: unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17090: push(@oklcsecs,$gp);
17091: }
17092: } else {
17093: push(@badclasses,$class);
17094: }
17095: }
17096: $cenv{'internal.sectionnums'} =~ s/,$//;
17097: }
17098: }
17099: # do not hide course coordinator from staff listing,
17100: # even if privileged
17101: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17102: # add course coordinator's domain to domains to check for privileged users
17103: # if different to course domain
17104: if ($$crsudom ne $args->{'ccdomain'}) {
17105: $cenv{'checkforpriv'} = $args->{'ccdomain'};
17106: }
17107: # add crosslistings
17108: if ($args->{'crsxlist'}) {
17109: $cenv{'internal.crosslistings'}='';
17110: if ($args->{'crsxlist'} =~ m/,/) {
17111: @xlists = split/,/,$args->{'crsxlist'};
17112: } else {
17113: $xlists[0] = $args->{'crsxlist'};
17114: }
17115: if (@xlists > 0) {
17116: foreach my $item (@xlists) {
17117: my ($xl,$gp) = split/:/,$item;
17118: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
17119: $cenv{'internal.crosslistings'} .= $item.',';
17120: if ($addcheck eq 'ok') {
17121: unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
17122: push(@oklcsecs,$gp);
17123: }
17124: } else {
17125: push(@badclasses,$xl);
17126: }
17127: }
17128: $cenv{'internal.crosslistings'} =~ s/,$//;
17129: }
17130: }
17131: if ($args->{'autoadds'}) {
17132: $cenv{'internal.autoadds'}=$args->{'autoadds'};
17133: }
17134: if ($args->{'autodrops'}) {
17135: $cenv{'internal.autodrops'}=$args->{'autodrops'};
17136: }
17137: # check for notification of enrollment changes
17138: my @notified = ();
17139: if ($args->{'notify_owner'}) {
17140: if ($args->{'ccuname'} ne '') {
17141: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
17142: }
17143: }
17144: if ($args->{'notify_dc'}) {
17145: if ($uname ne '') {
17146: push(@notified,$uname.':'.$udom);
17147: }
17148: }
17149: if (@notified > 0) {
17150: my $notifylist;
17151: if (@notified > 1) {
17152: $notifylist = join(',',@notified);
17153: } else {
17154: $notifylist = $notified[0];
17155: }
17156: $cenv{'internal.notifylist'} = $notifylist;
17157: }
17158: if (@badclasses > 0) {
17159: my %lt=&Apache::lonlocal::texthash(
17160: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
17161: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
17162: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
17163: );
17164: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
17165: &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'};
17166: if ($context eq 'auto') {
17167: $outcome .= $badclass_msg.$linefeed;
17168: } else {
17169: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
17170: }
17171: foreach my $item (@badclasses) {
17172: if ($context eq 'auto') {
17173: $outcome .= " - $item\n";
17174: } else {
17175: $outcome .= "<li>$item</li>\n";
17176: }
17177: }
17178: if ($context eq 'auto') {
17179: $outcome .= $linefeed;
17180: } else {
17181: $outcome .= "</ul><br /><br /></div>\n";
17182: }
17183: }
17184: if ($args->{'no_end_date'}) {
17185: $args->{'endaccess'} = 0;
17186: }
17187: # If an official course with institutional sections is created by cloning
17188: # an existing course, section-specific hiding of course totals in student's
17189: # view of grades as copied from cloned course, will be checked for valid
17190: # sections.
17191: if (($can_clone && $cloneid) &&
17192: ($cenv{'internal.coursecode'} ne '') &&
17193: ($cenv{'grading'} eq 'standard') &&
17194: ($cenv{'hidetotals'} ne '') &&
17195: ($cenv{'hidetotals'} ne 'all')) {
17196: my @hidesecs;
17197: my $deletehidetotals;
17198: if (@oklcsecs) {
17199: foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
17200: if (grep(/^\Q$sec$/,@oklcsecs)) {
17201: push(@hidesecs,$sec);
17202: }
17203: }
17204: if (@hidesecs) {
17205: $cenv{'hidetotals'} = join(',',@hidesecs);
17206: } else {
17207: $deletehidetotals = 1;
17208: }
17209: } else {
17210: $deletehidetotals = 1;
17211: }
17212: if ($deletehidetotals) {
17213: delete($cenv{'hidetotals'});
17214: &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
17215: }
17216: }
17217: $cenv{'internal.autostart'}=$args->{'enrollstart'};
17218: $cenv{'internal.autoend'}=$args->{'enrollend'};
17219: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
17220: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
17221: if ($args->{'showphotos'}) {
17222: $cenv{'internal.showphotos'}=$args->{'showphotos'};
17223: }
17224: $cenv{'internal.authtype'} = $args->{'authtype'};
17225: $cenv{'internal.autharg'} = $args->{'autharg'};
17226: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
17227: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
17228: 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');
17229: if ($context eq 'auto') {
17230: $outcome .= $krb_msg;
17231: } else {
17232: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
17233: }
17234: $outcome .= $linefeed;
17235: }
17236: }
17237: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
17238: if ($args->{'setpolicy'}) {
17239: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17240: }
17241: if ($args->{'setcontent'}) {
17242: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17243: }
17244: if ($args->{'setcomment'}) {
17245: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
17246: }
17247: }
17248: if ($args->{'reshome'}) {
17249: $cenv{'reshome'}=$args->{'reshome'}.'/';
17250: $cenv{'reshome'}=~s/\/+$/\//;
17251: }
17252: #
17253: # course has keyed access
17254: #
17255: if ($args->{'setkeys'}) {
17256: $cenv{'keyaccess'}='yes';
17257: }
17258: # if specified, key authority is not course, but user
17259: # only active if keyaccess is yes
17260: if ($args->{'keyauth'}) {
17261: my ($user,$domain) = split(':',$args->{'keyauth'});
17262: $user = &LONCAPA::clean_username($user);
17263: $domain = &LONCAPA::clean_username($domain);
17264: if ($user ne '' && $domain ne '') {
17265: $cenv{'keyauth'}=$user.':'.$domain;
17266: }
17267: }
17268:
17269: #
17270: # generate and store uniquecode (available to course requester), if course should have one.
17271: #
17272: if ($args->{'uniquecode'}) {
17273: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
17274: if ($code) {
17275: $cenv{'internal.uniquecode'} = $code;
17276: my %crsinfo =
17277: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
17278: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
17279: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
17280: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
17281: }
17282: if (ref($coderef)) {
17283: $$coderef = $code;
17284: }
17285: }
17286: }
17287:
17288: if ($args->{'disresdis'}) {
17289: $cenv{'pch.roles.denied'}='st';
17290: }
17291: if ($args->{'disablechat'}) {
17292: $cenv{'plc.roles.denied'}='st';
17293: }
17294:
17295: # Record we've not yet viewed the Course Initialization Helper for this
17296: # course
17297: $cenv{'course.helper.not.run'} = 1;
17298: #
17299: # Use new Randomseed
17300: #
17301: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
17302: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
17303: #
17304: # The encryption code and receipt prefix for this course
17305: #
17306: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
17307: $cenv{'internal.encpref'}=100+int(9*rand(99));
17308: #
17309: # By default, use standard grading
17310: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
17311:
17312: $outcome .= $linefeed.&mt('Setting environment').': '.
17313: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
17314: #
17315: # Open all assignments
17316: #
17317: if ($args->{'openall'}) {
17318: my $opendate = time;
17319: if ($args->{'openallfrom'} =~ /^\d+$/) {
17320: $opendate = $args->{'openallfrom'};
17321: }
17322: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
17323: my %storecontent = ($storeunder => $opendate,
17324: $storeunder.'.type' => 'date_start');
17325: $outcome .= &mt('All assignments open starting [_1]',
17326: &Apache::lonlocal::locallocaltime($opendate)).': '.
17327: &Apache::lonnet::cput
17328: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
17329: }
17330: #
17331: # Set first page
17332: #
17333: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
17334: || ($cloneid)) {
17335: $outcome .= &mt('Setting first resource').': ';
17336:
17337: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
17338: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
17339:
17340: $outcome .= ($fatal?$errtext:'read ok').' - ';
17341: my $title; my $url;
17342: if ($args->{'firstres'} eq 'syl') {
17343: $title=&mt('Syllabus');
17344: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
17345: } else {
17346: $title=&mt('Table of Contents');
17347: $url='/adm/navmaps';
17348: }
17349:
17350: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
17351: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
17352:
17353: if ($errtext) { $fatal=2; }
17354: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
17355: }
17356:
17357: #
17358: # Set params for Placement Tests
17359: #
17360: if ($args->{'crstype'} eq 'Placement') {
17361: my %storecontent;
17362: my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
17363: my %defaults = (
17364: buttonshide => { value => 'yes',
17365: type => 'string_yesno',},
17366: type => { value => 'randomizetry',
17367: type => 'string_questiontype',},
17368: maxtries => { value => 1,
17369: type => 'int_pos',},
17370: problemstatus => { value => 'no',
17371: type => 'string_problemstatus',},
17372: );
17373: foreach my $key (keys(%defaults)) {
17374: $storecontent{$prefix.$key} = $defaults{$key}{'value'};
17375: $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
17376: }
17377: &Apache::lonnet::cput
17378: ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
17379: }
17380:
17381: return (1,$outcome,\@clonemsg);
17382: }
17383:
17384: sub make_unique_code {
17385: my ($cdom,$cnum) = @_;
17386: # get lock on uniquecodes db
17387: my $lockhash = {
17388: $cnum."\0".'uniquecodes' => $env{'user.name'}.
17389: ':'.$env{'user.domain'},
17390: };
17391: my $tries = 0;
17392: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17393: my ($code,$error);
17394:
17395: while (($gotlock ne 'ok') && ($tries<3)) {
17396: $tries ++;
17397: sleep 1;
17398: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17399: }
17400: if ($gotlock eq 'ok') {
17401: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
17402: my $gotcode;
17403: my $attempts = 0;
17404: while ((!$gotcode) && ($attempts < 100)) {
17405: $code = &generate_code();
17406: if (!exists($currcodes{$code})) {
17407: $gotcode = 1;
17408: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
17409: $error = 'nostore';
17410: }
17411: }
17412: $attempts ++;
17413: }
17414: my @del_lock = ($cnum."\0".'uniquecodes');
17415: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
17416: } else {
17417: $error = 'nolock';
17418: }
17419: return ($code,$error);
17420: }
17421:
17422: sub generate_code {
17423: my $code;
17424: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
17425: for (my $i=0; $i<6; $i++) {
17426: my $lettnum = int (rand 2);
17427: my $item = '';
17428: if ($lettnum) {
17429: $item = $letts[int( rand(18) )];
17430: } else {
17431: $item = 1+int( rand(8) );
17432: }
17433: $code .= $item;
17434: }
17435: return $code;
17436: }
17437:
17438: ############################################################
17439: ############################################################
17440:
17441: # Community, Course and Placement Test
17442: sub course_type {
17443: my ($cid) = @_;
17444: if (!defined($cid)) {
17445: $cid = $env{'request.course.id'};
17446: }
17447: if (defined($env{'course.'.$cid.'.type'})) {
17448: return $env{'course.'.$cid.'.type'};
17449: } else {
17450: return 'Course';
17451: }
17452: }
17453:
17454: sub group_term {
17455: my $crstype = &course_type();
17456: my %names = (
17457: 'Course' => 'group',
17458: 'Community' => 'group',
17459: 'Placement' => 'group',
17460: );
17461: return $names{$crstype};
17462: }
17463:
17464: sub course_types {
17465: my @types = ('official','unofficial','community','textbook','placement','lti');
17466: my %typename = (
17467: official => 'Official course',
17468: unofficial => 'Unofficial course',
17469: community => 'Community',
17470: textbook => 'Textbook course',
17471: placement => 'Placement test',
17472: lti => 'LTI provider',
17473: );
17474: return (\@types,\%typename);
17475: }
17476:
17477: sub icon {
17478: my ($file)=@_;
17479: my $curfext = lc((split(/\./,$file))[-1]);
17480: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
17481: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
17482: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
17483: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
17484: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17485: $curfext.".gif") {
17486: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
17487: $curfext.".gif";
17488: }
17489: }
17490: return &lonhttpdurl($iconname);
17491: }
17492:
17493: sub lonhttpdurl {
17494: #
17495: # Had been used for "small fry" static images on separate port 8080.
17496: # Modify here if lightweight http functionality desired again.
17497: # Currently eliminated due to increasing firewall issues.
17498: #
17499: my ($url)=@_;
17500: return $url;
17501: }
17502:
17503: sub connection_aborted {
17504: my ($r)=@_;
17505: $r->print(" ");$r->rflush();
17506: my $c = $r->connection;
17507: return $c->aborted();
17508: }
17509:
17510: # Escapes strings that may have embedded 's that will be put into
17511: # strings as 'strings'.
17512: sub escape_single {
17513: my ($input) = @_;
17514: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
17515: $input =~ s/\'/\\\'/g; # Esacpe the 's....
17516: return $input;
17517: }
17518:
17519: # Same as escape_single, but escape's "'s This
17520: # can be used for "strings"
17521: sub escape_double {
17522: my ($input) = @_;
17523: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
17524: $input =~ s/\"/\\\"/g; # Esacpe the "s....
17525: return $input;
17526: }
17527:
17528: # Escapes the last element of a full URL.
17529: sub escape_url {
17530: my ($url) = @_;
17531: my @urlslices = split(/\//, $url,-1);
17532: my $lastitem = &escape(pop(@urlslices));
17533: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
17534: }
17535:
17536: sub compare_arrays {
17537: my ($arrayref1,$arrayref2) = @_;
17538: my (@difference,%count);
17539: @difference = ();
17540: %count = ();
17541: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
17542: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
17543: foreach my $element (keys(%count)) {
17544: if ($count{$element} == 1) {
17545: push(@difference,$element);
17546: }
17547: }
17548: }
17549: return @difference;
17550: }
17551:
17552: sub lon_status_items {
17553: my %defaults = (
17554: E => 100,
17555: W => 4,
17556: N => 1,
17557: U => 5,
17558: threshold => 200,
17559: sysmail => 2500,
17560: );
17561: my %names = (
17562: E => 'Errors',
17563: W => 'Warnings',
17564: N => 'Notices',
17565: U => 'Unsent',
17566: );
17567: return (\%defaults,\%names);
17568: }
17569:
17570: # -------------------------------------------------------- Initialize user login
17571: sub init_user_environment {
17572: my ($r, $username, $domain, $authhost, $form, $args) = @_;
17573: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
17574:
17575: my $public=($username eq 'public' && $domain eq 'public');
17576:
17577: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
17578: $coauthorenv);
17579: my $now=time;
17580:
17581: if ($public) {
17582: my $max_public=100;
17583: my $oldest;
17584: my $oldest_time=0;
17585: for(my $next=1;$next<=$max_public;$next++) {
17586: if (-e $lonids."/publicuser_$next.id") {
17587: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
17588: if ($mtime<$oldest_time || !$oldest_time) {
17589: $oldest_time=$mtime;
17590: $oldest=$next;
17591: }
17592: } else {
17593: $cookie="publicuser_$next";
17594: last;
17595: }
17596: }
17597: if (!$cookie) { $cookie="publicuser_$oldest"; }
17598: } else {
17599: # See if old ID present, if so, remove if this isn't a robot,
17600: # killing any existing non-robot sessions
17601: if (!$args->{'robot'}) {
17602: opendir(DIR,$lonids);
17603: while ($filename=readdir(DIR)) {
17604: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
17605: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
17606: &GDBM_READER(),0640)) {
17607: my $linkedfile;
17608: if (exists($oldenv{'user.linkedenv'})) {
17609: $linkedfile = $oldenv{'user.linkedenv'};
17610: }
17611: untie(%oldenv);
17612: if (unlink("$lonids/$filename")) {
17613: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
17614: if (-l "$lonids/$linkedfile.id") {
17615: unlink("$lonids/$linkedfile.id");
17616: }
17617: }
17618: }
17619: } else {
17620: unlink($lonids.'/'.$filename);
17621: }
17622: }
17623: }
17624: closedir(DIR);
17625: # If there is a undeleted lockfile for the user's paste buffer remove it.
17626: my $namespace = 'nohist_courseeditor';
17627: my $lockingkey = 'paste'."\0".'locked_num';
17628: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
17629: $domain,$username);
17630: if (exists($lockhash{$lockingkey})) {
17631: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
17632: unless ($delresult eq 'ok') {
17633: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
17634: }
17635: }
17636: }
17637: # Give them a new cookie
17638: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
17639: : $now.$$.int(rand(10000)));
17640: $cookie="$username\_$id\_$domain\_$authhost";
17641:
17642: # Initialize roles
17643:
17644: ($userroles,$firstaccenv,$timerintenv,$coauthorenv) =
17645: &Apache::lonnet::rolesinit($domain,$username,$authhost);
17646: }
17647: # ------------------------------------ Check browser type and MathML capability
17648:
17649: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
17650: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
17651:
17652: # ------------------------------------------------------------- Get environment
17653:
17654: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
17655: my ($tmp) = keys(%userenv);
17656: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
17657: undef(%userenv);
17658: }
17659: if (($userenv{'interface'}) && (!$form->{'interface'})) {
17660: $form->{'interface'}=$userenv{'interface'};
17661: }
17662: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
17663:
17664: # --------------- Do not trust query string to be put directly into environment
17665: foreach my $option ('interface','localpath','localres') {
17666: $form->{$option}=~s/[\n\r\=]//gs;
17667: }
17668: # --------------------------------------------------------- Write first profile
17669:
17670: {
17671: my $ip = &Apache::lonnet::get_requestor_ip($r);
17672: my %initial_env =
17673: ("user.name" => $username,
17674: "user.domain" => $domain,
17675: "user.home" => $authhost,
17676: "browser.type" => $clientbrowser,
17677: "browser.version" => $clientversion,
17678: "browser.mathml" => $clientmathml,
17679: "browser.unicode" => $clientunicode,
17680: "browser.os" => $clientos,
17681: "browser.mobile" => $clientmobile,
17682: "browser.info" => $clientinfo,
17683: "browser.osversion" => $clientosversion,
17684: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
17685: "request.course.fn" => '',
17686: "request.course.uri" => '',
17687: "request.course.sec" => '',
17688: "request.role" => 'cm',
17689: "request.role.adv" => $env{'user.adv'},
17690: "request.host" => $ip,);
17691:
17692: if ($form->{'localpath'}) {
17693: $initial_env{"browser.localpath"} = $form->{'localpath'};
17694: $initial_env{"browser.localres"} = $form->{'localres'};
17695: }
17696:
17697: if ($form->{'interface'}) {
17698: $form->{'interface'}=~s/\W//gs;
17699: $initial_env{"browser.interface"} = $form->{'interface'};
17700: $env{'browser.interface'}=$form->{'interface'};
17701: }
17702:
17703: if ($form->{'iptoken'}) {
17704: my $lonhost = $r->dir_config('lonHostID');
17705: $initial_env{"user.noloadbalance"} = $lonhost;
17706: $env{'user.noloadbalance'} = $lonhost;
17707: }
17708:
17709: if ($form->{'noloadbalance'}) {
17710: my @hosts = &Apache::lonnet::current_machine_ids();
17711: my $hosthere = $form->{'noloadbalance'};
17712: if (grep(/^\Q$hosthere\E$/,@hosts)) {
17713: $initial_env{"user.noloadbalance"} = $hosthere;
17714: $env{'user.noloadbalance'} = $hosthere;
17715: }
17716: }
17717:
17718: unless ($domain eq 'public') {
17719: my %is_adv = ( is_adv => $env{'user.adv'} );
17720: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
17721:
17722: foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
17723: $userenv{'availabletools.'.$tool} =
17724: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
17725: undef,\%userenv,\%domdef,\%is_adv);
17726: }
17727:
17728: foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
17729: $userenv{'canrequest.'.$crstype} =
17730: &Apache::lonnet::usertools_access($username,$domain,$crstype,
17731: 'reload','requestcourses',
17732: \%userenv,\%domdef,\%is_adv);
17733: }
17734:
17735: $userenv{'canrequest.author'} =
17736: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
17737: 'reload','requestauthor',
17738: \%userenv,\%domdef,\%is_adv);
17739: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
17740: $domain,$username);
17741: my $reqstatus = $reqauthor{'author_status'};
17742: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
17743: if (ref($reqauthor{'author'}) eq 'HASH') {
17744: $userenv{'requestauthorqueued'} = $reqstatus.':'.
17745: $reqauthor{'author'}{'timestamp'};
17746: }
17747: }
17748: my ($types,$typename) = &course_types();
17749: if (ref($types) eq 'ARRAY') {
17750: my @options = ('approval','validate','autolimit');
17751: my $optregex = join('|',@options);
17752: my (%willtrust,%trustchecked);
17753: foreach my $type (@{$types}) {
17754: my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
17755: if ($dom_str ne '') {
17756: my $updatedstr = '';
17757: my @possdomains = split(',',$dom_str);
17758: foreach my $entry (@possdomains) {
17759: my ($extdom,$extopt) = split(':',$entry);
17760: unless ($trustchecked{$extdom}) {
17761: $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
17762: $trustchecked{$extdom} = 1;
17763: }
17764: if ($willtrust{$extdom}) {
17765: $updatedstr .= $entry.',';
17766: }
17767: }
17768: $updatedstr =~ s/,$//;
17769: if ($updatedstr) {
17770: $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
17771: } else {
17772: delete($userenv{'reqcrsotherdom.'.$type});
17773: }
17774: }
17775: }
17776: }
17777: }
17778: $env{'user.environment'} = "$lonids/$cookie.id";
17779:
17780: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
17781: &GDBM_WRCREAT(),0640)) {
17782: &_add_to_env(\%disk_env,\%initial_env);
17783: &_add_to_env(\%disk_env,\%userenv,'environment.');
17784: &_add_to_env(\%disk_env,$userroles);
17785: if (ref($firstaccenv) eq 'HASH') {
17786: &_add_to_env(\%disk_env,$firstaccenv);
17787: }
17788: if (ref($timerintenv) eq 'HASH') {
17789: &_add_to_env(\%disk_env,$timerintenv);
17790: }
17791: if (ref($coauthorenv) eq 'HASH') {
17792: if (keys(%{$coauthorenv})) {
17793: &_add_to_env(\%disk_env,$coauthorenv);
17794: }
17795: }
17796: if (ref($args->{'extra_env'})) {
17797: &_add_to_env(\%disk_env,$args->{'extra_env'});
17798: }
17799: untie(%disk_env);
17800: } else {
17801: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
17802: 'Could not create environment storage in lonauth: '.$!.'</span>');
17803: return 'error: '.$!;
17804: }
17805: }
17806: $env{'request.role'}='cm';
17807: $env{'request.role.adv'}=$env{'user.adv'};
17808: $env{'browser.type'}=$clientbrowser;
17809:
17810: return $cookie;
17811:
17812: }
17813:
17814: sub _add_to_env {
17815: my ($idf,$env_data,$prefix) = @_;
17816: if (ref($env_data) eq 'HASH') {
17817: while (my ($key,$value) = each(%$env_data)) {
17818: $idf->{$prefix.$key} = $value;
17819: $env{$prefix.$key} = $value;
17820: }
17821: }
17822: }
17823:
17824: # --- Get the symbolic name of a problem and the url
17825: sub get_symb {
17826: my ($request,$silent) = @_;
17827: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
17828: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
17829: if ($symb eq '') {
17830: if (!$silent) {
17831: if (ref($request)) {
17832: $request->print("Unable to handle ambiguous references:$url:.");
17833: }
17834: return ();
17835: }
17836: }
17837: &Apache::lonenc::check_decrypt(\$symb);
17838: return ($symb);
17839: }
17840:
17841: # --------------------------------------------------------------Get annotation
17842:
17843: sub get_annotation {
17844: my ($symb,$enc) = @_;
17845:
17846: my $key = $symb;
17847: if (!$enc) {
17848: $key =
17849: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
17850: }
17851: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
17852: return $annotation{$key};
17853: }
17854:
17855: sub clean_symb {
17856: my ($symb,$delete_enc) = @_;
17857:
17858: &Apache::lonenc::check_decrypt(\$symb);
17859: my $enc = $env{'request.enc'};
17860: if ($delete_enc) {
17861: delete($env{'request.enc'});
17862: }
17863:
17864: return ($symb,$enc);
17865: }
17866:
17867: ############################################################
17868: ############################################################
17869:
17870: =pod
17871:
17872: =head1 Routines for building display used to search for courses
17873:
17874:
17875: =over 4
17876:
17877: =item * &build_filters()
17878:
17879: Create markup for a table used to set filters to use when selecting
17880: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
17881: and quotacheck.pl
17882:
17883:
17884: Inputs:
17885:
17886: filterlist - anonymous array of fields to include as potential filters
17887:
17888: crstype - course type
17889:
17890: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
17891: to pop-open a course selector (will contain "extra element").
17892:
17893: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
17894:
17895: filter - anonymous hash of criteria and their values
17896:
17897: action - form action
17898:
17899: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
17900:
17901: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
17902:
17903: cloneruname - username of owner of new course who wants to clone
17904:
17905: clonerudom - domain of owner of new course who wants to clone
17906:
17907: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
17908:
17909: codetitlesref - reference to array of titles of components in institutional codes (official courses)
17910:
17911: codedom - domain
17912:
17913: formname - value of form element named "form".
17914:
17915: fixeddom - domain, if fixed.
17916:
17917: prevphase - value to assign to form element named "phase" when going back to the previous screen
17918:
17919: cnameelement - name of form element in form on opener page which will receive title of selected course
17920:
17921: cnumelement - name of form element in form on opener page which will receive courseID of selected course
17922:
17923: cdomelement - name of form element in form on opener page which will receive domain of selected course
17924:
17925: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
17926:
17927: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
17928:
17929: clonewarning - warning message about missing information for intended course owner when DC creates a course
17930:
17931:
17932: Returns: $output - HTML for display of search criteria, and hidden form elements.
17933:
17934:
17935: Side Effects: None
17936:
17937: =cut
17938:
17939: # ---------------------------------------------- search for courses based on last activity etc.
17940:
17941: sub build_filters {
17942: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
17943: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
17944: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
17945: $cnameelement,$cnumelement,$cdomelement,$setroles,
17946: $clonetext,$clonewarning) = @_;
17947: my ($list,$jscript);
17948: my $onchange = 'javascript:updateFilters(this)';
17949: my ($domainselectform,$sincefilterform,$createdfilterform,
17950: $ownerdomselectform,$persondomselectform,$instcodeform,
17951: $typeselectform,$instcodetitle);
17952: if ($formname eq '') {
17953: $formname = $caller;
17954: }
17955: foreach my $item (@{$filterlist}) {
17956: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
17957: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
17958: if ($item eq 'domainfilter') {
17959: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
17960: } elsif ($item eq 'coursefilter') {
17961: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
17962: } elsif ($item eq 'ownerfilter') {
17963: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17964: } elsif ($item eq 'ownerdomfilter') {
17965: $filter->{'ownerdomfilter'} =
17966: &LONCAPA::clean_domain($filter->{$item});
17967: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
17968: 'ownerdomfilter',1);
17969: } elsif ($item eq 'personfilter') {
17970: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
17971: } elsif ($item eq 'persondomfilter') {
17972: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
17973: 'persondomfilter',1);
17974: } else {
17975: $filter->{$item} =~ s/\W//g;
17976: }
17977: if (!$filter->{$item}) {
17978: $filter->{$item} = '';
17979: }
17980: }
17981: if ($item eq 'domainfilter') {
17982: my $allow_blank = 1;
17983: if ($formname eq 'portform') {
17984: $allow_blank=0;
17985: } elsif ($formname eq 'studentform') {
17986: $allow_blank=0;
17987: }
17988: if ($fixeddom) {
17989: $domainselectform = '<input type="hidden" name="domainfilter"'.
17990: ' value="'.$codedom.'" />'.
17991: &Apache::lonnet::domain($codedom,'description');
17992: } else {
17993: $domainselectform = &select_dom_form($filter->{$item},
17994: 'domainfilter',
17995: $allow_blank,'',$onchange);
17996: }
17997: } else {
17998: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
17999: }
18000: }
18001:
18002: # last course activity filter and selection
18003: $sincefilterform = &timebased_select_form('sincefilter',$filter);
18004:
18005: # course created filter and selection
18006: if (exists($filter->{'createdfilter'})) {
18007: $createdfilterform = &timebased_select_form('createdfilter',$filter);
18008: }
18009:
18010: my $prefix = $crstype;
18011: if ($crstype eq 'Placement') {
18012: $prefix = 'Placement Test'
18013: }
18014: my %lt = &Apache::lonlocal::texthash(
18015: 'cac' => "$prefix Activity",
18016: 'ccr' => "$prefix Created",
18017: 'cde' => "$prefix Title",
18018: 'cdo' => "$prefix Domain",
18019: 'ins' => 'Institutional Code',
18020: 'inc' => 'Institutional Categorization',
18021: 'cow' => "$prefix Owner/Co-owner",
18022: 'cop' => "$prefix Personnel Includes",
18023: 'cog' => 'Type',
18024: );
18025:
18026: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18027: my $typeval = 'Course';
18028: if ($crstype eq 'Community') {
18029: $typeval = 'Community';
18030: } elsif ($crstype eq 'Placement') {
18031: $typeval = 'Placement';
18032: }
18033: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
18034: } else {
18035: $typeselectform = '<select name="type" size="1"';
18036: if ($onchange) {
18037: $typeselectform .= ' onchange="'.$onchange.'"';
18038: }
18039: $typeselectform .= '>'."\n";
18040: foreach my $posstype ('Course','Community','Placement') {
18041: my $shown;
18042: if ($posstype eq 'Placement') {
18043: $shown = &mt('Placement Test');
18044: } else {
18045: $shown = &mt($posstype);
18046: }
18047: $typeselectform.='<option value="'.$posstype.'"'.
18048: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
18049: }
18050: $typeselectform.="</select>";
18051: }
18052:
18053: my ($cloneableonlyform,$cloneabletitle);
18054: if (exists($filter->{'cloneableonly'})) {
18055: my $cloneableon = '';
18056: my $cloneableoff = ' checked="checked"';
18057: if ($filter->{'cloneableonly'}) {
18058: $cloneableon = $cloneableoff;
18059: $cloneableoff = '';
18060: }
18061: $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>';
18062: if ($formname eq 'ccrs') {
18063: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
18064: } else {
18065: $cloneabletitle = &mt('Cloneable by you');
18066: }
18067: }
18068: my $officialjs;
18069: if ($crstype eq 'Course') {
18070: if (exists($filter->{'instcodefilter'})) {
18071: # if (($fixeddom) || ($formname eq 'requestcrs') ||
18072: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
18073: if ($codedom) {
18074: $officialjs = 1;
18075: ($instcodeform,$jscript,$$numtitlesref) =
18076: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
18077: $officialjs,$codetitlesref);
18078: if ($jscript) {
18079: $jscript = '<script type="text/javascript">'."\n".
18080: '// <![CDATA['."\n".
18081: $jscript."\n".
18082: '// ]]>'."\n".
18083: '</script>'."\n";
18084: }
18085: }
18086: if ($instcodeform eq '') {
18087: $instcodeform =
18088: '<input type="text" name="instcodefilter" size="10" value="'.
18089: $list->{'instcodefilter'}.'" />';
18090: $instcodetitle = $lt{'ins'};
18091: } else {
18092: $instcodetitle = $lt{'inc'};
18093: }
18094: if ($fixeddom) {
18095: $instcodetitle .= '<br />('.$codedom.')';
18096: }
18097: }
18098: }
18099: my $output = qq|
18100: <form method="post" name="filterpicker" action="$action">
18101: <input type="hidden" name="form" value="$formname" />
18102: |;
18103: if ($formname eq 'modifycourse') {
18104: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
18105: '<input type="hidden" name="prevphase" value="'.
18106: $prevphase.'" />'."\n";
18107: } elsif ($formname eq 'quotacheck') {
18108: $output .= qq|
18109: <input type="hidden" name="sortby" value="" />
18110: <input type="hidden" name="sortorder" value="" />
18111: |;
18112: } else {
18113: my $name_input;
18114: if ($cnameelement ne '') {
18115: $name_input = '<input type="hidden" name="cnameelement" value="'.
18116: $cnameelement.'" />';
18117: }
18118: $output .= qq|
18119: <input type="hidden" name="cnumelement" value="$cnumelement" />
18120: <input type="hidden" name="cdomelement" value="$cdomelement" />
18121: $name_input
18122: $roleelement
18123: $multelement
18124: $typeelement
18125: |;
18126: if ($formname eq 'portform') {
18127: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
18128: }
18129: }
18130: if ($fixeddom) {
18131: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
18132: }
18133: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
18134: if ($sincefilterform) {
18135: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
18136: .$sincefilterform
18137: .&Apache::lonhtmlcommon::row_closure();
18138: }
18139: if ($createdfilterform) {
18140: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
18141: .$createdfilterform
18142: .&Apache::lonhtmlcommon::row_closure();
18143: }
18144: if ($domainselectform) {
18145: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
18146: .$domainselectform
18147: .&Apache::lonhtmlcommon::row_closure();
18148: }
18149: if ($typeselectform) {
18150: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
18151: $output .= $typeselectform;
18152: } else {
18153: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
18154: .$typeselectform
18155: .&Apache::lonhtmlcommon::row_closure();
18156: }
18157: }
18158: if ($instcodeform) {
18159: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
18160: .$instcodeform
18161: .&Apache::lonhtmlcommon::row_closure();
18162: }
18163: if (exists($filter->{'ownerfilter'})) {
18164: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
18165: '<table><tr><td>'.&mt('Username').'<br />'.
18166: '<input type="text" name="ownerfilter" size="20" value="'.
18167: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18168: $ownerdomselectform.'</td></tr></table>'.
18169: &Apache::lonhtmlcommon::row_closure();
18170: }
18171: if (exists($filter->{'personfilter'})) {
18172: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
18173: '<table><tr><td>'.&mt('Username').'<br />'.
18174: '<input type="text" name="personfilter" size="20" value="'.
18175: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
18176: $persondomselectform.'</td></tr></table>'.
18177: &Apache::lonhtmlcommon::row_closure();
18178: }
18179: if (exists($filter->{'coursefilter'})) {
18180: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
18181: .'<input type="text" name="coursefilter" size="25" value="'
18182: .$list->{'coursefilter'}.'" />'
18183: .&Apache::lonhtmlcommon::row_closure();
18184: }
18185: if ($cloneableonlyform) {
18186: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
18187: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
18188: }
18189: if (exists($filter->{'descriptfilter'})) {
18190: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
18191: .'<input type="text" name="descriptfilter" size="40" value="'
18192: .$list->{'descriptfilter'}.'" />'
18193: .&Apache::lonhtmlcommon::row_closure(1);
18194: }
18195: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
18196: '<input type="hidden" name="updater" value="" />'."\n".
18197: '<input type="submit" name="gosearch" value="'.
18198: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
18199: return $jscript.$clonewarning.$output;
18200: }
18201:
18202: =pod
18203:
18204: =item * &timebased_select_form()
18205:
18206: Create markup for a dropdown list used to select a time-based
18207: filter e.g., Course Activity, Course Created, when searching for courses
18208: or communities
18209:
18210: Inputs:
18211:
18212: item - name of form element (sincefilter or createdfilter)
18213:
18214: filter - anonymous hash of criteria and their values
18215:
18216: Returns: HTML for a select box contained a blank, then six time selections,
18217: with value set in incoming form variables currently selected.
18218:
18219: Side Effects: None
18220:
18221: =cut
18222:
18223: sub timebased_select_form {
18224: my ($item,$filter) = @_;
18225: if (ref($filter) eq 'HASH') {
18226: $filter->{$item} =~ s/[^\d-]//g;
18227: if (!$filter->{$item}) { $filter->{$item}=-1; }
18228: return &select_form(
18229: $filter->{$item},
18230: $item,
18231: { '-1' => '',
18232: '86400' => &mt('today'),
18233: '604800' => &mt('last week'),
18234: '2592000' => &mt('last month'),
18235: '7776000' => &mt('last three months'),
18236: '15552000' => &mt('last six months'),
18237: '31104000' => &mt('last year'),
18238: 'select_form_order' =>
18239: ['-1','86400','604800','2592000','7776000',
18240: '15552000','31104000']});
18241: }
18242: }
18243:
18244: =pod
18245:
18246: =item * &js_changer()
18247:
18248: Create script tag containing Javascript used to submit course search form
18249: when course type or domain is changed, and also to hide 'Searching ...' on
18250: page load completion for page showing search result.
18251:
18252: Inputs: None
18253:
18254: Returns: markup containing updateFilters() and hideSearching() javascript functions.
18255:
18256: Side Effects: None
18257:
18258: =cut
18259:
18260: sub js_changer {
18261: return <<ENDJS;
18262: <script type="text/javascript">
18263: // <![CDATA[
18264: function updateFilters(caller) {
18265: if (typeof(caller) != "undefined") {
18266: document.filterpicker.updater.value = caller.name;
18267: }
18268: document.filterpicker.submit();
18269: }
18270:
18271: function hideSearching() {
18272: if (document.getElementById('searching')) {
18273: document.getElementById('searching').style.display = 'none';
18274: }
18275: return;
18276: }
18277:
18278: // ]]>
18279: </script>
18280:
18281: ENDJS
18282: }
18283:
18284: =pod
18285:
18286: =item * &search_courses()
18287:
18288: Process selected filters form course search form and pass to lonnet::courseiddump
18289: to retrieve a hash for which keys are courseIDs which match the selected filters.
18290:
18291: Inputs:
18292:
18293: dom - domain being searched
18294:
18295: type - course type ('Course' or 'Community' or '.' if any).
18296:
18297: filter - anonymous hash of criteria and their values
18298:
18299: numtitles - for institutional codes - number of categories
18300:
18301: cloneruname - optional username of new course owner
18302:
18303: clonerudom - optional domain of new course owner
18304:
18305: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
18306: (used when DC is using course creation form)
18307:
18308: codetitles - reference to array of titles of components in institutional codes (official courses).
18309:
18310: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
18311: (and so can clone automatically)
18312:
18313: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
18314:
18315: reqinstcode - institutional code of new course, where search_courses is used to identify potential
18316: courses to clone
18317:
18318: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
18319:
18320:
18321: Side Effects: None
18322:
18323: =cut
18324:
18325:
18326: sub search_courses {
18327: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
18328: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
18329: my (%courses,%showcourses,$cloner);
18330: if (($filter->{'ownerfilter'} ne '') ||
18331: ($filter->{'ownerdomfilter'} ne '')) {
18332: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
18333: $filter->{'ownerdomfilter'};
18334: }
18335: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
18336: if (!$filter->{$item}) {
18337: $filter->{$item}='.';
18338: }
18339: }
18340: my $now = time;
18341: my $timefilter =
18342: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
18343: my ($createdbefore,$createdafter);
18344: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
18345: $createdbefore = $now;
18346: $createdafter = $now-$filter->{'createdfilter'};
18347: }
18348: my ($instcodefilter,$regexpok);
18349: if ($numtitles) {
18350: if ($env{'form.official'} eq 'on') {
18351: $instcodefilter =
18352: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18353: $regexpok = 1;
18354: } elsif ($env{'form.official'} eq 'off') {
18355: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
18356: unless ($instcodefilter eq '') {
18357: $regexpok = -1;
18358: }
18359: }
18360: } else {
18361: $instcodefilter = $filter->{'instcodefilter'};
18362: }
18363: if ($instcodefilter eq '') { $instcodefilter = '.'; }
18364: if ($type eq '') { $type = '.'; }
18365:
18366: if (($clonerudom ne '') && ($cloneruname ne '')) {
18367: $cloner = $cloneruname.':'.$clonerudom;
18368: }
18369: %courses = &Apache::lonnet::courseiddump($dom,
18370: $filter->{'descriptfilter'},
18371: $timefilter,
18372: $instcodefilter,
18373: $filter->{'combownerfilter'},
18374: $filter->{'coursefilter'},
18375: undef,undef,$type,$regexpok,undef,undef,
18376: undef,undef,$cloner,$cc_clone,
18377: $filter->{'cloneableonly'},
18378: $createdbefore,$createdafter,undef,
18379: $domcloner,undef,$reqcrsdom,$reqinstcode);
18380: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
18381: my $ccrole;
18382: if ($type eq 'Community') {
18383: $ccrole = 'co';
18384: } else {
18385: $ccrole = 'cc';
18386: }
18387: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
18388: $filter->{'persondomfilter'},
18389: 'userroles',undef,
18390: [$ccrole,'in','ad','ep','ta','cr'],
18391: $dom);
18392: foreach my $role (keys(%rolehash)) {
18393: my ($cnum,$cdom,$courserole) = split(':',$role);
18394: my $cid = $cdom.'_'.$cnum;
18395: if (exists($courses{$cid})) {
18396: if (ref($courses{$cid}) eq 'HASH') {
18397: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
18398: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
18399: push(@{$courses{$cid}{roles}},$courserole);
18400: }
18401: } else {
18402: $courses{$cid}{roles} = [$courserole];
18403: }
18404: $showcourses{$cid} = $courses{$cid};
18405: }
18406: }
18407: }
18408: %courses = %showcourses;
18409: }
18410: return %courses;
18411: }
18412:
18413: =pod
18414:
18415: =back
18416:
18417: =head1 Routines for version requirements for current course.
18418:
18419: =over 4
18420:
18421: =item * &check_release_required()
18422:
18423: Compares required LON-CAPA version with version on server, and
18424: if required version is newer looks for a server with the required version.
18425:
18426: Looks first at servers in user's owen domain; if none suitable, looks at
18427: servers in course's domain are permitted to host sessions for user's domain.
18428:
18429: Inputs:
18430:
18431: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18432:
18433: $courseid - Course ID of current course
18434:
18435: $rolecode - User's current role in course (for switchserver query string).
18436:
18437: $required - LON-CAPA version needed by course (format: Major.Minor).
18438:
18439:
18440: Returns:
18441:
18442: $switchserver - query string tp append to /adm/switchserver call (if
18443: current server's LON-CAPA version is too old.
18444:
18445: $warning - Message is displayed if no suitable server could be found.
18446:
18447: =cut
18448:
18449: sub check_release_required {
18450: my ($loncaparev,$courseid,$rolecode,$required) = @_;
18451: my ($switchserver,$warning);
18452: if ($required ne '') {
18453: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
18454: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18455: if ($reqdmajor ne '' && $reqdminor ne '') {
18456: my $otherserver;
18457: if (($major eq '' && $minor eq '') ||
18458: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
18459: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
18460: my $switchlcrev =
18461: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
18462: $userdomserver);
18463: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
18464: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
18465: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
18466: my $cdom = $env{'course.'.$courseid.'.domain'};
18467: if ($cdom ne $env{'user.domain'}) {
18468: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
18469: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
18470: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
18471: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
18472: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
18473: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
18474: my $canhost =
18475: &Apache::lonnet::can_host_session($env{'user.domain'},
18476: $coursedomserver,
18477: $remoterev,
18478: $udomdefaults{'remotesessions'},
18479: $defdomdefaults{'hostedsessions'});
18480:
18481: if ($canhost) {
18482: $otherserver = $coursedomserver;
18483: } else {
18484: $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.");
18485: }
18486: } else {
18487: $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).");
18488: }
18489: } else {
18490: $otherserver = $userdomserver;
18491: }
18492: }
18493: if ($otherserver ne '') {
18494: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
18495: }
18496: }
18497: }
18498: return ($switchserver,$warning);
18499: }
18500:
18501: =pod
18502:
18503: =item * &check_release_result()
18504:
18505: Inputs:
18506:
18507: $switchwarning - Warning message if no suitable server found to host session.
18508:
18509: $switchserver - query string to append to /adm/switchserver containing lonHostID
18510: and current role.
18511:
18512: Returns: HTML to display with information about requirement to switch server.
18513: Either displaying warning with link to Roles/Courses screen or
18514: display link to switchserver.
18515:
18516: =cut
18517:
18518: sub check_release_result {
18519: my ($switchwarning,$switchserver) = @_;
18520: my $output = &start_page('Selected course unavailable on this server').
18521: '<p class="LC_warning">';
18522: if ($switchwarning) {
18523: $output .= $switchwarning.'<br /><a href="/adm/roles">';
18524: if (&show_course()) {
18525: $output .= &mt('Display courses');
18526: } else {
18527: $output .= &mt('Display roles');
18528: }
18529: $output .= '</a>';
18530: } elsif ($switchserver) {
18531: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
18532: '<br />'.
18533: '<a href="/adm/switchserver?'.$switchserver.'">'.
18534: &mt('Switch Server').
18535: '</a>';
18536: }
18537: $output .= '</p>'.&end_page();
18538: return $output;
18539: }
18540:
18541: =pod
18542:
18543: =item * &needs_coursereinit()
18544:
18545: Determine if course contents stored for user's session needs to be
18546: refreshed, because content has changed since "Big Hash" last tied.
18547:
18548: Check for change is made if time last checked is more than 10 minutes ago
18549: (by default).
18550:
18551: Inputs:
18552:
18553: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
18554:
18555: $interval (optional) - Time which may elapse (in s) between last check for content
18556: change in current course. (default: 600 s).
18557:
18558: Returns: an array; first element is:
18559:
18560: =over 4
18561:
18562: 'switch' - if content updates mean user's session
18563: needs to be switched to a server running a newer LON-CAPA version
18564:
18565: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
18566: on current server hosting user's session
18567:
18568: '' - if no action required.
18569:
18570: =back
18571:
18572: If first item element is 'switch':
18573:
18574: second item is $switchwarning - Warning message if no suitable server found to host session.
18575:
18576: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
18577: and current role.
18578:
18579: otherwise: no other elements returned.
18580:
18581: =back
18582:
18583: =cut
18584:
18585: sub needs_coursereinit {
18586: my ($loncaparev,$interval) = @_;
18587: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
18588: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18589: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18590: my $now = time;
18591: if ($interval eq '') {
18592: $interval = 600;
18593: }
18594: if (($now-$env{'request.course.timechecked'})>$interval) {
18595: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
18596: my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
18597: if ($blocked) {
18598: return ();
18599: }
18600: my $update;
18601: my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
18602: my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
18603: if ($lastmainchange > $env{'request.course.tied'}) {
18604: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18605: if ($needswitch) {
18606: return ('switch',$switchwarning,$switchserver);
18607: }
18608: $update = 'main';
18609: }
18610: if ($lastsuppchange > $env{'request.course.suppupdated'}) {
18611: if ($update) {
18612: $update = 'both';
18613: } else {
18614: my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
18615: if ($needswitch) {
18616: return ('switch',$switchwarning,$switchserver);
18617: } else {
18618: $update = 'supp';
18619: }
18620: }
18621: return ($update);
18622: }
18623: }
18624: return ();
18625: }
18626:
18627: sub switch_for_update {
18628: my ($loncaparev,$cdom,$cnum) = @_;
18629: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18630: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
18631: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
18632: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
18633: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
18634: $curr_reqd_hash{'internal.releaserequired'}});
18635: my ($switchserver,$switchwarning) =
18636: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
18637: $curr_reqd_hash{'internal.releaserequired'});
18638: if ($switchwarning ne '' || $switchserver ne '') {
18639: return ('switch',$switchwarning,$switchserver);
18640: }
18641: }
18642: }
18643: return ();
18644: }
18645:
18646: sub update_content_constraints {
18647: my ($cdom,$cnum,$chome,$cid) = @_;
18648: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
18649: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
18650: my (%checkresponsetypes,%checkcrsrestypes);
18651: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
18652: my ($item,$name,$value) = split(/:/,$key);
18653: if ($item eq 'resourcetag') {
18654: if ($name eq 'responsetype') {
18655: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
18656: }
18657: } elsif ($item eq 'course') {
18658: if ($name eq 'courserestype') {
18659: $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
18660: }
18661: }
18662: }
18663: my $navmap = Apache::lonnavmaps::navmap->new();
18664: if (defined($navmap)) {
18665: my (%allresponses,%allcrsrestypes);
18666: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
18667: if ($res->is_tool()) {
18668: if ($allcrsrestypes{'exttool'}) {
18669: $allcrsrestypes{'exttool'} ++;
18670: } else {
18671: $allcrsrestypes{'exttool'} = 1;
18672: }
18673: next;
18674: }
18675: my %responses = $res->responseTypes();
18676: foreach my $key (keys(%responses)) {
18677: next unless(exists($checkresponsetypes{$key}));
18678: $allresponses{$key} += $responses{$key};
18679: }
18680: }
18681: foreach my $key (keys(%allresponses)) {
18682: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
18683: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18684: ($reqdmajor,$reqdminor) = ($major,$minor);
18685: }
18686: }
18687: foreach my $key (keys(%allcrsrestypes)) {
18688: my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
18689: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18690: ($reqdmajor,$reqdminor) = ($major,$minor);
18691: }
18692: }
18693: undef($navmap);
18694: }
18695: if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
18696: my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
18697: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
18698: ($reqdmajor,$reqdminor) = ($major,$minor);
18699: }
18700: }
18701: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
18702: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
18703: }
18704: return;
18705: }
18706:
18707: sub allmaps_incourse {
18708: my ($cdom,$cnum,$chome,$cid) = @_;
18709: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
18710: $cid = $env{'request.course.id'};
18711: $cdom = $env{'course.'.$cid.'.domain'};
18712: $cnum = $env{'course.'.$cid.'.num'};
18713: $chome = $env{'course.'.$cid.'.home'};
18714: }
18715: my %allmaps = ();
18716: my $lastchange =
18717: &Apache::lonnet::get_coursechange($cdom,$cnum);
18718: if ($lastchange > $env{'request.course.tied'}) {
18719: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
18720: unless ($ferr) {
18721: &update_content_constraints($cdom,$cnum,$chome,$cid);
18722: }
18723: }
18724: my $navmap = Apache::lonnavmaps::navmap->new();
18725: if (defined($navmap)) {
18726: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
18727: $allmaps{$res->src()} = 1;
18728: }
18729: }
18730: return \%allmaps;
18731: }
18732:
18733: sub parse_supplemental_title {
18734: my ($title) = @_;
18735:
18736: my ($foldertitle,$renametitle);
18737: if ($title =~ /&&&/) {
18738: $title = &HTML::Entites::decode($title);
18739: }
18740: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
18741: $renametitle=$4;
18742: my ($time,$uname,$udom) = ($1,$2,$3);
18743: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
18744: my $name = &plainname($uname,$udom);
18745: $name = &HTML::Entities::encode($name,'"<>&\'');
18746: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
18747: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
18748: if ($foldertitle ne '') {
18749: $title .= ': <br />'.$foldertitle;
18750: }
18751: }
18752: if (wantarray) {
18753: return ($title,$foldertitle,$renametitle);
18754: }
18755: return $title;
18756: }
18757:
18758: sub get_supplemental {
18759: my ($cnum,$cdom,$ignorecache,$possdel)=@_;
18760: my $hashid=$cnum.':'.$cdom;
18761: my ($supplemental,$cached,$set_httprefs);
18762: unless ($ignorecache) {
18763: ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
18764: }
18765: unless (defined($cached)) {
18766: my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
18767: unless ($chome eq 'no_host') {
18768: my @order = @LONCAPA::map::order;
18769: my @resources = @LONCAPA::map::resources;
18770: my @resparms = @LONCAPA::map::resparms;
18771: my @zombies = @LONCAPA::map::zombies;
18772: my ($errors,%ids,%hidden);
18773: $errors =
18774: &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
18775: $errors,$possdel,\%ids,\%hidden);
18776: @LONCAPA::map::order = @order;
18777: @LONCAPA::map::resources = @resources;
18778: @LONCAPA::map::resparms = @resparms;
18779: @LONCAPA::map::zombies = @zombies;
18780: $set_httprefs = 1;
18781: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18782: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18783: }
18784: $supplemental = {
18785: ids => \%ids,
18786: hidden => \%hidden,
18787: };
18788: &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
18789: }
18790: }
18791: return ($supplemental,$set_httprefs);
18792: }
18793:
18794: sub recurse_supplemental {
18795: my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
18796: if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
18797: my $mapnum;
18798: if ($suppmap eq 'supplemental.sequence') {
18799: $mapnum = 0;
18800: } else {
18801: ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
18802: }
18803: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
18804: if ($fatal) {
18805: $errors ++;
18806: } else {
18807: my @order = @LONCAPA::map::order;
18808: if (@order > 0) {
18809: my @resources = @LONCAPA::map::resources;
18810: my @resparms = @LONCAPA::map::resparms;
18811: foreach my $idx (@order) {
18812: my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
18813: if (($src ne '') && ($status eq 'res')) {
18814: my $id = $mapnum.':'.$idx;
18815: push(@{$suppids->{$src}},$id);
18816: if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
18817: $hiddensupp->{$id} = 1;
18818: }
18819: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
18820: $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
18821: $hiddensupp,$hiddensupp->{$id});
18822: } else {
18823: my $allowed;
18824: if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
18825: $allowed = 1;
18826: } elsif ($possdel) {
18827: foreach my $item (@{$suppids->{$src}}) {
18828: next if ($item eq $id);
18829: unless ($hiddensupp->{$item}) {
18830: $allowed = 1;
18831: last;
18832: }
18833: }
18834: if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
18835: &Apache::lonnet::delenv('httpref.'.$src);
18836: }
18837: }
18838: if ($allowed && (!exists($env{'httpref.'.$src}))) {
18839: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18840: }
18841: }
18842: }
18843: }
18844: }
18845: }
18846: }
18847: return $errors;
18848: }
18849:
18850: sub set_supp_httprefs {
18851: my ($cnum,$cdom,$supplemental,$possdel) = @_;
18852: if (ref($supplemental) eq 'HASH') {
18853: if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
18854: foreach my $src (keys(%{$supplemental->{'ids'}})) {
18855: next if ($src =~ /\.sequence$/);
18856: if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
18857: my $allowed;
18858: if ($env{'request.role.adv'}) {
18859: $allowed = 1;
18860: } else {
18861: foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
18862: unless ($supplemental->{'hidden'}->{$id}) {
18863: $allowed = 1;
18864: last;
18865: }
18866: }
18867: }
18868: if (exists($env{'httpref.'.$src})) {
18869: if ($possdel) {
18870: unless ($allowed) {
18871: &Apache::lonnet::delenv('httpref.'.$src);
18872: }
18873: }
18874: } elsif ($allowed) {
18875: &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
18876: }
18877: }
18878: }
18879: if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
18880: &Apache::lonnet::appenv({'request.course.suppupdated' => time});
18881: }
18882: }
18883: }
18884: }
18885:
18886: sub get_supp_parameter {
18887: my ($resparm,$name)=@_;
18888: return if ($resparm eq '');
18889: my $value=undef;
18890: my $ptype=undef;
18891: foreach (split('&&&',$resparm)) {
18892: my ($thistype,$thisname,$thisvalue)=split('___',$_);
18893: if ($thisname eq $name) {
18894: $value=$thisvalue;
18895: $ptype=$thistype;
18896: }
18897: }
18898: return $value;
18899: }
18900:
18901: sub symb_to_docspath {
18902: my ($symb,$navmapref) = @_;
18903: return unless ($symb && ref($navmapref));
18904: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
18905: if ($resurl=~/\.(sequence|page)$/) {
18906: $mapurl=$resurl;
18907: } elsif ($resurl eq 'adm/navmaps') {
18908: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
18909: }
18910: my $mapresobj;
18911: unless (ref($$navmapref)) {
18912: $$navmapref = Apache::lonnavmaps::navmap->new();
18913: }
18914: if (ref($$navmapref)) {
18915: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
18916: }
18917: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
18918: my $type=$2;
18919: my $path;
18920: if (ref($mapresobj)) {
18921: my $pcslist = $mapresobj->map_hierarchy();
18922: if ($pcslist ne '') {
18923: foreach my $pc (split(/,/,$pcslist)) {
18924: next if ($pc <= 1);
18925: my $res = $$navmapref->getByMapPc($pc);
18926: if (ref($res)) {
18927: my $thisurl = $res->src();
18928: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
18929: my $thistitle = $res->title();
18930: $path .= '&'.
18931: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
18932: &escape($thistitle).
18933: ':'.$res->randompick().
18934: ':'.$res->randomout().
18935: ':'.$res->encrypted().
18936: ':'.$res->randomorder().
18937: ':'.$res->is_page();
18938: }
18939: }
18940: }
18941: $path =~ s/^\&//;
18942: my $maptitle = $mapresobj->title();
18943: if ($mapurl eq 'default') {
18944: $maptitle = 'Main Content';
18945: }
18946: $path .= (($path ne '')? '&' : '').
18947: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18948: &escape($maptitle).
18949: ':'.$mapresobj->randompick().
18950: ':'.$mapresobj->randomout().
18951: ':'.$mapresobj->encrypted().
18952: ':'.$mapresobj->randomorder().
18953: ':'.$mapresobj->is_page();
18954: } else {
18955: my $maptitle = &Apache::lonnet::gettitle($mapurl);
18956: my $ispage = (($type eq 'page')? 1 : '');
18957: if ($mapurl eq 'default') {
18958: $maptitle = 'Main Content';
18959: }
18960: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
18961: &escape($maptitle).':::::'.$ispage;
18962: }
18963: unless ($mapurl eq 'default') {
18964: $path = 'default&'.
18965: &escape('Main Content').
18966: ':::::&'.$path;
18967: }
18968: return $path;
18969: }
18970:
18971: sub validate_folderpath {
18972: my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
18973: if ($env{'form.folderpath'} ne '') {
18974: my @items = split(/\&/,$env{'form.folderpath'});
18975: my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
18976: for (my $i=0; $i<@items; $i++) {
18977: my $odd = $i%2;
18978: if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
18979: $badpath = 1;
18980: } elsif ($odd && $supplementalflag) {
18981: my $idx = $i-1;
18982: if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
18983: my $esc_name = $1;
18984: if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
18985: $supppath .= '&'.$esc_name;
18986: $changed = 1;
18987: } else {
18988: $supppath .= '&'.$items[$i];
18989: }
18990: } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
18991: $changed = 1;
18992: my $is_hidden;
18993: unless ($got_supp) {
18994: my ($supplemental) = &get_supplemental($coursenum,$coursedom);
18995: if (ref($supplemental) eq 'HASH') {
18996: if (ref($supplemental->{'hidden'}) eq 'HASH') {
18997: %supphidden = %{$supplemental->{'hidden'}};
18998: }
18999: if (ref($supplemental->{'ids'}) eq 'HASH') {
19000: %suppids = %{$supplemental->{'ids'}};
19001: }
19002: }
19003: $got_supp = 1;
19004: }
19005: if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
19006: my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
19007: if ($supphidden{$mapid}) {
19008: $is_hidden = 1;
19009: }
19010: }
19011: $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
19012: } else {
19013: $supppath .= '&'.$items[$i];
19014: }
19015: } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
19016: $badpath = 1;
19017: } elsif ($supplementalflag) {
19018: $supppath .= '&'.$items[$i];
19019: }
19020: last if ($badpath);
19021: }
19022: if ($badpath) {
19023: delete($env{'form.folderpath'});
19024: } elsif ($changed && $supplementalflag) {
19025: $supppath =~ s/^\&//;
19026: $env{'form.folderpath'} = $supppath;
19027: }
19028: }
19029: return;
19030: }
19031:
19032: sub captcha_display {
19033: my ($context,$lonhost,$defdom) = @_;
19034: my ($output,$error);
19035: my ($captcha,$pubkey,$privkey,$version) =
19036: &get_captcha_config($context,$lonhost,$defdom);
19037: if ($captcha eq 'original') {
19038: $output = &create_captcha();
19039: unless ($output) {
19040: $error = 'captcha';
19041: }
19042: } elsif ($captcha eq 'recaptcha') {
19043: $output = &create_recaptcha($pubkey,$version);
19044: unless ($output) {
19045: $error = 'recaptcha';
19046: }
19047: }
19048: return ($output,$error,$captcha,$version);
19049: }
19050:
19051: sub captcha_response {
19052: my ($context,$lonhost,$defdom) = @_;
19053: my ($captcha_chk,$captcha_error);
19054: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
19055: if ($captcha eq 'original') {
19056: ($captcha_chk,$captcha_error) = &check_captcha();
19057: } elsif ($captcha eq 'recaptcha') {
19058: $captcha_chk = &check_recaptcha($privkey,$version);
19059: } else {
19060: $captcha_chk = 1;
19061: }
19062: return ($captcha_chk,$captcha_error);
19063: }
19064:
19065: sub get_captcha_config {
19066: my ($context,$lonhost,$dom_in_effect) = @_;
19067: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
19068: my $hostname = &Apache::lonnet::hostname($lonhost);
19069: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
19070: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
19071: if ($context eq 'usercreation') {
19072: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
19073: if (ref($domconfig{$context}) eq 'HASH') {
19074: $hashtocheck = $domconfig{$context}{'cancreate'};
19075: if (ref($hashtocheck) eq 'HASH') {
19076: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
19077: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
19078: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
19079: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
19080: }
19081: if ($privkey && $pubkey) {
19082: $captcha = 'recaptcha';
19083: $version = $hashtocheck->{'recaptchaversion'};
19084: if ($version ne '2') {
19085: $version = 1;
19086: }
19087: } else {
19088: $captcha = 'original';
19089: }
19090: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
19091: $captcha = 'original';
19092: }
19093: }
19094: } else {
19095: $captcha = 'captcha';
19096: }
19097: } elsif ($context eq 'login') {
19098: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
19099: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
19100: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
19101: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
19102: if ($privkey && $pubkey) {
19103: $captcha = 'recaptcha';
19104: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
19105: if ($version ne '2') {
19106: $version = 1;
19107: }
19108: } else {
19109: $captcha = 'original';
19110: }
19111: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
19112: $captcha = 'original';
19113: }
19114: } elsif ($context eq 'passwords') {
19115: if ($dom_in_effect) {
19116: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
19117: if ($passwdconf{'captcha'} eq 'recaptcha') {
19118: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
19119: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
19120: $privkey = $passwdconf{'recaptchakeys'}{'private'};
19121: }
19122: if ($privkey && $pubkey) {
19123: $captcha = 'recaptcha';
19124: $version = $passwdconf{'recaptchaversion'};
19125: if ($version ne '2') {
19126: $version = 1;
19127: }
19128: } else {
19129: $captcha = 'original';
19130: }
19131: } elsif ($passwdconf{'captcha'} ne 'notused') {
19132: $captcha = 'original';
19133: }
19134: }
19135: }
19136: return ($captcha,$pubkey,$privkey,$version);
19137: }
19138:
19139: sub create_captcha {
19140: my %captcha_params = &captcha_settings();
19141: my ($output,$maxtries,$tries) = ('',10,0);
19142: while ($tries < $maxtries) {
19143: $tries ++;
19144: my $captcha = Authen::Captcha->new (
19145: output_folder => $captcha_params{'output_dir'},
19146: data_folder => $captcha_params{'db_dir'},
19147: );
19148: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
19149:
19150: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
19151: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
19152: '<span class="LC_nobreak">'.
19153: &mt('Type in the letters/numbers shown below').' '.
19154: '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
19155: '</span><br />'.
19156: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
19157: last;
19158: }
19159: }
19160: if ($output eq '') {
19161: &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
19162: }
19163: return $output;
19164: }
19165:
19166: sub captcha_settings {
19167: my %captcha_params = (
19168: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
19169: www_output_dir => "/captchaspool",
19170: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
19171: numchars => '5',
19172: );
19173: return %captcha_params;
19174: }
19175:
19176: sub check_captcha {
19177: my ($captcha_chk,$captcha_error);
19178: my $code = $env{'form.code'};
19179: my $md5sum = $env{'form.crypt'};
19180: my %captcha_params = &captcha_settings();
19181: my $captcha = Authen::Captcha->new(
19182: output_folder => $captcha_params{'output_dir'},
19183: data_folder => $captcha_params{'db_dir'},
19184: );
19185: $captcha_chk = $captcha->check_code($code,$md5sum);
19186: my %captcha_hash = (
19187: 0 => 'Code not checked (file error)',
19188: -1 => 'Failed: code expired',
19189: -2 => 'Failed: invalid code (not in database)',
19190: -3 => 'Failed: invalid code (code does not match crypt)',
19191: );
19192: if ($captcha_chk != 1) {
19193: $captcha_error = $captcha_hash{$captcha_chk}
19194: }
19195: return ($captcha_chk,$captcha_error);
19196: }
19197:
19198: sub create_recaptcha {
19199: my ($pubkey,$version) = @_;
19200: if ($version >= 2) {
19201: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
19202: '<div style="padding:0;clear:both;margin:0;border:0"></div>';
19203: } else {
19204: my $use_ssl;
19205: if ($ENV{'SERVER_PORT'} == 443) {
19206: $use_ssl = 1;
19207: }
19208: my $captcha = Captcha::reCAPTCHA->new;
19209: return $captcha->get_options_setter({theme => 'white'})."\n".
19210: $captcha->get_html($pubkey,undef,$use_ssl).
19211: &mt('If the text is hard to read, [_1] will replace them.',
19212: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
19213: '<br /><br />';
19214: }
19215: }
19216:
19217: sub check_recaptcha {
19218: my ($privkey,$version) = @_;
19219: my $captcha_chk;
19220: my $ip = &Apache::lonnet::get_requestor_ip();
19221: if ($version >= 2) {
19222: my %info = (
19223: secret => $privkey,
19224: response => $env{'form.g-recaptcha-response'},
19225: remoteip => $ip,
19226: );
19227: my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
19228: $request->content(join('&',map {
19229: my $name = escape($_);
19230: "$name=" . ( ref($info{$_}) eq 'ARRAY'
19231: ? join("&$name=", map {escape($_) } @{$info{$_}})
19232: : &escape($info{$_}) );
19233: } keys(%info)));
19234: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
19235: if ($response->is_success) {
19236: my $data = JSON::DWIW->from_json($response->decoded_content);
19237: if (ref($data) eq 'HASH') {
19238: if ($data->{'success'}) {
19239: $captcha_chk = 1;
19240: }
19241: }
19242: }
19243: } else {
19244: my $captcha = Captcha::reCAPTCHA->new;
19245: my $captcha_result =
19246: $captcha->check_answer(
19247: $privkey,
19248: $ip,
19249: $env{'form.recaptcha_challenge_field'},
19250: $env{'form.recaptcha_response_field'},
19251: );
19252: if ($captcha_result->{is_valid}) {
19253: $captcha_chk = 1;
19254: }
19255: }
19256: return $captcha_chk;
19257: }
19258:
19259: sub emailusername_info {
19260: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
19261: my %titles = &Apache::lonlocal::texthash (
19262: lastname => 'Last Name',
19263: firstname => 'First Name',
19264: institution => 'School/college/university',
19265: location => "School's city, state/province, country",
19266: web => "School's web address",
19267: officialemail => 'E-mail address at institution (if different)',
19268: id => 'Student/Employee ID',
19269: );
19270: return (\@fields,\%titles);
19271: }
19272:
19273: sub cleanup_html {
19274: my ($incoming) = @_;
19275: my $outgoing;
19276: if ($incoming ne '') {
19277: $outgoing = $incoming;
19278: $outgoing =~ s/;/;/g;
19279: $outgoing =~ s/\#/#/g;
19280: $outgoing =~ s/\&/&/g;
19281: $outgoing =~ s/</</g;
19282: $outgoing =~ s/>/>/g;
19283: $outgoing =~ s/\(/(/g;
19284: $outgoing =~ s/\)/)/g;
19285: $outgoing =~ s/"/"/g;
19286: $outgoing =~ s/'/'/g;
19287: $outgoing =~ s/\$/$/g;
19288: $outgoing =~ s{/}{/}g;
19289: $outgoing =~ s/=/=/g;
19290: $outgoing =~ s/\\/\/g
19291: }
19292: return $outgoing;
19293: }
19294:
19295: # Checks for critical messages and returns a redirect url if one exists.
19296: # $interval indicates how often to check for messages.
19297: # $context is the calling context -- roles, grades, contents, menu or flip.
19298: sub critical_redirect {
19299: my ($interval,$context) = @_;
19300: unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
19301: return ();
19302: }
19303: if ((time-$env{'user.criticalcheck.time'})>$interval) {
19304: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
19305: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
19306: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
19307: my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
19308: if ($blocked) {
19309: my $checkrole = "cm./$cdom/$cnum";
19310: if ($env{'request.course.sec'} ne '') {
19311: $checkrole .= "/$env{'request.course.sec'}";
19312: }
19313: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
19314: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
19315: return;
19316: }
19317: }
19318: }
19319: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
19320: $env{'user.name'});
19321: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
19322: my $redirecturl;
19323: if ($what[0]) {
19324: if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
19325: $redirecturl='/adm/email?critical=display';
19326: my $url=&Apache::lonnet::absolute_url().$redirecturl;
19327: return (1, $url);
19328: }
19329: }
19330: }
19331: return ();
19332: }
19333:
19334: # Use:
19335: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
19336: #
19337: ##################################################
19338: # password associated functions #
19339: ##################################################
19340: sub des_keys {
19341: # Make a new key for DES encryption.
19342: # Each key has two parts which are returned separately.
19343: # Please note: Each key must be passed through the &hex function
19344: # before it is output to the web browser. The hex versions cannot
19345: # be used to decrypt.
19346: my @hexstr=('0','1','2','3','4','5','6','7',
19347: '8','9','a','b','c','d','e','f');
19348: my $lkey='';
19349: for (0..7) {
19350: $lkey.=$hexstr[rand(15)];
19351: }
19352: my $ukey='';
19353: for (0..7) {
19354: $ukey.=$hexstr[rand(15)];
19355: }
19356: return ($lkey,$ukey);
19357: }
19358:
19359: sub des_decrypt {
19360: my ($key,$cyphertext) = @_;
19361: my $keybin=pack("H16",$key);
19362: my $cypher;
19363: if ($Crypt::DES::VERSION>=2.03) {
19364: $cypher=new Crypt::DES $keybin;
19365: } else {
19366: $cypher=new DES $keybin;
19367: }
19368: my $plaintext='';
19369: my $cypherlength = length($cyphertext);
19370: my $numchunks = int($cypherlength/32);
19371: for (my $j=0; $j<$numchunks; $j++) {
19372: my $start = $j*32;
19373: my $cypherblock = substr($cyphertext,$start,32);
19374: my $chunk =
19375: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
19376: $chunk .=
19377: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
19378: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
19379: $plaintext .= $chunk;
19380: }
19381: return $plaintext;
19382: }
19383:
19384: sub get_requested_shorturls {
19385: my ($cdom,$cnum,$navmap) = @_;
19386: return unless (ref($navmap));
19387: my ($numnew,$errors);
19388: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
19389: if (@toshorten) {
19390: my (%maps,%resources,%titles);
19391: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
19392: 'shorturls',$cdom,$cnum);
19393: if (keys(%resources)) {
19394: my %tocreate;
19395: foreach my $item (sort {$a <=> $b} (@toshorten)) {
19396: my $symb = $resources{$item};
19397: if ($symb) {
19398: $tocreate{$cnum.'&'.$symb} = 1;
19399: }
19400: }
19401: if (keys(%tocreate)) {
19402: ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
19403: \%tocreate);
19404: }
19405: }
19406: }
19407: return ($numnew,$errors);
19408: }
19409:
19410: sub make_short_symbs {
19411: my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
19412: my ($numnew,@errors);
19413: if (ref($tocreateref) eq 'HASH') {
19414: my %tocreate = %{$tocreateref};
19415: if (keys(%tocreate)) {
19416: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
19417: my $su = Short::URL->new(no_vowels => 1);
19418: my $init = '';
19419: my (%newunique,%addcourse,%courseonly,%failed);
19420: # get lock on tiny db
19421: my $now = time;
19422: if ($lockuser eq '') {
19423: $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
19424: }
19425: my $lockhash = {
19426: "lock\0$now" => $lockuser,
19427: };
19428: my $tries = 0;
19429: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19430: my ($code,$error);
19431: while (($gotlock ne 'ok') && ($tries<3)) {
19432: $tries ++;
19433: sleep 1;
19434: $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
19435: }
19436: if ($gotlock eq 'ok') {
19437: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
19438: \%addcourse,\%courseonly,\%failed);
19439: if (keys(%failed)) {
19440: my $numfailed = scalar(keys(%failed));
19441: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
19442: }
19443: if (keys(%newunique)) {
19444: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
19445: if ($putres eq 'ok') {
19446: $numnew = scalar(keys(%newunique));
19447: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
19448: unless ($newputres eq 'ok') {
19449: push(@errors,&mt('error: could not store course look-up of short URLs'));
19450: }
19451: } else {
19452: push(@errors,&mt('error: could not store unique six character URLs'));
19453: }
19454: }
19455: my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
19456: unless ($dellockres eq 'ok') {
19457: push(@errors,&mt('error: could not release lockfile'));
19458: }
19459: } else {
19460: push(@errors,&mt('error: could not obtain lockfile'));
19461: }
19462: if (keys(%courseonly)) {
19463: my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
19464: if ($result ne 'ok') {
19465: push(@errors,&mt('error: could not update course look-up of short URLs'));
19466: }
19467: }
19468: }
19469: }
19470: return ($numnew,\@errors);
19471: }
19472:
19473: sub shorten_symbs {
19474: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
19475: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
19476: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
19477: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
19478: my (%possibles,%collisions);
19479: foreach my $key (keys(%{$tocreate})) {
19480: my $num = String::CRC32::crc32($key);
19481: my $tiny = $su->encode($num,$init);
19482: if ($tiny) {
19483: $possibles{$tiny} = $key;
19484: }
19485: }
19486: if (!$init) {
19487: $init = 1;
19488: } else {
19489: $init ++;
19490: }
19491: if (keys(%possibles)) {
19492: my @posstiny = keys(%possibles);
19493: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
19494: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
19495: if (keys(%currtiny)) {
19496: foreach my $key (keys(%currtiny)) {
19497: next if ($currtiny{$key} eq '');
19498: if ($currtiny{$key} eq $possibles{$key}) {
19499: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
19500: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19501: $courseonly->{$tsymb} = $key;
19502: }
19503: } else {
19504: $collisions{$possibles{$key}} = 1;
19505: }
19506: delete($possibles{$key});
19507: }
19508: }
19509: foreach my $key (keys(%possibles)) {
19510: $newunique->{$key} = $possibles{$key};
19511: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
19512: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
19513: $addcourse->{$tsymb} = $key;
19514: }
19515: }
19516: }
19517: if (keys(%collisions)) {
19518: if ($init <5) {
19519: if (!$init) {
19520: $init = 1;
19521: } else {
19522: $init ++;
19523: }
19524: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
19525: $newunique,$addcourse,$courseonly,$failed);
19526: } else {
19527: foreach my $key (keys(%collisions)) {
19528: $failed->{$key} = 1;
19529: }
19530: }
19531: }
19532: return $init;
19533: }
19534:
19535: sub is_nonframeable {
19536: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
19537: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
19538: return if (($remprotocol eq '') || ($remhost eq ''));
19539:
19540: $remprotocol = lc($remprotocol);
19541: $remhost = lc($remhost);
19542: my $remport = 80;
19543: if ($remprotocol eq 'https') {
19544: $remport = 443;
19545: }
19546: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
19547: if ($cached) {
19548: unless ($nocache) {
19549: if ($result) {
19550: return 1;
19551: } else {
19552: return 0;
19553: }
19554: }
19555: }
19556: my $uselink;
19557: my $request = new HTTP::Request('HEAD',$url);
19558: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
19559: if ($response->is_success()) {
19560: my $secpolicy = lc($response->header('content-security-policy'));
19561: my $xframeop = lc($response->header('x-frame-options'));
19562: $secpolicy =~ s/^\s+|\s+$//g;
19563: $xframeop =~ s/^\s+|\s+$//g;
19564: if (($secpolicy ne '') || ($xframeop ne '')) {
19565: my $remotehost = $remprotocol.'://'.$remhost;
19566: my ($origin,$protocol,$port);
19567: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
19568: $port = $ENV{'SERVER_PORT'};
19569: } else {
19570: $port = 80;
19571: }
19572: if ($absolute eq '') {
19573: $protocol = 'http:';
19574: if ($port == 443) {
19575: $protocol = 'https:';
19576: }
19577: $origin = $protocol.'//'.lc($hostname);
19578: } else {
19579: $origin = lc($absolute);
19580: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
19581: }
19582: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
19583: my $framepolicy = $1;
19584: $framepolicy =~ s/^\s+|\s+$//g;
19585: my @policies = split(/\s+/,$framepolicy);
19586: if (@policies) {
19587: if (grep(/^\Q'none'\E$/,@policies)) {
19588: $uselink = 1;
19589: } else {
19590: $uselink = 1;
19591: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
19592: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
19593: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
19594: undef($uselink);
19595: }
19596: if ($uselink) {
19597: if (grep(/^\Q'self'\E$/,@policies)) {
19598: if (($origin ne '') && ($remotehost eq $origin)) {
19599: undef($uselink);
19600: }
19601: }
19602: }
19603: if ($uselink) {
19604: my @possok;
19605: if ($ip ne '') {
19606: push(@possok,$ip);
19607: }
19608: my $hoststr = '';
19609: foreach my $part (reverse(split(/\./,$hostname))) {
19610: if ($hoststr eq '') {
19611: $hoststr = $part;
19612: } else {
19613: $hoststr = "$part.$hoststr";
19614: }
19615: if ($hoststr eq $hostname) {
19616: push(@possok,$hostname);
19617: } else {
19618: push(@possok,"*.$hoststr");
19619: }
19620: }
19621: if (@possok) {
19622: foreach my $poss (@possok) {
19623: last if (!$uselink);
19624: foreach my $policy (@policies) {
19625: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
19626: undef($uselink);
19627: last;
19628: }
19629: }
19630: }
19631: }
19632: }
19633: }
19634: }
19635: } elsif ($xframeop ne '') {
19636: $uselink = 1;
19637: my @policies = split(/\s*,\s*/,$xframeop);
19638: if (@policies) {
19639: unless (grep(/^deny$/,@policies)) {
19640: if ($origin ne '') {
19641: if (grep(/^sameorigin$/,@policies)) {
19642: if ($remotehost eq $origin) {
19643: undef($uselink);
19644: }
19645: }
19646: if ($uselink) {
19647: foreach my $policy (@policies) {
19648: if ($policy =~ /^allow-from\s*(.+)$/) {
19649: my $allowfrom = $1;
19650: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
19651: undef($uselink);
19652: last;
19653: }
19654: }
19655: }
19656: }
19657: }
19658: }
19659: }
19660: }
19661: }
19662: }
19663: if ($nocache) {
19664: if ($cached) {
19665: my $devalidate;
19666: if ($uselink && !$result) {
19667: $devalidate = 1;
19668: } elsif (!$uselink && $result) {
19669: $devalidate = 1;
19670: }
19671: if ($devalidate) {
19672: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
19673: }
19674: }
19675: } else {
19676: if ($uselink) {
19677: $result = 1;
19678: } else {
19679: $result = 0;
19680: }
19681: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
19682: }
19683: return $uselink;
19684: }
19685:
19686: sub page_menu {
19687: my ($menucolls,$menunum) = @_;
19688: my %menu;
19689: foreach my $item (split(/;/,$menucolls)) {
19690: my ($num,$value) = split(/\%/,$item);
19691: if ($num eq $menunum) {
19692: my @entries = split(/\&/,$value);
19693: foreach my $entry (@entries) {
19694: my ($name,$fields) = split(/=/,$entry);
19695: if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
19696: $menu{$name} = $fields;
19697: } else {
19698: my @shown;
19699: if ($fields =~ /,/) {
19700: @shown = split(/,/,$fields);
19701: } else {
19702: @shown = ($fields);
19703: }
19704: if (@shown) {
19705: foreach my $field (@shown) {
19706: next if ($field eq '');
19707: $menu{$field} = 1;
19708: }
19709: }
19710: }
19711: }
19712: }
19713: }
19714: return %menu;
19715: }
19716:
19717: 1;
19718: __END__;
19719:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>