1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.141.2.8 2020/09/29 19:02:00 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use HTTP::Request;
75: use DateTime::TimeZone;
76: use DateTime::Locale;
77: use Encode();
78: use Authen::Captcha;
79: use Captcha::reCAPTCHA;
80: use JSON::DWIW;
81: use LWP::UserAgent;
82: use Crypt::DES;
83: use DynaLoader; # for Crypt::DES version
84: use File::Copy();
85: use File::Path();
86: use String::CRC32();
87: use Short::URL();
88:
89: # ---------------------------------------------- Designs
90: use vars qw(%defaultdesign);
91:
92: my $readit;
93:
94:
95: ##
96: ## Global Variables
97: ##
98:
99:
100: # ----------------------------------------------- SSI with retries:
101: #
102:
103: =pod
104:
105: =head1 Server Side include with retries:
106:
107: =over 4
108:
109: =item * &ssi_with_retries(resource,retries form)
110:
111: Performs an ssi with some number of retries. Retries continue either
112: until the result is ok or until the retry count supplied by the
113: caller is exhausted.
114:
115: Inputs:
116:
117: =over 4
118:
119: resource - Identifies the resource to insert.
120:
121: retries - Count of the number of retries allowed.
122:
123: form - Hash that identifies the rendering options.
124:
125: =back
126:
127: Returns:
128:
129: =over 4
130:
131: content - The content of the response. If retries were exhausted this is empty.
132:
133: response - The response from the last attempt (which may or may not have been successful.
134:
135: =back
136:
137: =back
138:
139: =cut
140:
141: sub ssi_with_retries {
142: my ($resource, $retries, %form) = @_;
143:
144:
145: my $ok = 0; # True if we got a good response.
146: my $content;
147: my $response;
148:
149: # Try to get the ssi done. within the retries count:
150:
151: do {
152: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
153: $ok = $response->is_success;
154: if (!$ok) {
155: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
156: }
157: $retries--;
158: } while (!$ok && ($retries > 0));
159:
160: if (!$ok) {
161: $content = ''; # On error return an empty content.
162: }
163: return ($content, $response);
164:
165: }
166:
167:
168:
169: # ----------------------------------------------- Filetypes/Languages/Copyright
170: my %language;
171: my %supported_language;
172: my %latex_language; # For choosing hyphenation in <transl..>
173: my %latex_language_bykey; # for choosing hyphenation from metadata
174: my %cprtag;
175: my %scprtag;
176: my %fe; my %fd; my %fm;
177: my %category_extensions;
178:
179: # ---------------------------------------------- Thesaurus variables
180: #
181: # %Keywords:
182: # A hash used by &keyword to determine if a word is considered a keyword.
183: # $thesaurus_db_file
184: # Scalar containing the full path to the thesaurus database.
185:
186: my %Keywords;
187: my $thesaurus_db_file;
188:
189: #
190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
191: # thesaurus.tab, and filecategories.tab.
192: #
193: BEGIN {
194: # Variable initialization
195: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
196: #
197: unless ($readit) {
198: # ------------------------------------------------------------------- languages
199: {
200: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
201: '/language.tab';
202: if ( open(my $fh,'<',$langtabfile) ) {
203: while (my $line = <$fh>) {
204: next if ($line=~/^\#/);
205: chomp($line);
206: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
207: $language{$key}=$val.' - '.$enc;
208: if ($sup) {
209: $supported_language{$key}=$sup;
210: }
211: if ($latex) {
212: $latex_language_bykey{$key} = $latex;
213: $latex_language{$two} = $latex;
214: }
215: }
216: close($fh);
217: }
218: }
219: # ------------------------------------------------------------------ copyrights
220: {
221: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
222: '/copyright.tab';
223: if ( open (my $fh,'<',$copyrightfile) ) {
224: while (my $line = <$fh>) {
225: next if ($line=~/^\#/);
226: chomp($line);
227: my ($key,$val)=(split(/\s+/,$line,2));
228: $cprtag{$key}=$val;
229: }
230: close($fh);
231: }
232: }
233: # ----------------------------------------------------------- source copyrights
234: {
235: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
236: '/source_copyright.tab';
237: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
238: while (my $line = <$fh>) {
239: next if ($line =~ /^\#/);
240: chomp($line);
241: my ($key,$val)=(split(/\s+/,$line,2));
242: $scprtag{$key}=$val;
243: }
244: close($fh);
245: }
246: }
247:
248: # -------------------------------------------------------------- default domain designs
249: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
250: my $designfile = $designdir.'/default.tab';
251: if ( open (my $fh,'<',$designfile) ) {
252: while (my $line = <$fh>) {
253: next if ($line =~ /^\#/);
254: chomp($line);
255: my ($key,$val)=(split(/\=/,$line));
256: if ($val) { $defaultdesign{$key}=$val; }
257: }
258: close($fh);
259: }
260:
261: # ------------------------------------------------------------- file categories
262: {
263: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
264: '/filecategories.tab';
265: if ( open (my $fh,'<',$categoryfile) ) {
266: while (my $line = <$fh>) {
267: next if ($line =~ /^\#/);
268: chomp($line);
269: my ($extension,$category)=(split(/\s+/,$line,2));
270: push(@{$category_extensions{lc($category)}},$extension);
271: }
272: close($fh);
273: }
274:
275: }
276: # ------------------------------------------------------------------ file types
277: {
278: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
279: '/filetypes.tab';
280: if ( open (my $fh,'<',$typesfile) ) {
281: while (my $line = <$fh>) {
282: next if ($line =~ /^\#/);
283: chomp($line);
284: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
285: if ($descr ne '') {
286: $fe{$ending}=lc($emb);
287: $fd{$ending}=$descr;
288: if ($mime ne 'unk') { $fm{$ending}=$mime; }
289: }
290: }
291: close($fh);
292: }
293: }
294: &Apache::lonnet::logthis(
295: "<span style='color:yellow;'>INFO: Read file types</span>");
296: $readit=1;
297: } # end of unless($readit)
298:
299: }
300:
301: ###############################################################
302: ## HTML and Javascript Helper Functions ##
303: ###############################################################
304:
305: =pod
306:
307: =head1 HTML and Javascript Functions
308:
309: =over 4
310:
311: =item * &browser_and_searcher_javascript()
312:
313: X<browsing, javascript>X<searching, javascript>Returns a string
314: containing javascript with two functions, C<openbrowser> and
315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
316: tags.
317:
318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
319:
320: inputs: formname, elementname, only, omit
321:
322: formname and elementname indicate the name of the html form and name of
323: the element that the results of the browsing selection are to be placed in.
324:
325: Specifying 'only' will restrict the browser to displaying only files
326: with the given extension. Can be a comma separated list.
327:
328: Specifying 'omit' will restrict the browser to NOT displaying files
329: with the given extension. Can be a comma separated list.
330:
331: =item * &opensearcher(formname,elementname) [javascript]
332:
333: Inputs: formname, elementname
334:
335: formname and elementname specify the name of the html form and the name
336: of the element the selection from the search results will be placed in.
337:
338: =cut
339:
340: sub browser_and_searcher_javascript {
341: my ($mode)=@_;
342: if (!defined($mode)) { $mode='edit'; }
343: my $resurl=&escape_single(&lastresurl());
344: return <<END;
345: // <!-- BEGIN LON-CAPA Internal
346: var editbrowser = null;
347: function openbrowser(formname,elementname,only,omit,titleelement) {
348: var url = '$resurl/?';
349: if (editbrowser == null) {
350: url += 'launch=1&';
351: }
352: url += 'catalogmode=interactive&';
353: url += 'mode=$mode&';
354: url += 'inhibitmenu=yes&';
355: url += 'form=' + formname + '&';
356: if (only != null) {
357: url += 'only=' + only + '&';
358: } else {
359: url += 'only=&';
360: }
361: if (omit != null) {
362: url += 'omit=' + omit + '&';
363: } else {
364: url += 'omit=&';
365: }
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Browser';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editbrowser = open(url,title,options,'1');
376: editbrowser.focus();
377: }
378: var editsearcher;
379: function opensearcher(formname,elementname,titleelement) {
380: var url = '/adm/searchcat?';
381: if (editsearcher == null) {
382: url += 'launch=1&';
383: }
384: url += 'catalogmode=interactive&';
385: url += 'mode=$mode&';
386: url += 'form=' + formname + '&';
387: if (titleelement != null) {
388: url += 'titleelement=' + titleelement + '&';
389: } else {
390: url += 'titleelement=&';
391: }
392: url += 'element=' + elementname + '';
393: var title = 'Search';
394: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
395: options += ',width=700,height=600';
396: editsearcher = open(url,title,options,'1');
397: editsearcher.focus();
398: }
399: // END LON-CAPA Internal -->
400: END
401: }
402:
403: sub lastresurl {
404: if ($env{'environment.lastresurl'}) {
405: return $env{'environment.lastresurl'}
406: } else {
407: return '/res';
408: }
409: }
410:
411: sub storeresurl {
412: my $resurl=&Apache::lonnet::clutter(shift);
413: unless ($resurl=~/^\/res/) { return 0; }
414: $resurl=~s/\/$//;
415: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
416: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
417: return 1;
418: }
419:
420: sub studentbrowser_javascript {
421: unless (
422: (($env{'request.course.id'}) &&
423: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
424: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
425: '/'.$env{'request.course.sec'})
426: ))
427: || ($env{'request.role'}=~/^(au|dc|su)/)
428: ) { return ''; }
429: return (<<'ENDSTDBRW');
430: <script type="text/javascript" language="Javascript">
431: // <![CDATA[
432: var stdeditbrowser;
433: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
434: var url = '/adm/pickstudent?';
435: var filter;
436: if (!ignorefilter) {
437: eval('filter=document.'+formname+'.'+uname+'.value;');
438: }
439: if (filter != null) {
440: if (filter != '') {
441: url += 'filter='+filter+'&';
442: }
443: }
444: url += 'form=' + formname + '&unameelement='+uname+
445: '&udomelement='+udom+
446: '&clicker='+clicker;
447: if (roleflag) { url+="&roles=1"; }
448: if (courseadv == 'condition') {
449: if (document.getElementById('courseadv')) {
450: courseadv = document.getElementById('courseadv').value;
451: }
452: }
453: if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
454: var title = 'Student_Browser';
455: var options = 'scrollbars=1,resizable=1,menubar=0';
456: options += ',width=700,height=600';
457: stdeditbrowser = open(url,title,options,'1');
458: stdeditbrowser.focus();
459: }
460: // ]]>
461: </script>
462: ENDSTDBRW
463: }
464:
465: sub resourcebrowser_javascript {
466: unless ($env{'request.course.id'}) { return ''; }
467: return (<<'ENDRESBRW');
468: <script type="text/javascript" language="Javascript">
469: // <![CDATA[
470: var reseditbrowser;
471: function openresbrowser(formname,reslink) {
472: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
473: var title = 'Resource_Browser';
474: var options = 'scrollbars=1,resizable=1,menubar=0';
475: options += ',width=700,height=500';
476: reseditbrowser = open(url,title,options,'1');
477: reseditbrowser.focus();
478: }
479: // ]]>
480: </script>
481: ENDRESBRW
482: }
483:
484: sub selectstudent_link {
485: my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
486: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
487: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
488: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
489: if ($env{'request.course.id'}) {
490: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
491: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
492: '/'.$env{'request.course.sec'})) {
493: return '';
494: }
495: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
496: if ($courseadv eq 'only') {
497: $callargs .= ",'',1,'$courseadv'";
498: } elsif ($courseadv eq 'none') {
499: $callargs .= ",'','','$courseadv'";
500: } elsif ($courseadv eq 'condition') {
501: $callargs .= ",'','','$courseadv'";
502: }
503: return '<span class="LC_nobreak">'.
504: '<a href="javascript:openstdbrowser('.$callargs.');">'.
505: &mt('Select User').'</a></span>';
506: }
507: if ($env{'request.role'}=~/^(au|dc|su)/) {
508: $callargs .= ",'',1";
509: return '<span class="LC_nobreak">'.
510: '<a href="javascript:openstdbrowser('.$callargs.');">'.
511: &mt('Select User').'</a></span>';
512: }
513: return '';
514: }
515:
516: sub selectresource_link {
517: my ($form,$reslink,$arg)=@_;
518:
519: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
520: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
521: unless ($env{'request.course.id'}) { return $arg; }
522: return '<span class="LC_nobreak">'.
523: '<a href="javascript:openresbrowser('.$callargs.');">'.
524: $arg.'</a></span>';
525: }
526:
527:
528:
529: sub authorbrowser_javascript {
530: return <<"ENDAUTHORBRW";
531: <script type="text/javascript" language="JavaScript">
532: // <![CDATA[
533: var stdeditbrowser;
534:
535: function openauthorbrowser(formname,udom) {
536: var url = '/adm/pickauthor?';
537: url += 'form='+formname+'&roledom='+udom;
538: var title = 'Author_Browser';
539: var options = 'scrollbars=1,resizable=1,menubar=0';
540: options += ',width=700,height=600';
541: stdeditbrowser = open(url,title,options,'1');
542: stdeditbrowser.focus();
543: }
544:
545: // ]]>
546: </script>
547: ENDAUTHORBRW
548: }
549:
550: sub coursebrowser_javascript {
551: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
552: $credits_element,$instcode) = @_;
553: my $wintitle = 'Course_Browser';
554: if ($crstype eq 'Community') {
555: $wintitle = 'Community_Browser';
556: }
557: my $id_functions = &javascript_index_functions();
558: my $output = '
559: <script type="text/javascript" language="JavaScript">
560: // <![CDATA[
561: var stdeditbrowser;'."\n";
562:
563: $output .= <<"ENDSTDBRW";
564: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
565: var url = '/adm/pickcourse?';
566: var formid = getFormIdByName(formname);
567: var domainfilter = getDomainFromSelectbox(formname,udom);
568: if (domainfilter != null) {
569: if (domainfilter != '') {
570: url += 'domainfilter='+domainfilter+'&';
571: }
572: }
573: url += 'form=' + formname + '&cnumelement='+uname+
574: '&cdomelement='+udom+
575: '&cnameelement='+desc;
576: if (extra_element !=null && extra_element != '') {
577: if (formname == 'rolechoice' || formname == 'studentform') {
578: url += '&roleelement='+extra_element;
579: if (domainfilter == null || domainfilter == '') {
580: url += '&domainfilter='+extra_element;
581: }
582: }
583: else {
584: if (formname == 'portform') {
585: url += '&setroles='+extra_element;
586: } else {
587: if (formname == 'rules') {
588: url += '&fixeddom='+extra_element;
589: }
590: }
591: }
592: }
593: if (type != null && type != '') {
594: url += '&type='+type;
595: }
596: if (type_elem != null && type_elem != '') {
597: url += '&typeelement='+type_elem;
598: }
599: if (formname == 'ccrs') {
600: var ownername = document.forms[formid].ccuname.value;
601: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
602: url += '&cloner='+ownername+':'+ownerdom;
603: if (type == 'Course') {
604: url += '&crscode='+document.forms[formid].crscode.value;
605: }
606: }
607: if (formname == 'requestcrs') {
608: url += '&crsdom=$domainfilter&crscode=$instcode';
609: }
610: if (multflag !=null && multflag != '') {
611: url += '&multiple='+multflag;
612: }
613: var title = '$wintitle';
614: var options = 'scrollbars=1,resizable=1,menubar=0';
615: options += ',width=700,height=600';
616: stdeditbrowser = open(url,title,options,'1');
617: stdeditbrowser.focus();
618: }
619: $id_functions
620: ENDSTDBRW
621: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
622: $output .= &setsec_javascript($sec_element,$formname,$role_element,
623: $credits_element);
624: }
625: $output .= '
626: // ]]>
627: </script>';
628: return $output;
629: }
630:
631: sub javascript_index_functions {
632: return <<"ENDJS";
633:
634: function getFormIdByName(formname) {
635: for (var i=0;i<document.forms.length;i++) {
636: if (document.forms[i].name == formname) {
637: return i;
638: }
639: }
640: return -1;
641: }
642:
643: function getIndexByName(formid,item) {
644: for (var i=0;i<document.forms[formid].elements.length;i++) {
645: if (document.forms[formid].elements[i].name == item) {
646: return i;
647: }
648: }
649: return -1;
650: }
651:
652: function getDomainFromSelectbox(formname,udom) {
653: var userdom;
654: var formid = getFormIdByName(formname);
655: if (formid > -1) {
656: var domid = getIndexByName(formid,udom);
657: if (domid > -1) {
658: if (document.forms[formid].elements[domid].type == 'select-one') {
659: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
660: }
661: if (document.forms[formid].elements[domid].type == 'hidden') {
662: userdom=document.forms[formid].elements[domid].value;
663: }
664: }
665: }
666: return userdom;
667: }
668:
669: ENDJS
670:
671: }
672:
673: sub javascript_array_indexof {
674: return <<ENDJS;
675: <script type="text/javascript" language="JavaScript">
676: // <![CDATA[
677:
678: if (!Array.prototype.indexOf) {
679: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
680: "use strict";
681: if (this === void 0 || this === null) {
682: throw new TypeError();
683: }
684: var t = Object(this);
685: var len = t.length >>> 0;
686: if (len === 0) {
687: return -1;
688: }
689: var n = 0;
690: if (arguments.length > 0) {
691: n = Number(arguments[1]);
692: if (n !== n) { // shortcut for verifying if it's NaN
693: n = 0;
694: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
695: n = (n > 0 || -1) * Math.floor(Math.abs(n));
696: }
697: }
698: if (n >= len) {
699: return -1;
700: }
701: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
702: for (; k < len; k++) {
703: if (k in t && t[k] === searchElement) {
704: return k;
705: }
706: }
707: return -1;
708: }
709: }
710:
711: // ]]>
712: </script>
713:
714: ENDJS
715:
716: }
717:
718: sub userbrowser_javascript {
719: my $id_functions = &javascript_index_functions();
720: return <<"ENDUSERBRW";
721:
722: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
723: var url = '/adm/pickuser?';
724: var userdom = getDomainFromSelectbox(formname,udom);
725: if (userdom != null) {
726: if (userdom != '') {
727: url += 'srchdom='+userdom+'&';
728: }
729: }
730: url += 'form=' + formname + '&unameelement='+uname+
731: '&udomelement='+udom+
732: '&ulastelement='+ulast+
733: '&ufirstelement='+ufirst+
734: '&uemailelement='+uemail+
735: '&hideudomelement='+hideudom+
736: '&coursedom='+crsdom;
737: if ((caller != null) && (caller != undefined)) {
738: url += '&caller='+caller;
739: }
740: var title = 'User_Browser';
741: var options = 'scrollbars=1,resizable=1,menubar=0';
742: options += ',width=700,height=600';
743: var stdeditbrowser = open(url,title,options,'1');
744: stdeditbrowser.focus();
745: }
746:
747: function fix_domain (formname,udom,origdom,uname) {
748: var formid = getFormIdByName(formname);
749: if (formid > -1) {
750: var unameid = getIndexByName(formid,uname);
751: var domid = getIndexByName(formid,udom);
752: var hidedomid = getIndexByName(formid,origdom);
753: if (hidedomid > -1) {
754: var fixeddom = document.forms[formid].elements[hidedomid].value;
755: var unameval = document.forms[formid].elements[unameid].value;
756: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
757: if (domid > -1) {
758: var slct = document.forms[formid].elements[domid];
759: if (slct.type == 'select-one') {
760: var i;
761: for (i=0;i<slct.length;i++) {
762: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
763: }
764: }
765: if (slct.type == 'hidden') {
766: slct.value = fixeddom;
767: }
768: }
769: }
770: }
771: }
772: return;
773: }
774:
775: $id_functions
776: ENDUSERBRW
777: }
778:
779: sub setsec_javascript {
780: my ($sec_element,$formname,$role_element,$credits_element) = @_;
781: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
782: $communityrolestr);
783: if ($role_element ne '') {
784: my @allroles = ('st','ta','ep','in','ad');
785: foreach my $crstype ('Course','Community') {
786: if ($crstype eq 'Community') {
787: foreach my $role (@allroles) {
788: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
789: }
790: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
791: } else {
792: foreach my $role (@allroles) {
793: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
794: }
795: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
796: }
797: }
798: $rolestr = '"'.join('","',@allroles).'"';
799: $courserolestr = '"'.join('","',@courserolenames).'"';
800: $communityrolestr = '"'.join('","',@communityrolenames).'"';
801: }
802: my $setsections = qq|
803: function setSect(sectionlist) {
804: var sectionsArray = new Array();
805: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
806: sectionsArray = sectionlist.split(",");
807: }
808: var numSections = sectionsArray.length;
809: document.$formname.$sec_element.length = 0;
810: if (numSections == 0) {
811: document.$formname.$sec_element.multiple=false;
812: document.$formname.$sec_element.size=1;
813: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
814: } else {
815: if (numSections == 1) {
816: document.$formname.$sec_element.multiple=false;
817: document.$formname.$sec_element.size=1;
818: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
819: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
820: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
821: } else {
822: for (var i=0; i<numSections; i++) {
823: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
824: }
825: document.$formname.$sec_element.multiple=true
826: if (numSections < 3) {
827: document.$formname.$sec_element.size=numSections;
828: } else {
829: document.$formname.$sec_element.size=3;
830: }
831: document.$formname.$sec_element.options[0].selected = false
832: }
833: }
834: }
835:
836: function setRole(crstype) {
837: |;
838: if ($role_element eq '') {
839: $setsections .= ' return;
840: }
841: ';
842: } else {
843: $setsections .= qq|
844: var elementLength = document.$formname.$role_element.length;
845: var allroles = Array($rolestr);
846: var courserolenames = Array($courserolestr);
847: var communityrolenames = Array($communityrolestr);
848: if (elementLength != undefined) {
849: if (document.$formname.$role_element.options[5].value == 'cc') {
850: if (crstype == 'Course') {
851: return;
852: } else {
853: allroles[5] = 'co';
854: for (var i=0; i<6; i++) {
855: document.$formname.$role_element.options[i].value = allroles[i];
856: document.$formname.$role_element.options[i].text = communityrolenames[i];
857: }
858: }
859: } else {
860: if (crstype == 'Community') {
861: return;
862: } else {
863: allroles[5] = 'cc';
864: for (var i=0; i<6; i++) {
865: document.$formname.$role_element.options[i].value = allroles[i];
866: document.$formname.$role_element.options[i].text = courserolenames[i];
867: }
868: }
869: }
870: }
871: return;
872: }
873: |;
874: }
875: if ($credits_element) {
876: $setsections .= qq|
877: function setCredits(defaultcredits) {
878: document.$formname.$credits_element.value = defaultcredits;
879: return;
880: }
881: |;
882: }
883: return $setsections;
884: }
885:
886: sub selectcourse_link {
887: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
888: $typeelement) = @_;
889: my $type = $selecttype;
890: my $linktext = &mt('Select Course');
891: if ($selecttype eq 'Community') {
892: $linktext = &mt('Select Community');
893: } elsif ($selecttype eq 'Course/Community') {
894: $linktext = &mt('Select Course/Community');
895: $type = '';
896: } elsif ($selecttype eq 'Select') {
897: $linktext = &mt('Select');
898: $type = '';
899: }
900: return '<span class="LC_nobreak">'
901: ."<a href='"
902: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
903: .'","'.$udomele.'","'.$desc.'","'.$extra_element
904: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
905: ."'>".$linktext.'</a>'
906: .'</span>';
907: }
908:
909: sub selectauthor_link {
910: my ($form,$udom)=@_;
911: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
912: &mt('Select Author').'</a>';
913: }
914:
915: sub selectuser_link {
916: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
917: $coursedom,$linktext,$caller) = @_;
918: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
919: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
920: ');">'.$linktext.'</a>';
921: }
922:
923: sub check_uncheck_jscript {
924: my $jscript = <<"ENDSCRT";
925: function checkAll(field) {
926: if (field.length > 0) {
927: for (i = 0; i < field.length; i++) {
928: if (!field[i].disabled) {
929: field[i].checked = true;
930: }
931: }
932: } else {
933: if (!field.disabled) {
934: field.checked = true;
935: }
936: }
937: }
938:
939: function uncheckAll(field) {
940: if (field.length > 0) {
941: for (i = 0; i < field.length; i++) {
942: field[i].checked = false ;
943: }
944: } else {
945: field.checked = false ;
946: }
947: }
948: ENDSCRT
949: return $jscript;
950: }
951:
952: sub select_timezone {
953: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
954: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
955: if ($includeempty) {
956: $output .= '<option value=""';
957: if (($selected eq '') || ($selected eq 'local')) {
958: $output .= ' selected="selected" ';
959: }
960: $output .= '> </option>';
961: }
962: my @timezones = DateTime::TimeZone->all_names;
963: foreach my $tzone (@timezones) {
964: $output.= '<option value="'.$tzone.'"';
965: if ($tzone eq $selected) {
966: $output.=' selected="selected"';
967: }
968: $output.=">$tzone</option>\n";
969: }
970: $output.="</select>";
971: return $output;
972: }
973:
974: sub select_datelocale {
975: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
976: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
977: if ($includeempty) {
978: $output .= '<option value=""';
979: if ($selected eq '') {
980: $output .= ' selected="selected" ';
981: }
982: $output .= '> </option>';
983: }
984: my @languages = &Apache::lonlocal::preferred_languages();
985: my (@possibles,%locale_names);
986: my @locales = DateTime::Locale->ids();
987: foreach my $id (@locales) {
988: if ($id ne '') {
989: my ($en_terr,$native_terr);
990: my $loc = DateTime::Locale->load($id);
991: if (ref($loc)) {
992: $en_terr = $loc->name();
993: $native_terr = $loc->native_name();
994: if (grep(/^en$/,@languages) || !@languages) {
995: if ($en_terr ne '') {
996: $locale_names{$id} = '('.$en_terr.')';
997: } elsif ($native_terr ne '') {
998: $locale_names{$id} = $native_terr;
999: }
1000: } else {
1001: if ($native_terr ne '') {
1002: $locale_names{$id} = $native_terr.' ';
1003: } elsif ($en_terr ne '') {
1004: $locale_names{$id} = '('.$en_terr.')';
1005: }
1006: }
1007: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1008: push(@possibles,$id);
1009: }
1010: }
1011: }
1012: foreach my $item (sort(@possibles)) {
1013: $output.= '<option value="'.$item.'"';
1014: if ($item eq $selected) {
1015: $output.=' selected="selected"';
1016: }
1017: $output.=">$item";
1018: if ($locale_names{$item} ne '') {
1019: $output.=' '.$locale_names{$item};
1020: }
1021: $output.="</option>\n";
1022: }
1023: $output.="</select>";
1024: return $output;
1025: }
1026:
1027: sub select_language {
1028: my ($name,$selected,$includeempty,$noedit) = @_;
1029: my %langchoices;
1030: if ($includeempty) {
1031: %langchoices = ('' => 'No language preference');
1032: }
1033: foreach my $id (&languageids()) {
1034: my $code = &supportedlanguagecode($id);
1035: if ($code) {
1036: $langchoices{$code} = &plainlanguagedescription($id);
1037: }
1038: }
1039: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1040: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1041: }
1042:
1043: =pod
1044:
1045: =item * &linked_select_forms(...)
1046:
1047: linked_select_forms returns a string containing a <script></script> block
1048: and html for two <select> menus. The select menus will be linked in that
1049: changing the value of the first menu will result in new values being placed
1050: in the second menu. The values in the select menu will appear in alphabetical
1051: order unless a defined order is provided.
1052:
1053: linked_select_forms takes the following ordered inputs:
1054:
1055: =over 4
1056:
1057: =item * $formname, the name of the <form> tag
1058:
1059: =item * $middletext, the text which appears between the <select> tags
1060:
1061: =item * $firstdefault, the default value for the first menu
1062:
1063: =item * $firstselectname, the name of the first <select> tag
1064:
1065: =item * $secondselectname, the name of the second <select> tag
1066:
1067: =item * $hashref, a reference to a hash containing the data for the menus.
1068:
1069: =item * $menuorder, the order of values in the first menu
1070:
1071: =item * $onchangefirst, additional javascript call to execute for an onchange
1072: event for the first <select> tag
1073:
1074: =item * $onchangesecond, additional javascript call to execute for an onchange
1075: event for the second <select> tag
1076:
1077: =back
1078:
1079: Below is an example of such a hash. Only the 'text', 'default', and
1080: 'select2' keys must appear as stated. keys(%menu) are the possible
1081: values for the first select menu. The text that coincides with the
1082: first menu value is given in $menu{$choice1}->{'text'}. The values
1083: and text for the second menu are given in the hash pointed to by
1084: $menu{$choice1}->{'select2'}.
1085:
1086: my %menu = ( A1 => { text =>"Choice A1" ,
1087: default => "B3",
1088: select2 => {
1089: B1 => "Choice B1",
1090: B2 => "Choice B2",
1091: B3 => "Choice B3",
1092: B4 => "Choice B4"
1093: },
1094: order => ['B4','B3','B1','B2'],
1095: },
1096: A2 => { text =>"Choice A2" ,
1097: default => "C2",
1098: select2 => {
1099: C1 => "Choice C1",
1100: C2 => "Choice C2",
1101: C3 => "Choice C3"
1102: },
1103: order => ['C2','C1','C3'],
1104: },
1105: A3 => { text =>"Choice A3" ,
1106: default => "D6",
1107: select2 => {
1108: D1 => "Choice D1",
1109: D2 => "Choice D2",
1110: D3 => "Choice D3",
1111: D4 => "Choice D4",
1112: D5 => "Choice D5",
1113: D6 => "Choice D6",
1114: D7 => "Choice D7"
1115: },
1116: order => ['D4','D3','D2','D1','D7','D6','D5'],
1117: }
1118: );
1119:
1120: =cut
1121:
1122: sub linked_select_forms {
1123: my ($formname,
1124: $middletext,
1125: $firstdefault,
1126: $firstselectname,
1127: $secondselectname,
1128: $hashref,
1129: $menuorder,
1130: $onchangefirst,
1131: $onchangesecond
1132: ) = @_;
1133: my $second = "document.$formname.$secondselectname";
1134: my $first = "document.$formname.$firstselectname";
1135: # output the javascript to do the changing
1136: my $result = '';
1137: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1138: $result.="// <![CDATA[\n";
1139: $result.="var select2data = new Object();\n";
1140: $" = '","';
1141: my $debug = '';
1142: foreach my $s1 (sort(keys(%$hashref))) {
1143: $result.="select2data.d_$s1 = new Object();\n";
1144: $result.="select2data.d_$s1.def = new String('".
1145: $hashref->{$s1}->{'default'}."');\n";
1146: $result.="select2data.d_$s1.values = new Array(";
1147: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1148: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1149: @s2values = @{$hashref->{$s1}->{'order'}};
1150: }
1151: $result.="\"@s2values\");\n";
1152: $result.="select2data.d_$s1.texts = new Array(";
1153: my @s2texts;
1154: foreach my $value (@s2values) {
1155: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1156: }
1157: $result.="\"@s2texts\");\n";
1158: }
1159: $"=' ';
1160: $result.= <<"END";
1161:
1162: function select1_changed() {
1163: // Determine new choice
1164: var newvalue = "d_" + $first.value;
1165: // update select2
1166: var values = select2data[newvalue].values;
1167: var texts = select2data[newvalue].texts;
1168: var select2def = select2data[newvalue].def;
1169: var i;
1170: // out with the old
1171: for (i = 0; i < $second.options.length; i++) {
1172: $second.options[i] = null;
1173: }
1174: // in with the nuclear
1175: for (i=0;i<values.length; i++) {
1176: $second.options[i] = new Option(values[i]);
1177: $second.options[i].value = values[i];
1178: $second.options[i].text = texts[i];
1179: if (values[i] == select2def) {
1180: $second.options[i].selected = true;
1181: }
1182: }
1183: }
1184: // ]]>
1185: </script>
1186: END
1187: # output the initial values for the selection lists
1188: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1189: my @order = sort(keys(%{$hashref}));
1190: if (ref($menuorder) eq 'ARRAY') {
1191: @order = @{$menuorder};
1192: }
1193: foreach my $value (@order) {
1194: $result.=" <option value=\"$value\" ";
1195: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1196: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1197: }
1198: $result .= "</select>\n";
1199: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1200: $result .= $middletext;
1201: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1202: if ($onchangesecond) {
1203: $result .= ' onchange="'.$onchangesecond.'"';
1204: }
1205: $result .= ">\n";
1206: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1207:
1208: my @secondorder = sort(keys(%select2));
1209: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1210: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1211: }
1212: foreach my $value (@secondorder) {
1213: $result.=" <option value=\"$value\" ";
1214: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1215: $result.=">".&mt($select2{$value})."</option>\n";
1216: }
1217: $result .= "</select>\n";
1218: # return $debug;
1219: return $result;
1220: } # end of sub linked_select_forms {
1221:
1222: =pod
1223:
1224: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1225:
1226: Returns a string corresponding to an HTML link to the given help
1227: $topic, where $topic corresponds to the name of a .tex file in
1228: /home/httpd/html/adm/help/tex, with underscores replaced by
1229: spaces.
1230:
1231: $text will optionally be linked to the same topic, allowing you to
1232: link text in addition to the graphic. If you do not want to link
1233: text, but wish to specify one of the later parameters, pass an
1234: empty string.
1235:
1236: $stayOnPage is a value that will be interpreted as a boolean. If true,
1237: the link will not open a new window. If false, the link will open
1238: a new window using Javascript. (Default is false.)
1239:
1240: $width and $height are optional numerical parameters that will
1241: override the width and height of the popped up window, which may
1242: be useful for certain help topics with big pictures included.
1243:
1244: $imgid is the id of the img tag used for the help icon. This may be
1245: used in a javascript call to switch the image src. See
1246: lonhtmlcommon::htmlareaselectactive() for an example.
1247:
1248: =cut
1249:
1250: sub help_open_topic {
1251: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1252: $text = "" if (not defined $text);
1253: $stayOnPage = 0 if (not defined $stayOnPage);
1254: $width = 500 if (not defined $width);
1255: $height = 400 if (not defined $height);
1256: my $filename = $topic;
1257: $filename =~ s/ /_/g;
1258:
1259: my $template = "";
1260: my $link;
1261:
1262: $topic=~s/\W/\_/g;
1263:
1264: if (!$stayOnPage) {
1265: if ($env{'browser.mobile'}) {
1266: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1267: } else {
1268: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1269: }
1270: } elsif ($stayOnPage eq 'popup') {
1271: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1272: } else {
1273: $link = "/adm/help/${filename}.hlp";
1274: }
1275:
1276: # Add the text
1277: if ($text ne "") {
1278: $template.='<span class="LC_help_open_topic">'
1279: .'<a target="_top" href="'.$link.'">'
1280: .$text.'</a>';
1281: }
1282:
1283: # (Always) Add the graphic
1284: my $title = &mt('Online Help');
1285: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1286: if ($imgid ne '') {
1287: $imgid = ' id="'.$imgid.'"';
1288: }
1289: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1290: .'<img src="'.$helpicon.'" border="0"'
1291: .' alt="'.&mt('Help: [_1]',$topic).'"'
1292: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1293: .' /></a>';
1294: if ($text ne "") {
1295: $template.='</span>';
1296: }
1297: return $template;
1298:
1299: }
1300:
1301: # This is a quicky function for Latex cheatsheet editing, since it
1302: # appears in at least four places
1303: sub helpLatexCheatsheet {
1304: my ($topic,$text,$not_author,$stayOnPage) = @_;
1305: my $out;
1306: my $addOther = '';
1307: if ($topic) {
1308: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1309: }
1310: $out = '<span>' # Start cheatsheet
1311: .$addOther
1312: .'<span>'
1313: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1314: .'</span> <span>'
1315: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1316: .'</span>';
1317: unless ($not_author) {
1318: $out .= ' <span>'
1319: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1320: .'</span> <span>'
1321: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1322: .'</span>';
1323: }
1324: $out .= '</span>'; # End cheatsheet
1325: return $out;
1326: }
1327:
1328: sub general_help {
1329: my $helptopic='Student_Intro';
1330: if ($env{'request.role'}=~/^(ca|au)/) {
1331: $helptopic='Authoring_Intro';
1332: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1333: $helptopic='Course_Coordination_Intro';
1334: } elsif ($env{'request.role'}=~/^dc/) {
1335: $helptopic='Domain_Coordination_Intro';
1336: }
1337: return $helptopic;
1338: }
1339:
1340: sub update_help_link {
1341: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1342: my $origurl = $ENV{'REQUEST_URI'};
1343: $origurl=~s|^/~|/priv/|;
1344: my $timestamp = time;
1345: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1346: $$datum = &escape($$datum);
1347: }
1348:
1349: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1350: my $output .= <<"ENDOUTPUT";
1351: <script type="text/javascript">
1352: // <![CDATA[
1353: banner_link = '$banner_link';
1354: // ]]>
1355: </script>
1356: ENDOUTPUT
1357: return $output;
1358: }
1359:
1360: # now just updates the help link and generates a blue icon
1361: sub help_open_menu {
1362: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1363: = @_;
1364: $stayOnPage = 1;
1365: my $output;
1366: if ($component_help) {
1367: if (!$text) {
1368: $output=&help_open_topic($component_help,undef,$stayOnPage,
1369: $width,$height);
1370: } else {
1371: my $help_text;
1372: $help_text=&unescape($topic);
1373: $output='<table><tr><td>'.
1374: &help_open_topic($component_help,$help_text,$stayOnPage,
1375: $width,$height).'</td></tr></table>';
1376: }
1377: }
1378: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1379: return $output.$banner_link;
1380: }
1381:
1382: sub top_nav_help {
1383: my ($text) = @_;
1384: $text = &mt($text);
1385: my $stay_on_page;
1386: unless ($env{'environment.remote'} eq 'on') {
1387: $stay_on_page = 1;
1388: }
1389: my ($link,$banner_link);
1390: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1391: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1392: : "javascript:helpMenu('open')";
1393: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1394: }
1395: my $title = &mt('Get help');
1396: if ($link) {
1397: return <<"END";
1398: $banner_link
1399: <a href="$link" title="$title">$text</a>
1400: END
1401: } else {
1402: return ' '.$text.' ';
1403: }
1404: }
1405:
1406: sub help_menu_js {
1407: my ($httphost) = @_;
1408: my $stayOnPage = 1;
1409: my $width = 620;
1410: my $height = 600;
1411: my $helptopic=&general_help();
1412: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1413: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1414: my $start_page =
1415: &Apache::loncommon::start_page('Help Menu', undef,
1416: {'frameset' => 1,
1417: 'js_ready' => 1,
1418: 'use_absolute' => $httphost,
1419: 'add_entries' => {
1420: 'border' => '0',
1421: 'rows' => "110,*",},});
1422: my $end_page =
1423: &Apache::loncommon::end_page({'frameset' => 1,
1424: 'js_ready' => 1,});
1425:
1426: my $template .= <<"ENDTEMPLATE";
1427: <script type="text/javascript">
1428: // <![CDATA[
1429: // <!-- BEGIN LON-CAPA Internal
1430: var banner_link = '';
1431: function helpMenu(target) {
1432: var caller = this;
1433: if (target == 'open') {
1434: var newWindow = null;
1435: try {
1436: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1437: }
1438: catch(error) {
1439: writeHelp(caller);
1440: return;
1441: }
1442: if (newWindow) {
1443: caller = newWindow;
1444: }
1445: }
1446: writeHelp(caller);
1447: return;
1448: }
1449: function writeHelp(caller) {
1450: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1451: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1452: caller.document.close();
1453: caller.focus();
1454: }
1455: // END LON-CAPA Internal -->
1456: // ]]>
1457: </script>
1458: ENDTEMPLATE
1459: return $template;
1460: }
1461:
1462: sub help_open_bug {
1463: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1464: unless ($env{'user.adv'}) { return ''; }
1465: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1466: $text = "" if (not defined $text);
1467: $stayOnPage=1;
1468: $width = 600 if (not defined $width);
1469: $height = 600 if (not defined $height);
1470:
1471: $topic=~s/\W+/\+/g;
1472: my $link='';
1473: my $template='';
1474: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1475: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1476: if (!$stayOnPage)
1477: {
1478: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1479: }
1480: else
1481: {
1482: $link = $url;
1483: }
1484: # Add the text
1485: if ($text ne "")
1486: {
1487: $template .=
1488: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1489: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1490: }
1491:
1492: # Add the graphic
1493: my $title = &mt('Report a Bug');
1494: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1495: $template .= <<"ENDTEMPLATE";
1496: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1497: ENDTEMPLATE
1498: if ($text ne '') { $template.='</td></tr></table>' };
1499: return $template;
1500:
1501: }
1502:
1503: sub help_open_faq {
1504: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1505: unless ($env{'user.adv'}) { return ''; }
1506: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1507: $text = "" if (not defined $text);
1508: $stayOnPage=1;
1509: $width = 350 if (not defined $width);
1510: $height = 400 if (not defined $height);
1511:
1512: $topic=~s/\W+/\+/g;
1513: my $link='';
1514: my $template='';
1515: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1516: if (!$stayOnPage)
1517: {
1518: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1519: }
1520: else
1521: {
1522: $link = $url;
1523: }
1524:
1525: # Add the text
1526: if ($text ne "")
1527: {
1528: $template .=
1529: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1530: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1531: }
1532:
1533: # Add the graphic
1534: my $title = &mt('View the FAQ');
1535: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1536: $template .= <<"ENDTEMPLATE";
1537: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1538: ENDTEMPLATE
1539: if ($text ne '') { $template.='</td></tr></table>' };
1540: return $template;
1541:
1542: }
1543:
1544: ###############################################################
1545: ###############################################################
1546:
1547: =pod
1548:
1549: =item * &change_content_javascript():
1550:
1551: This and the next function allow you to create small sections of an
1552: otherwise static HTML page that you can update on the fly with
1553: Javascript, even in Netscape 4.
1554:
1555: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1556: must be written to the HTML page once. It will prove the Javascript
1557: function "change(name, content)". Calling the change function with the
1558: name of the section
1559: you want to update, matching the name passed to C<changable_area>, and
1560: the new content you want to put in there, will put the content into
1561: that area.
1562:
1563: B<Note>: Netscape 4 only reserves enough space for the changable area
1564: to contain room for the original contents. You need to "make space"
1565: for whatever changes you wish to make, and be B<sure> to check your
1566: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1567: it's adequate for updating a one-line status display, but little more.
1568: This script will set the space to 100% width, so you only need to
1569: worry about height in Netscape 4.
1570:
1571: Modern browsers are much less limiting, and if you can commit to the
1572: user not using Netscape 4, this feature may be used freely with
1573: pretty much any HTML.
1574:
1575: =cut
1576:
1577: sub change_content_javascript {
1578: # If we're on Netscape 4, we need to use Layer-based code
1579: if ($env{'browser.type'} eq 'netscape' &&
1580: $env{'browser.version'} =~ /^4\./) {
1581: return (<<NETSCAPE4);
1582: function change(name, content) {
1583: doc = document.layers[name+"___escape"].layers[0].document;
1584: doc.open();
1585: doc.write(content);
1586: doc.close();
1587: }
1588: NETSCAPE4
1589: } else {
1590: # Otherwise, we need to use semi-standards-compliant code
1591: # (technically, "innerHTML" isn't standard but the equivalent
1592: # is really scary, and every useful browser supports it
1593: return (<<DOMBASED);
1594: function change(name, content) {
1595: element = document.getElementById(name);
1596: element.innerHTML = content;
1597: }
1598: DOMBASED
1599: }
1600: }
1601:
1602: =pod
1603:
1604: =item * &changable_area($name,$origContent):
1605:
1606: This provides a "changable area" that can be modified on the fly via
1607: the Javascript code provided in C<change_content_javascript>. $name is
1608: the name you will use to reference the area later; do not repeat the
1609: same name on a given HTML page more then once. $origContent is what
1610: the area will originally contain, which can be left blank.
1611:
1612: =cut
1613:
1614: sub changable_area {
1615: my ($name, $origContent) = @_;
1616:
1617: if ($env{'browser.type'} eq 'netscape' &&
1618: $env{'browser.version'} =~ /^4\./) {
1619: # If this is netscape 4, we need to use the Layer tag
1620: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1621: } else {
1622: return "<span id='$name'>$origContent</span>";
1623: }
1624: }
1625:
1626: =pod
1627:
1628: =item * &viewport_geometry_js
1629:
1630: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1631:
1632: =cut
1633:
1634:
1635: sub viewport_geometry_js {
1636: return <<"GEOMETRY";
1637: var Geometry = {};
1638: function init_geometry() {
1639: if (Geometry.init) { return };
1640: Geometry.init=1;
1641: if (window.innerHeight) {
1642: Geometry.getViewportHeight = function() { return window.innerHeight; };
1643: Geometry.getViewportWidth = function() { return window.innerWidth; };
1644: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1645: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1646: }
1647: else if (document.documentElement && document.documentElement.clientHeight) {
1648: Geometry.getViewportHeight =
1649: function() { return document.documentElement.clientHeight; };
1650: Geometry.getViewportWidth =
1651: function() { return document.documentElement.clientWidth; };
1652:
1653: Geometry.getHorizontalScroll =
1654: function() { return document.documentElement.scrollLeft; };
1655: Geometry.getVerticalScroll =
1656: function() { return document.documentElement.scrollTop; };
1657: }
1658: else if (document.body.clientHeight) {
1659: Geometry.getViewportHeight =
1660: function() { return document.body.clientHeight; };
1661: Geometry.getViewportWidth =
1662: function() { return document.body.clientWidth; };
1663: Geometry.getHorizontalScroll =
1664: function() { return document.body.scrollLeft; };
1665: Geometry.getVerticalScroll =
1666: function() { return document.body.scrollTop; };
1667: }
1668: }
1669:
1670: GEOMETRY
1671: }
1672:
1673: =pod
1674:
1675: =item * &viewport_size_js()
1676:
1677: 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.
1678:
1679: =cut
1680:
1681: sub viewport_size_js {
1682: my $geometry = &viewport_geometry_js();
1683: return <<"DIMS";
1684:
1685: $geometry
1686:
1687: function getViewportDims(width,height) {
1688: init_geometry();
1689: width.value = Geometry.getViewportWidth();
1690: height.value = Geometry.getViewportHeight();
1691: return;
1692: }
1693:
1694: DIMS
1695: }
1696:
1697: =pod
1698:
1699: =item * &resize_textarea_js()
1700:
1701: emits the needed javascript to resize a textarea to be as big as possible
1702:
1703: creates a function resize_textrea that takes two IDs first should be
1704: the id of the element to resize, second should be the id of a div that
1705: surrounds everything that comes after the textarea, this routine needs
1706: to be attached to the <body> for the onload and onresize events.
1707:
1708: =back
1709:
1710: =cut
1711:
1712: sub resize_textarea_js {
1713: my $geometry = &viewport_geometry_js();
1714: return <<"RESIZE";
1715: <script type="text/javascript">
1716: // <![CDATA[
1717: $geometry
1718:
1719: function getX(element) {
1720: var x = 0;
1721: while (element) {
1722: x += element.offsetLeft;
1723: element = element.offsetParent;
1724: }
1725: return x;
1726: }
1727: function getY(element) {
1728: var y = 0;
1729: while (element) {
1730: y += element.offsetTop;
1731: element = element.offsetParent;
1732: }
1733: return y;
1734: }
1735:
1736:
1737: function resize_textarea(textarea_id,bottom_id) {
1738: init_geometry();
1739: var textarea = document.getElementById(textarea_id);
1740: //alert(textarea);
1741:
1742: var textarea_top = getY(textarea);
1743: var textarea_height = textarea.offsetHeight;
1744: var bottom = document.getElementById(bottom_id);
1745: var bottom_top = getY(bottom);
1746: var bottom_height = bottom.offsetHeight;
1747: var window_height = Geometry.getViewportHeight();
1748: var fudge = 23;
1749: var new_height = window_height-fudge-textarea_top-bottom_height;
1750: if (new_height < 300) {
1751: new_height = 300;
1752: }
1753: textarea.style.height=new_height+'px';
1754: }
1755: // ]]>
1756: </script>
1757: RESIZE
1758:
1759: }
1760:
1761: sub colorfuleditor_js {
1762: return <<"COLORFULEDIT"
1763: <script type="text/javascript">
1764: // <![CDATA[>
1765: function fold_box(curDepth, lastresource){
1766:
1767: // we need a list because there can be several blocks you need to fold in one tag
1768: var block = document.getElementsByName('foldblock_'+curDepth);
1769: // but there is only one folding button per tag
1770: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1771:
1772: if(block.item(0).style.display == 'none'){
1773:
1774: foldbutton.value = '@{[&mt("Hide")]}';
1775: for (i = 0; i < block.length; i++){
1776: block.item(i).style.display = '';
1777: }
1778: }else{
1779:
1780: foldbutton.value = '@{[&mt("Show")]}';
1781: for (i = 0; i < block.length; i++){
1782: // block.item(i).style.visibility = 'collapse';
1783: block.item(i).style.display = 'none';
1784: }
1785: };
1786: saveState(lastresource);
1787: }
1788:
1789: function saveState (lastresource) {
1790:
1791: var tag_list = getTagList();
1792: if(tag_list != null){
1793: var timestamp = new Date().getTime();
1794: var key = lastresource;
1795:
1796: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1797: // starting with timestamp
1798: var value = timestamp+';';
1799:
1800: // building the list of key-value pairs
1801: for(var i = 0; i < tag_list.length; i++){
1802: value += tag_list[i]+',';
1803: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1804: }
1805:
1806: // only iterate whole storage if nothing to override
1807: if(localStorage.getItem(key) == null){
1808:
1809: // prevent storage from growing large
1810: if(localStorage.length > 50){
1811: var regex_getTimestamp = /^(?:\d)+;/;
1812: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1813: var oldest_key;
1814:
1815: for(var i = 1; i < localStorage.length; i++){
1816: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1817: oldest_key = localStorage.key(i);
1818: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1819: }
1820: }
1821: localStorage.removeItem(oldest_key);
1822: }
1823: }
1824: localStorage.setItem(key,value);
1825: }
1826: }
1827:
1828: // restore folding status of blocks (on page load)
1829: function restoreState (lastresource) {
1830: if(localStorage.getItem(lastresource) != null){
1831: var key = lastresource;
1832: var value = localStorage.getItem(key);
1833: var regex_delTimestamp = /^\d+;/;
1834:
1835: value.replace(regex_delTimestamp, '');
1836:
1837: var valueArr = value.split(';');
1838: var pairs;
1839: var elements;
1840: for (var i = 0; i < valueArr.length; i++){
1841: pairs = valueArr[i].split(',');
1842: elements = document.getElementsByName(pairs[0]);
1843:
1844: for (var j = 0; j < elements.length; j++){
1845: elements[j].style.display = pairs[1];
1846: if (pairs[1] == "none"){
1847: var regex_id = /([_\\d]+)\$/;
1848: regex_id.exec(pairs[0]);
1849: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
1850: }
1851: }
1852: }
1853: }
1854: }
1855:
1856: function getTagList () {
1857:
1858: var stringToSearch = document.lonhomework.innerHTML;
1859:
1860: var ret = new Array();
1861: var regex_findBlock = /(foldblock_.*?)"/g;
1862: var tag_list = stringToSearch.match(regex_findBlock);
1863:
1864: if(tag_list != null){
1865: for(var i = 0; i < tag_list.length; i++){
1866: ret.push(tag_list[i].replace(/"/, ''));
1867: }
1868: }
1869: return ret;
1870: }
1871:
1872: function saveScrollPosition (resource) {
1873: var tag_list = getTagList();
1874:
1875: // we dont always want to jump to the first block
1876: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
1877: if(\$(window).scrollTop() > 170){
1878: if(tag_list != null){
1879: var result;
1880: for(var i = 0; i < tag_list.length; i++){
1881: if(isElementInViewport(tag_list[i])){
1882: result += tag_list[i]+';';
1883: }
1884: }
1885: sessionStorage.setItem('anchor_'+resource, result);
1886: }
1887: } else {
1888: // we dont need to save zero, just delete the item to leave everything tidy
1889: sessionStorage.removeItem('anchor_'+resource);
1890: }
1891: }
1892:
1893: function restoreScrollPosition(resource){
1894:
1895: var elem = sessionStorage.getItem('anchor_'+resource);
1896: if(elem != null){
1897: var tag_list = elem.split(';');
1898: var elem_list;
1899:
1900: for(var i = 0; i < tag_list.length; i++){
1901: elem_list = document.getElementsByName(tag_list[i]);
1902:
1903: if(elem_list.length > 0){
1904: elem = elem_list[0];
1905: break;
1906: }
1907: }
1908: elem.scrollIntoView();
1909: }
1910: }
1911:
1912: function isElementInViewport(el) {
1913:
1914: // change to last element instead of first
1915: var elem = document.getElementsByName(el);
1916: var rect = elem[0].getBoundingClientRect();
1917:
1918: return (
1919: rect.top >= 0 &&
1920: rect.left >= 0 &&
1921: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
1922: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
1923: );
1924: }
1925:
1926: function autosize(depth){
1927: var cmInst = window['cm'+depth];
1928: var fitsizeButton = document.getElementById('fitsize'+depth);
1929:
1930: // is fixed size, switching to dynamic
1931: if (sessionStorage.getItem("autosized_"+depth) == null) {
1932: cmInst.setSize("","auto");
1933: fitsizeButton.value = "@{[&mt('Fixed size')]}";
1934: sessionStorage.setItem("autosized_"+depth, "yes");
1935:
1936: // is dynamic size, switching to fixed
1937: } else {
1938: cmInst.setSize("","300px");
1939: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
1940: sessionStorage.removeItem("autosized_"+depth);
1941: }
1942: }
1943:
1944:
1945:
1946: // ]]>
1947: </script>
1948: COLORFULEDIT
1949: }
1950:
1951: sub xmleditor_js {
1952: return <<XMLEDIT
1953: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
1954: <script type="text/javascript">
1955: // <![CDATA[>
1956:
1957: function saveScrollPosition (resource) {
1958:
1959: var scrollPos = \$(window).scrollTop();
1960: sessionStorage.setItem(resource,scrollPos);
1961: }
1962:
1963: function restoreScrollPosition(resource){
1964:
1965: var scrollPos = sessionStorage.getItem(resource);
1966: \$(window).scrollTop(scrollPos);
1967: }
1968:
1969: // unless internet explorer
1970: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
1971:
1972: \$(document).ready(function() {
1973: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
1974: });
1975: }
1976:
1977: // inserts text at cursor position into codemirror (xml editor only)
1978: function insertText(text){
1979: cm.focus();
1980: var curPos = cm.getCursor();
1981: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
1982: }
1983: // ]]>
1984: </script>
1985: XMLEDIT
1986: }
1987:
1988: sub insert_folding_button {
1989: my $curDepth = $Apache::lonxml::curdepth;
1990: my $lastresource = $env{'request.ambiguous'};
1991:
1992: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
1993: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
1994: }
1995:
1996:
1997: =pod
1998:
1999: =head1 Excel and CSV file utility routines
2000:
2001: =cut
2002:
2003: ###############################################################
2004: ###############################################################
2005:
2006: =pod
2007:
2008: =over 4
2009:
2010: =item * &csv_translate($text)
2011:
2012: Translate $text to allow it to be output as a 'comma separated values'
2013: format.
2014:
2015: =cut
2016:
2017: ###############################################################
2018: ###############################################################
2019: sub csv_translate {
2020: my $text = shift;
2021: $text =~ s/\"/\"\"/g;
2022: $text =~ s/\n/ /g;
2023: return $text;
2024: }
2025:
2026: ###############################################################
2027: ###############################################################
2028:
2029: =pod
2030:
2031: =item * &define_excel_formats()
2032:
2033: Define some commonly used Excel cell formats.
2034:
2035: Currently supported formats:
2036:
2037: =over 4
2038:
2039: =item header
2040:
2041: =item bold
2042:
2043: =item h1
2044:
2045: =item h2
2046:
2047: =item h3
2048:
2049: =item h4
2050:
2051: =item i
2052:
2053: =item date
2054:
2055: =back
2056:
2057: Inputs: $workbook
2058:
2059: Returns: $format, a hash reference.
2060:
2061:
2062: =cut
2063:
2064: ###############################################################
2065: ###############################################################
2066: sub define_excel_formats {
2067: my ($workbook) = @_;
2068: my $format;
2069: $format->{'header'} = $workbook->add_format(bold => 1,
2070: bottom => 1,
2071: align => 'center');
2072: $format->{'bold'} = $workbook->add_format(bold=>1);
2073: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2074: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2075: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2076: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2077: $format->{'i'} = $workbook->add_format(italic=>1);
2078: $format->{'date'} = $workbook->add_format(num_format=>
2079: 'mm/dd/yyyy hh:mm:ss');
2080: return $format;
2081: }
2082:
2083: ###############################################################
2084: ###############################################################
2085:
2086: =pod
2087:
2088: =item * &create_workbook()
2089:
2090: Create an Excel worksheet. If it fails, output message on the
2091: request object and return undefs.
2092:
2093: Inputs: Apache request object
2094:
2095: Returns (undef) on failure,
2096: Excel worksheet object, scalar with filename, and formats
2097: from &Apache::loncommon::define_excel_formats on success
2098:
2099: =cut
2100:
2101: ###############################################################
2102: ###############################################################
2103: sub create_workbook {
2104: my ($r) = @_;
2105: #
2106: # Create the excel spreadsheet
2107: my $filename = '/prtspool/'.
2108: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2109: time.'_'.rand(1000000000).'.xls';
2110: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2111: if (! defined($workbook)) {
2112: $r->log_error("Error creating excel spreadsheet $filename: $!");
2113: $r->print(
2114: '<p class="LC_error">'
2115: .&mt('Problems occurred in creating the new Excel file.')
2116: .' '.&mt('This error has been logged.')
2117: .' '.&mt('Please alert your LON-CAPA administrator.')
2118: .'</p>'
2119: );
2120: return (undef);
2121: }
2122: #
2123: $workbook->set_tempdir(LONCAPA::tempdir());
2124: #
2125: my $format = &Apache::loncommon::define_excel_formats($workbook);
2126: return ($workbook,$filename,$format);
2127: }
2128:
2129: ###############################################################
2130: ###############################################################
2131:
2132: =pod
2133:
2134: =item * &create_text_file()
2135:
2136: Create a file to write to and eventually make available to the user.
2137: If file creation fails, outputs an error message on the request object and
2138: return undefs.
2139:
2140: Inputs: Apache request object, and file suffix
2141:
2142: Returns (undef) on failure,
2143: Filehandle and filename on success.
2144:
2145: =cut
2146:
2147: ###############################################################
2148: ###############################################################
2149: sub create_text_file {
2150: my ($r,$suffix) = @_;
2151: if (! defined($suffix)) { $suffix = 'txt'; };
2152: my $fh;
2153: my $filename = '/prtspool/'.
2154: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2155: time.'_'.rand(1000000000).'.'.$suffix;
2156: $fh = Apache::File->new('>/home/httpd'.$filename);
2157: if (! defined($fh)) {
2158: $r->log_error("Couldn't open $filename for output $!");
2159: $r->print(
2160: '<p class="LC_error">'
2161: .&mt('Problems occurred in creating the output file.')
2162: .' '.&mt('This error has been logged.')
2163: .' '.&mt('Please alert your LON-CAPA administrator.')
2164: .'</p>'
2165: );
2166: }
2167: return ($fh,$filename)
2168: }
2169:
2170:
2171: =pod
2172:
2173: =back
2174:
2175: =cut
2176:
2177: ###############################################################
2178: ## Home server <option> list generating code ##
2179: ###############################################################
2180:
2181: # ------------------------------------------
2182:
2183: sub domain_select {
2184: my ($name,$value,$multiple)=@_;
2185: my %domains=map {
2186: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2187: } &Apache::lonnet::all_domains();
2188: if ($multiple) {
2189: $domains{''}=&mt('Any domain');
2190: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2191: return &multiple_select_form($name,$value,4,\%domains);
2192: } else {
2193: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2194: return &select_form($name,$value,\%domains);
2195: }
2196: }
2197:
2198: #-------------------------------------------
2199:
2200: =pod
2201:
2202: =head1 Routines for form select boxes
2203:
2204: =over 4
2205:
2206: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2207:
2208: Returns a string containing a <select> element int multiple mode
2209:
2210:
2211: Args:
2212: $name - name of the <select> element
2213: $value - scalar or array ref of values that should already be selected
2214: $size - number of rows long the select element is
2215: $hash - the elements should be 'option' => 'shown text'
2216: (shown text should already have been &mt())
2217: $order - (optional) array ref of the order to show the elements in
2218:
2219: =cut
2220:
2221: #-------------------------------------------
2222: sub multiple_select_form {
2223: my ($name,$value,$size,$hash,$order)=@_;
2224: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2225: my $output='';
2226: if (! defined($size)) {
2227: $size = 4;
2228: if (scalar(keys(%$hash))<4) {
2229: $size = scalar(keys(%$hash));
2230: }
2231: }
2232: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2233: my @order;
2234: if (ref($order) eq 'ARRAY') {
2235: @order = @{$order};
2236: } else {
2237: @order = sort(keys(%$hash));
2238: }
2239: if (exists($$hash{'select_form_order'})) {
2240: @order = @{$$hash{'select_form_order'}};
2241: }
2242:
2243: foreach my $key (@order) {
2244: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2245: $output.='selected="selected" ' if ($selected{$key});
2246: $output.='>'.$hash->{$key}."</option>\n";
2247: }
2248: $output.="</select>\n";
2249: return $output;
2250: }
2251:
2252: #-------------------------------------------
2253:
2254: =pod
2255:
2256: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2257:
2258: Returns a string containing a <select name='$name' size='1'> form to
2259: allow a user to select options from a ref to a hash containing:
2260: option_name => displayed text. An optional $onchange can include
2261: a javascript onchange item, e.g., onchange="this.form.submit();".
2262: An optional arg -- $readonly -- if true will cause the select form
2263: to be disabled, e.g., for the case where an instructor has a section-
2264: specific role, and is viewing/modifying parameters.
2265:
2266: See lonrights.pm for an example invocation and use.
2267:
2268: =cut
2269:
2270: #-------------------------------------------
2271: sub select_form {
2272: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2273: return unless (ref($hashref) eq 'HASH');
2274: if ($onchange) {
2275: $onchange = ' onchange="'.$onchange.'"';
2276: }
2277: my $disabled;
2278: if ($readonly) {
2279: $disabled = ' disabled="disabled"';
2280: }
2281: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2282: my @keys;
2283: if (exists($hashref->{'select_form_order'})) {
2284: @keys=@{$hashref->{'select_form_order'}};
2285: } else {
2286: @keys=sort(keys(%{$hashref}));
2287: }
2288: foreach my $key (@keys) {
2289: $selectform.=
2290: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2291: ($key eq $def ? 'selected="selected" ' : '').
2292: ">".$hashref->{$key}."</option>\n";
2293: }
2294: $selectform.="</select>";
2295: return $selectform;
2296: }
2297:
2298: # For display filters
2299:
2300: sub display_filter {
2301: my ($context) = @_;
2302: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2303: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2304: my $phraseinput = 'hidden';
2305: my $includeinput = 'hidden';
2306: my ($checked,$includetypestext);
2307: if ($env{'form.displayfilter'} eq 'containing') {
2308: $phraseinput = 'text';
2309: if ($context eq 'parmslog') {
2310: $includeinput = 'checkbox';
2311: if ($env{'form.includetypes'}) {
2312: $checked = ' checked="checked"';
2313: }
2314: $includetypestext = &mt('Include parameter types');
2315: }
2316: } else {
2317: $includetypestext = ' ';
2318: }
2319: my ($additional,$secondid,$thirdid);
2320: if ($context eq 'parmslog') {
2321: $additional =
2322: '<label><input type="'.$includeinput.'" name="includetypes"'.
2323: $checked.' name="includetypes" value="1" id="includetypes" />'.
2324: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2325: '</label>';
2326: $secondid = 'includetypes';
2327: $thirdid = 'includetypestext';
2328: }
2329: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2330: '$secondid','$thirdid')";
2331: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2332: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2333: (&mt('all'),10,20,50,100,1000,10000))).
2334: '</label></span> <span class="LC_nobreak">'.
2335: &mt('Filter: [_1]',
2336: &select_form($env{'form.displayfilter'},
2337: 'displayfilter',
2338: {'currentfolder' => 'Current folder/page',
2339: 'containing' => 'Containing phrase',
2340: 'none' => 'None'},$onchange)).' '.
2341: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2342: &HTML::Entities::encode($env{'form.containingphrase'}).
2343: '" />'.$additional;
2344: }
2345:
2346: sub display_filter_js {
2347: my $includetext = &mt('Include parameter types');
2348: return <<"ENDJS";
2349:
2350: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2351: var firstType = 'hidden';
2352: if (setter.options[setter.selectedIndex].value == 'containing') {
2353: firstType = 'text';
2354: }
2355: firstObject = document.getElementById(firstid);
2356: if (typeof(firstObject) == 'object') {
2357: if (firstObject.type != firstType) {
2358: changeInputType(firstObject,firstType);
2359: }
2360: }
2361: if (context == 'parmslog') {
2362: var secondType = 'hidden';
2363: if (firstType == 'text') {
2364: secondType = 'checkbox';
2365: }
2366: secondObject = document.getElementById(secondid);
2367: if (typeof(secondObject) == 'object') {
2368: if (secondObject.type != secondType) {
2369: changeInputType(secondObject,secondType);
2370: }
2371: }
2372: var textItem = document.getElementById(thirdid);
2373: var currtext = textItem.innerHTML;
2374: var newtext;
2375: if (firstType == 'text') {
2376: newtext = '$includetext';
2377: } else {
2378: newtext = ' ';
2379: }
2380: if (currtext != newtext) {
2381: textItem.innerHTML = newtext;
2382: }
2383: }
2384: return;
2385: }
2386:
2387: function changeInputType(oldObject,newType) {
2388: var newObject = document.createElement('input');
2389: newObject.type = newType;
2390: if (oldObject.size) {
2391: newObject.size = oldObject.size;
2392: }
2393: if (oldObject.value) {
2394: newObject.value = oldObject.value;
2395: }
2396: if (oldObject.name) {
2397: newObject.name = oldObject.name;
2398: }
2399: if (oldObject.id) {
2400: newObject.id = oldObject.id;
2401: }
2402: oldObject.parentNode.replaceChild(newObject,oldObject);
2403: return;
2404: }
2405:
2406: ENDJS
2407: }
2408:
2409: sub gradeleveldescription {
2410: my $gradelevel=shift;
2411: my %gradelevels=(0 => 'Not specified',
2412: 1 => 'Grade 1',
2413: 2 => 'Grade 2',
2414: 3 => 'Grade 3',
2415: 4 => 'Grade 4',
2416: 5 => 'Grade 5',
2417: 6 => 'Grade 6',
2418: 7 => 'Grade 7',
2419: 8 => 'Grade 8',
2420: 9 => 'Grade 9',
2421: 10 => 'Grade 10',
2422: 11 => 'Grade 11',
2423: 12 => 'Grade 12',
2424: 13 => 'Grade 13',
2425: 14 => '100 Level',
2426: 15 => '200 Level',
2427: 16 => '300 Level',
2428: 17 => '400 Level',
2429: 18 => 'Graduate Level');
2430: return &mt($gradelevels{$gradelevel});
2431: }
2432:
2433: sub select_level_form {
2434: my ($deflevel,$name)=@_;
2435: unless ($deflevel) { $deflevel=0; }
2436: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2437: for (my $i=0; $i<=18; $i++) {
2438: $selectform.="<option value=\"$i\" ".
2439: ($i==$deflevel ? 'selected="selected" ' : '').
2440: ">".&gradeleveldescription($i)."</option>\n";
2441: }
2442: $selectform.="</select>";
2443: return $selectform;
2444: }
2445:
2446: #-------------------------------------------
2447:
2448: =pod
2449:
2450: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2451:
2452: Returns a string containing a <select name='$name' size='1'> form to
2453: allow a user to select the domain to preform an operation in.
2454: See loncreateuser.pm for an example invocation and use.
2455:
2456: If the $includeempty flag is set, it also includes an empty choice ("no domain
2457: selected");
2458:
2459: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2460:
2461: 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.
2462:
2463: The optional $incdoms is a reference to an array of domains which will be the only available options.
2464:
2465: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2466:
2467: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2468:
2469: =cut
2470:
2471: #-------------------------------------------
2472: sub select_dom_form {
2473: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2474: if ($onchange) {
2475: $onchange = ' onchange="'.$onchange.'"';
2476: }
2477: if ($disabled) {
2478: $disabled = ' disabled="disabled"';
2479: }
2480: my (@domains,%exclude);
2481: if (ref($incdoms) eq 'ARRAY') {
2482: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2483: } else {
2484: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2485: }
2486: if ($includeempty) { @domains=('',@domains); }
2487: if (ref($excdoms) eq 'ARRAY') {
2488: map { $exclude{$_} = 1; } @{$excdoms};
2489: }
2490: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2491: foreach my $dom (@domains) {
2492: next if ($exclude{$dom});
2493: $selectdomain.="<option value=\"$dom\" ".
2494: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2495: if ($showdomdesc) {
2496: if ($dom ne '') {
2497: my $domdesc = &Apache::lonnet::domain($dom,'description');
2498: if ($domdesc ne '') {
2499: $selectdomain .= ' ('.$domdesc.')';
2500: }
2501: }
2502: }
2503: $selectdomain .= "</option>\n";
2504: }
2505: $selectdomain.="</select>";
2506: return $selectdomain;
2507: }
2508:
2509: #-------------------------------------------
2510:
2511: =pod
2512:
2513: =item * &home_server_form_item($domain,$name,$defaultflag)
2514:
2515: input: 4 arguments (two required, two optional) -
2516: $domain - domain of new user
2517: $name - name of form element
2518: $default - Value of 'default' causes a default item to be first
2519: option, and selected by default.
2520: $hide - Value of 'hide' causes hiding of the name of the server,
2521: if 1 server found, or default, if 0 found.
2522: output: returns 2 items:
2523: (a) form element which contains either:
2524: (i) <select name="$name">
2525: <option value="$hostid1">$hostid $servers{$hostid}</option>
2526: <option value="$hostid2">$hostid $servers{$hostid}</option>
2527: </select>
2528: form item if there are multiple library servers in $domain, or
2529: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2530: if there is only one library server in $domain.
2531:
2532: (b) number of library servers found.
2533:
2534: See loncreateuser.pm for example of use.
2535:
2536: =cut
2537:
2538: #-------------------------------------------
2539: sub home_server_form_item {
2540: my ($domain,$name,$default,$hide) = @_;
2541: my %servers = &Apache::lonnet::get_servers($domain,'library');
2542: my $result;
2543: my $numlib = keys(%servers);
2544: if ($numlib > 1) {
2545: $result .= '<select name="'.$name.'" />'."\n";
2546: if ($default) {
2547: $result .= '<option value="default" selected="selected">'.&mt('default').
2548: '</option>'."\n";
2549: }
2550: foreach my $hostid (sort(keys(%servers))) {
2551: $result.= '<option value="'.$hostid.'">'.
2552: $hostid.' '.$servers{$hostid}."</option>\n";
2553: }
2554: $result .= '</select>'."\n";
2555: } elsif ($numlib == 1) {
2556: my $hostid;
2557: foreach my $item (keys(%servers)) {
2558: $hostid = $item;
2559: }
2560: $result .= '<input type="hidden" name="'.$name.'" value="'.
2561: $hostid.'" />';
2562: if (!$hide) {
2563: $result .= $hostid.' '.$servers{$hostid};
2564: }
2565: $result .= "\n";
2566: } elsif ($default) {
2567: $result .= '<input type="hidden" name="'.$name.
2568: '" value="default" />';
2569: if (!$hide) {
2570: $result .= &mt('default');
2571: }
2572: $result .= "\n";
2573: }
2574: return ($result,$numlib);
2575: }
2576:
2577: =pod
2578:
2579: =back
2580:
2581: =cut
2582:
2583: ###############################################################
2584: ## Decoding User Agent ##
2585: ###############################################################
2586:
2587: =pod
2588:
2589: =head1 Decoding the User Agent
2590:
2591: =over 4
2592:
2593: =item * &decode_user_agent()
2594:
2595: Inputs: $r
2596:
2597: Outputs:
2598:
2599: =over 4
2600:
2601: =item * $httpbrowser
2602:
2603: =item * $clientbrowser
2604:
2605: =item * $clientversion
2606:
2607: =item * $clientmathml
2608:
2609: =item * $clientunicode
2610:
2611: =item * $clientos
2612:
2613: =item * $clientmobile
2614:
2615: =item * $clientinfo
2616:
2617: =item * $clientosversion
2618:
2619: =back
2620:
2621: =back
2622:
2623: =cut
2624:
2625: ###############################################################
2626: ###############################################################
2627: sub decode_user_agent {
2628: my ($r)=@_;
2629: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2630: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2631: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2632: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2633: my $clientbrowser='unknown';
2634: my $clientversion='0';
2635: my $clientmathml='';
2636: my $clientunicode='0';
2637: my $clientmobile=0;
2638: my $clientosversion='';
2639: for (my $i=0;$i<=$#browsertype;$i++) {
2640: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2641: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2642: $clientbrowser=$bname;
2643: $httpbrowser=~/$vreg/i;
2644: $clientversion=$1;
2645: $clientmathml=($clientversion>=$minv);
2646: $clientunicode=($clientversion>=$univ);
2647: }
2648: }
2649: my $clientos='unknown';
2650: my $clientinfo;
2651: if (($httpbrowser=~/linux/i) ||
2652: ($httpbrowser=~/unix/i) ||
2653: ($httpbrowser=~/ux/i) ||
2654: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2655: if (($httpbrowser=~/vax/i) ||
2656: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2657: if ($httpbrowser=~/next/i) { $clientos='next'; }
2658: if (($httpbrowser=~/mac/i) ||
2659: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2660: if ($httpbrowser=~/win/i) {
2661: $clientos='win';
2662: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2663: $clientosversion = $1;
2664: }
2665: }
2666: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2667: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2668: $clientmobile=lc($1);
2669: }
2670: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2671: $clientinfo = 'firefox-'.$1;
2672: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2673: $clientinfo = 'chromeframe-'.$1;
2674: }
2675: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2676: $clientunicode,$clientos,$clientmobile,$clientinfo,
2677: $clientosversion);
2678: }
2679:
2680: ###############################################################
2681: ## Authentication changing form generation subroutines ##
2682: ###############################################################
2683: ##
2684: ## All of the authform_xxxxxxx subroutines take their inputs in a
2685: ## hash, and have reasonable default values.
2686: ##
2687: ## formname = the name given in the <form> tag.
2688: #-------------------------------------------
2689:
2690: =pod
2691:
2692: =head1 Authentication Routines
2693:
2694: =over 4
2695:
2696: =item * &authform_xxxxxx()
2697:
2698: The authform_xxxxxx subroutines provide javascript and html forms which
2699: handle some of the conveniences required for authentication forms.
2700: This is not an optimal method, but it works.
2701:
2702: =over 4
2703:
2704: =item * authform_header
2705:
2706: =item * authform_authorwarning
2707:
2708: =item * authform_nochange
2709:
2710: =item * authform_kerberos
2711:
2712: =item * authform_internal
2713:
2714: =item * authform_filesystem
2715:
2716: =back
2717:
2718: See loncreateuser.pm for invocation and use examples.
2719:
2720: =cut
2721:
2722: #-------------------------------------------
2723: sub authform_header{
2724: my %in = (
2725: formname => 'cu',
2726: kerb_def_dom => '',
2727: @_,
2728: );
2729: $in{'formname'} = 'document.' . $in{'formname'};
2730: my $result='';
2731:
2732: #---------------------------------------------- Code for upper case translation
2733: my $Javascript_toUpperCase;
2734: unless ($in{kerb_def_dom}) {
2735: $Javascript_toUpperCase =<<"END";
2736: switch (choice) {
2737: case 'krb': currentform.elements[choicearg].value =
2738: currentform.elements[choicearg].value.toUpperCase();
2739: break;
2740: default:
2741: }
2742: END
2743: } else {
2744: $Javascript_toUpperCase = "";
2745: }
2746:
2747: my $radioval = "'nochange'";
2748: if (defined($in{'curr_authtype'})) {
2749: if ($in{'curr_authtype'} ne '') {
2750: $radioval = "'".$in{'curr_authtype'}."arg'";
2751: }
2752: }
2753: my $argfield = 'null';
2754: if (defined($in{'mode'})) {
2755: if ($in{'mode'} eq 'modifycourse') {
2756: if (defined($in{'curr_autharg'})) {
2757: if ($in{'curr_autharg'} ne '') {
2758: $argfield = "'$in{'curr_autharg'}'";
2759: }
2760: }
2761: }
2762: }
2763:
2764: $result.=<<"END";
2765: var current = new Object();
2766: current.radiovalue = $radioval;
2767: current.argfield = $argfield;
2768:
2769: function changed_radio(choice,currentform) {
2770: var choicearg = choice + 'arg';
2771: // If a radio button in changed, we need to change the argfield
2772: if (current.radiovalue != choice) {
2773: current.radiovalue = choice;
2774: if (current.argfield != null) {
2775: currentform.elements[current.argfield].value = '';
2776: }
2777: if (choice == 'nochange') {
2778: current.argfield = null;
2779: } else {
2780: current.argfield = choicearg;
2781: switch(choice) {
2782: case 'krb':
2783: currentform.elements[current.argfield].value =
2784: "$in{'kerb_def_dom'}";
2785: break;
2786: default:
2787: break;
2788: }
2789: }
2790: }
2791: return;
2792: }
2793:
2794: function changed_text(choice,currentform) {
2795: var choicearg = choice + 'arg';
2796: if (currentform.elements[choicearg].value !='') {
2797: $Javascript_toUpperCase
2798: // clear old field
2799: if ((current.argfield != choicearg) && (current.argfield != null)) {
2800: currentform.elements[current.argfield].value = '';
2801: }
2802: current.argfield = choicearg;
2803: }
2804: set_auth_radio_buttons(choice,currentform);
2805: return;
2806: }
2807:
2808: function set_auth_radio_buttons(newvalue,currentform) {
2809: var numauthchoices = currentform.login.length;
2810: if (typeof numauthchoices == "undefined") {
2811: return;
2812: }
2813: var i=0;
2814: while (i < numauthchoices) {
2815: if (currentform.login[i].value == newvalue) { break; }
2816: i++;
2817: }
2818: if (i == numauthchoices) {
2819: return;
2820: }
2821: current.radiovalue = newvalue;
2822: currentform.login[i].checked = true;
2823: return;
2824: }
2825: END
2826: return $result;
2827: }
2828:
2829: sub authform_authorwarning {
2830: my $result='';
2831: $result='<i>'.
2832: &mt('As a general rule, only authors or co-authors should be '.
2833: 'filesystem authenticated '.
2834: '(which allows access to the server filesystem).')."</i>\n";
2835: return $result;
2836: }
2837:
2838: sub authform_nochange {
2839: my %in = (
2840: formname => 'document.cu',
2841: kerb_def_dom => 'MSU.EDU',
2842: @_,
2843: );
2844: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2845: my $result;
2846: if (!$authnum) {
2847: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2848: } else {
2849: $result = '<label>'.&mt('[_1] Do not change login data',
2850: '<input type="radio" name="login" value="nochange" '.
2851: 'checked="checked" onclick="'.
2852: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2853: '</label>';
2854: }
2855: return $result;
2856: }
2857:
2858: sub authform_kerberos {
2859: my %in = (
2860: formname => 'document.cu',
2861: kerb_def_dom => 'MSU.EDU',
2862: kerb_def_auth => 'krb4',
2863: @_,
2864: );
2865: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2866: $autharg,$jscall,$disabled);
2867: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2868: if ($in{'kerb_def_auth'} eq 'krb5') {
2869: $check5 = ' checked="checked"';
2870: } else {
2871: $check4 = ' checked="checked"';
2872: }
2873: if ($in{'readonly'}) {
2874: $disabled = ' disabled="disabled"';
2875: }
2876: $krbarg = $in{'kerb_def_dom'};
2877: if (defined($in{'curr_authtype'})) {
2878: if ($in{'curr_authtype'} eq 'krb') {
2879: $krbcheck = ' checked="checked"';
2880: if (defined($in{'mode'})) {
2881: if ($in{'mode'} eq 'modifyuser') {
2882: $krbcheck = '';
2883: }
2884: }
2885: if (defined($in{'curr_kerb_ver'})) {
2886: if ($in{'curr_krb_ver'} eq '5') {
2887: $check5 = ' checked="checked"';
2888: $check4 = '';
2889: } else {
2890: $check4 = ' checked="checked"';
2891: $check5 = '';
2892: }
2893: }
2894: if (defined($in{'curr_autharg'})) {
2895: $krbarg = $in{'curr_autharg'};
2896: }
2897: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2898: if (defined($in{'curr_autharg'})) {
2899: $result =
2900: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2901: $in{'curr_autharg'},$krbver);
2902: } else {
2903: $result =
2904: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2905: }
2906: return $result;
2907: }
2908: }
2909: } else {
2910: if ($authnum == 1) {
2911: $authtype = '<input type="hidden" name="login" value="krb" />';
2912: }
2913: }
2914: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2915: return;
2916: } elsif ($authtype eq '') {
2917: if (defined($in{'mode'})) {
2918: if ($in{'mode'} eq 'modifycourse') {
2919: if ($authnum == 1) {
2920: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
2921: }
2922: }
2923: }
2924: }
2925: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2926: if ($authtype eq '') {
2927: $authtype = '<input type="radio" name="login" value="krb" '.
2928: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2929: $krbcheck.$disabled.' />';
2930: }
2931: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2932: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2933: $in{'curr_authtype'} eq 'krb5') ||
2934: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2935: $in{'curr_authtype'} eq 'krb4')) {
2936: $result .= &mt
2937: ('[_1] Kerberos authenticated with domain [_2] '.
2938: '[_3] Version 4 [_4] Version 5 [_5]',
2939: '<label>'.$authtype,
2940: '</label><input type="text" size="10" name="krbarg" '.
2941: 'value="'.$krbarg.'" '.
2942: 'onchange="'.$jscall.'"'.$disabled.' />',
2943: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
2944: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
2945: '</label>');
2946: } elsif ($can_assign{'krb4'}) {
2947: $result .= &mt
2948: ('[_1] Kerberos authenticated with domain [_2] '.
2949: '[_3] Version 4 [_4]',
2950: '<label>'.$authtype,
2951: '</label><input type="text" size="10" name="krbarg" '.
2952: 'value="'.$krbarg.'" '.
2953: 'onchange="'.$jscall.'"'.$disabled.' />',
2954: '<label><input type="hidden" name="krbver" value="4" />',
2955: '</label>');
2956: } elsif ($can_assign{'krb5'}) {
2957: $result .= &mt
2958: ('[_1] Kerberos authenticated with domain [_2] '.
2959: '[_3] Version 5 [_4]',
2960: '<label>'.$authtype,
2961: '</label><input type="text" size="10" name="krbarg" '.
2962: 'value="'.$krbarg.'" '.
2963: 'onchange="'.$jscall.'"'.$disabled.' />',
2964: '<label><input type="hidden" name="krbver" value="5" />',
2965: '</label>');
2966: }
2967: return $result;
2968: }
2969:
2970: sub authform_internal {
2971: my %in = (
2972: formname => 'document.cu',
2973: kerb_def_dom => 'MSU.EDU',
2974: @_,
2975: );
2976: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
2977: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2978: if ($in{'readonly'}) {
2979: $disabled = ' disabled="disabled"';
2980: }
2981: if (defined($in{'curr_authtype'})) {
2982: if ($in{'curr_authtype'} eq 'int') {
2983: if ($can_assign{'int'}) {
2984: $intcheck = 'checked="checked" ';
2985: if (defined($in{'mode'})) {
2986: if ($in{'mode'} eq 'modifyuser') {
2987: $intcheck = '';
2988: }
2989: }
2990: if (defined($in{'curr_autharg'})) {
2991: $intarg = $in{'curr_autharg'};
2992: }
2993: } else {
2994: $result = &mt('Currently internally authenticated.');
2995: return $result;
2996: }
2997: }
2998: } else {
2999: if ($authnum == 1) {
3000: $authtype = '<input type="hidden" name="login" value="int" />';
3001: }
3002: }
3003: if (!$can_assign{'int'}) {
3004: return;
3005: } elsif ($authtype eq '') {
3006: if (defined($in{'mode'})) {
3007: if ($in{'mode'} eq 'modifycourse') {
3008: if ($authnum == 1) {
3009: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3010: }
3011: }
3012: }
3013: }
3014: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3015: if ($authtype eq '') {
3016: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3017: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3018: }
3019: $autharg = '<input type="password" size="10" name="intarg" value="'.
3020: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3021: $result = &mt
3022: ('[_1] Internally authenticated (with initial password [_2])',
3023: '<label>'.$authtype,'</label>'.$autharg);
3024: $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>';
3025: return $result;
3026: }
3027:
3028: sub authform_local {
3029: my %in = (
3030: formname => 'document.cu',
3031: kerb_def_dom => 'MSU.EDU',
3032: @_,
3033: );
3034: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3035: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3036: if ($in{'readonly'}) {
3037: $disabled = ' disabled="disabled"';
3038: }
3039: if (defined($in{'curr_authtype'})) {
3040: if ($in{'curr_authtype'} eq 'loc') {
3041: if ($can_assign{'loc'}) {
3042: $loccheck = 'checked="checked" ';
3043: if (defined($in{'mode'})) {
3044: if ($in{'mode'} eq 'modifyuser') {
3045: $loccheck = '';
3046: }
3047: }
3048: if (defined($in{'curr_autharg'})) {
3049: $locarg = $in{'curr_autharg'};
3050: }
3051: } else {
3052: $result = &mt('Currently using local (institutional) authentication.');
3053: return $result;
3054: }
3055: }
3056: } else {
3057: if ($authnum == 1) {
3058: $authtype = '<input type="hidden" name="login" value="loc" />';
3059: }
3060: }
3061: if (!$can_assign{'loc'}) {
3062: return;
3063: } elsif ($authtype eq '') {
3064: if (defined($in{'mode'})) {
3065: if ($in{'mode'} eq 'modifycourse') {
3066: if ($authnum == 1) {
3067: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3068: }
3069: }
3070: }
3071: }
3072: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3073: if ($authtype eq '') {
3074: $authtype = '<input type="radio" name="login" value="loc" '.
3075: $loccheck.' onchange="'.$jscall.'" onclick="'.
3076: $jscall.'"'.$disabled.' />';
3077: }
3078: $autharg = '<input type="text" size="10" name="locarg" value="'.
3079: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3080: $result = &mt('[_1] Local Authentication with argument [_2]',
3081: '<label>'.$authtype,'</label>'.$autharg);
3082: return $result;
3083: }
3084:
3085: sub authform_filesystem {
3086: my %in = (
3087: formname => 'document.cu',
3088: kerb_def_dom => 'MSU.EDU',
3089: @_,
3090: );
3091: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3092: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3093: if ($in{'readonly'}) {
3094: $disabled = ' disabled="disabled"';
3095: }
3096: if (defined($in{'curr_authtype'})) {
3097: if ($in{'curr_authtype'} eq 'fsys') {
3098: if ($can_assign{'fsys'}) {
3099: $fsyscheck = 'checked="checked" ';
3100: if (defined($in{'mode'})) {
3101: if ($in{'mode'} eq 'modifyuser') {
3102: $fsyscheck = '';
3103: }
3104: }
3105: } else {
3106: $result = &mt('Currently Filesystem Authenticated.');
3107: return $result;
3108: }
3109: }
3110: } else {
3111: if ($authnum == 1) {
3112: $authtype = '<input type="hidden" name="login" value="fsys" />';
3113: }
3114: }
3115: if (!$can_assign{'fsys'}) {
3116: return;
3117: } elsif ($authtype eq '') {
3118: if (defined($in{'mode'})) {
3119: if ($in{'mode'} eq 'modifycourse') {
3120: if ($authnum == 1) {
3121: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3122: }
3123: }
3124: }
3125: }
3126: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3127: if ($authtype eq '') {
3128: $authtype = '<input type="radio" name="login" value="fsys" '.
3129: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3130: $jscall.'"'.$disabled.' />';
3131: }
3132: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
3133: ' onchange="'.$jscall.'"'.$disabled.' />';
3134: $result = &mt
3135: ('[_1] Filesystem Authenticated (with initial password [_2])',
3136: '<label><input type="radio" name="login" value="fsys" '.
3137: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
3138: '</label><input type="password" size="10" name="fsysarg" value="" '.
3139: 'onchange="'.$jscall.'"'.$disabled.' />');
3140: return $result;
3141: }
3142:
3143: sub get_assignable_auth {
3144: my ($dom) = @_;
3145: if ($dom eq '') {
3146: $dom = $env{'request.role.domain'};
3147: }
3148: my %can_assign = (
3149: krb4 => 1,
3150: krb5 => 1,
3151: int => 1,
3152: loc => 1,
3153: );
3154: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3155: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3156: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3157: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3158: my $context;
3159: if ($env{'request.role'} =~ /^au/) {
3160: $context = 'author';
3161: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3162: $context = 'domain';
3163: } elsif ($env{'request.course.id'}) {
3164: $context = 'course';
3165: }
3166: if ($context) {
3167: if (ref($authhash->{$context}) eq 'HASH') {
3168: %can_assign = %{$authhash->{$context}};
3169: }
3170: }
3171: }
3172: }
3173: my $authnum = 0;
3174: foreach my $key (keys(%can_assign)) {
3175: if ($can_assign{$key}) {
3176: $authnum ++;
3177: }
3178: }
3179: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3180: $authnum --;
3181: }
3182: return ($authnum,%can_assign);
3183: }
3184:
3185: sub check_passwd_rules {
3186: my ($domain,$plainpass) = @_;
3187: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3188: my ($min,$max,@chars,@brokerule,$warning);
3189: $min = $Apache::lonnet::passwdmin;
3190: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3191: if ($passwdconf{'min'} =~ /^\d+$/) {
3192: if ($passwdconf{'min'} > $min) {
3193: $min = $passwdconf{'min'};
3194: }
3195: }
3196: if ($passwdconf{'max'} =~ /^\d+$/) {
3197: $max = $passwdconf{'max'};
3198: }
3199: @chars = @{$passwdconf{'chars'}};
3200: }
3201: if (($min) && (length($plainpass) < $min)) {
3202: push(@brokerule,'min');
3203: }
3204: if (($max) && (length($plainpass) > $max)) {
3205: push(@brokerule,'max');
3206: }
3207: if (@chars) {
3208: my %rules;
3209: map { $rules{$_} = 1; } @chars;
3210: if ($rules{'uc'}) {
3211: unless ($plainpass =~ /[A-Z]/) {
3212: push(@brokerule,'uc');
3213: }
3214: }
3215: if ($rules{'lc'}) {
3216: unless ($plainpass =~ /[a-z]/) {
3217: push(@brokerule,'lc');
3218: }
3219: }
3220: if ($rules{'num'}) {
3221: unless ($plainpass =~ /\d/) {
3222: push(@brokerule,'num');
3223: }
3224: }
3225: if ($rules{'spec'}) {
3226: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3227: push(@brokerule,'spec');
3228: }
3229: }
3230: }
3231: if (@brokerule) {
3232: my %rulenames = &Apache::lonlocal::texthash(
3233: uc => 'At least one upper case letter',
3234: lc => 'At least one lower case letter',
3235: num => 'At least one number',
3236: spec => 'At least one non-alphanumeric',
3237: );
3238: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3239: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3240: $rulenames{'num'} .= ': 0123456789';
3241: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3242: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3243: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3244: $warning = &mt('Password did not satisfy the following:').'<ul>';
3245: foreach my $rule ('min','max','uc','lc','num','spec') {
3246: if (grep(/^$rule$/,@brokerule)) {
3247: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3248: }
3249: }
3250: $warning .= '</ul>';
3251: }
3252: if (wantarray) {
3253: return @brokerule;
3254: }
3255: return $warning;
3256: }
3257:
3258: ###############################################################
3259: ## Get Kerberos Defaults for Domain ##
3260: ###############################################################
3261: ##
3262: ## Returns default kerberos version and an associated argument
3263: ## as listed in file domain.tab. If not listed, provides
3264: ## appropriate default domain and kerberos version.
3265: ##
3266: #-------------------------------------------
3267:
3268: =pod
3269:
3270: =item * &get_kerberos_defaults()
3271:
3272: get_kerberos_defaults($target_domain) returns the default kerberos
3273: version and domain. If not found, it defaults to version 4 and the
3274: domain of the server.
3275:
3276: =over 4
3277:
3278: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3279:
3280: =back
3281:
3282: =back
3283:
3284: =cut
3285:
3286: #-------------------------------------------
3287: sub get_kerberos_defaults {
3288: my $domain=shift;
3289: my ($krbdef,$krbdefdom);
3290: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3291: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3292: $krbdef = $domdefaults{'auth_def'};
3293: $krbdefdom = $domdefaults{'auth_arg_def'};
3294: } else {
3295: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3296: my $krbdefdom=$1;
3297: $krbdefdom=~tr/a-z/A-Z/;
3298: $krbdef = "krb4";
3299: }
3300: return ($krbdef,$krbdefdom);
3301: }
3302:
3303:
3304: ###############################################################
3305: ## Thesaurus Functions ##
3306: ###############################################################
3307:
3308: =pod
3309:
3310: =head1 Thesaurus Functions
3311:
3312: =over 4
3313:
3314: =item * &initialize_keywords()
3315:
3316: Initializes the package variable %Keywords if it is empty. Uses the
3317: package variable $thesaurus_db_file.
3318:
3319: =cut
3320:
3321: ###################################################
3322:
3323: sub initialize_keywords {
3324: return 1 if (scalar keys(%Keywords));
3325: # If we are here, %Keywords is empty, so fill it up
3326: # Make sure the file we need exists...
3327: if (! -e $thesaurus_db_file) {
3328: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3329: " failed because it does not exist");
3330: return 0;
3331: }
3332: # Set up the hash as a database
3333: my %thesaurus_db;
3334: if (! tie(%thesaurus_db,'GDBM_File',
3335: $thesaurus_db_file,&GDBM_READER(),0640)){
3336: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3337: $thesaurus_db_file);
3338: return 0;
3339: }
3340: # Get the average number of appearances of a word.
3341: my $avecount = $thesaurus_db{'average.count'};
3342: # Put keywords (those that appear > average) into %Keywords
3343: while (my ($word,$data)=each (%thesaurus_db)) {
3344: my ($count,undef) = split /:/,$data;
3345: $Keywords{$word}++ if ($count > $avecount);
3346: }
3347: untie %thesaurus_db;
3348: # Remove special values from %Keywords.
3349: foreach my $value ('total.count','average.count') {
3350: delete($Keywords{$value}) if (exists($Keywords{$value}));
3351: }
3352: return 1;
3353: }
3354:
3355: ###################################################
3356:
3357: =pod
3358:
3359: =item * &keyword($word)
3360:
3361: Returns true if $word is a keyword. A keyword is a word that appears more
3362: than the average number of times in the thesaurus database. Calls
3363: &initialize_keywords
3364:
3365: =cut
3366:
3367: ###################################################
3368:
3369: sub keyword {
3370: return if (!&initialize_keywords());
3371: my $word=lc(shift());
3372: $word=~s/\W//g;
3373: return exists($Keywords{$word});
3374: }
3375:
3376: ###############################################################
3377:
3378: =pod
3379:
3380: =item * &get_related_words()
3381:
3382: Look up a word in the thesaurus. Takes a scalar argument and returns
3383: an array of words. If the keyword is not in the thesaurus, an empty array
3384: will be returned. The order of the words returned is determined by the
3385: database which holds them.
3386:
3387: Uses global $thesaurus_db_file.
3388:
3389:
3390: =cut
3391:
3392: ###############################################################
3393: sub get_related_words {
3394: my $keyword = shift;
3395: my %thesaurus_db;
3396: if (! -e $thesaurus_db_file) {
3397: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3398: "failed because the file does not exist");
3399: return ();
3400: }
3401: if (! tie(%thesaurus_db,'GDBM_File',
3402: $thesaurus_db_file,&GDBM_READER(),0640)){
3403: return ();
3404: }
3405: my @Words=();
3406: my $count=0;
3407: if (exists($thesaurus_db{$keyword})) {
3408: # The first element is the number of times
3409: # the word appears. We do not need it now.
3410: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3411: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3412: my $threshold=$mostfrequentcount/10;
3413: foreach my $possibleword (@RelatedWords) {
3414: my ($word,$wordcount)=split(/\,/,$possibleword);
3415: if ($wordcount>$threshold) {
3416: push(@Words,$word);
3417: $count++;
3418: if ($count>10) { last; }
3419: }
3420: }
3421: }
3422: untie %thesaurus_db;
3423: return @Words;
3424: }
3425:
3426: =pod
3427:
3428: =back
3429:
3430: =cut
3431:
3432: # -------------------------------------------------------------- Plaintext name
3433: =pod
3434:
3435: =head1 User Name Functions
3436:
3437: =over 4
3438:
3439: =item * &plainname($uname,$udom,$first)
3440:
3441: Takes a users logon name and returns it as a string in
3442: "first middle last generation" form
3443: if $first is set to 'lastname' then it returns it as
3444: 'lastname generation, firstname middlename' if their is a lastname
3445:
3446: =cut
3447:
3448:
3449: ###############################################################
3450: sub plainname {
3451: my ($uname,$udom,$first)=@_;
3452: return if (!defined($uname) || !defined($udom));
3453: my %names=&getnames($uname,$udom);
3454: my $name=&Apache::lonnet::format_name($names{'firstname'},
3455: $names{'middlename'},
3456: $names{'lastname'},
3457: $names{'generation'},$first);
3458: $name=~s/^\s+//;
3459: $name=~s/\s+$//;
3460: $name=~s/\s+/ /g;
3461: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3462: return $name;
3463: }
3464:
3465: # -------------------------------------------------------------------- Nickname
3466: =pod
3467:
3468: =item * &nickname($uname,$udom)
3469:
3470: Gets a users name and returns it as a string as
3471:
3472: ""nickname""
3473:
3474: if the user has a nickname or
3475:
3476: "first middle last generation"
3477:
3478: if the user does not
3479:
3480: =cut
3481:
3482: sub nickname {
3483: my ($uname,$udom)=@_;
3484: return if (!defined($uname) || !defined($udom));
3485: my %names=&getnames($uname,$udom);
3486: my $name=$names{'nickname'};
3487: if ($name) {
3488: $name='"'.$name.'"';
3489: } else {
3490: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3491: $names{'lastname'}.' '.$names{'generation'};
3492: $name=~s/\s+$//;
3493: $name=~s/\s+/ /g;
3494: }
3495: return $name;
3496: }
3497:
3498: sub getnames {
3499: my ($uname,$udom)=@_;
3500: return if (!defined($uname) || !defined($udom));
3501: if ($udom eq 'public' && $uname eq 'public') {
3502: return ('lastname' => &mt('Public'));
3503: }
3504: my $id=$uname.':'.$udom;
3505: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3506: if ($cached) {
3507: return %{$names};
3508: } else {
3509: my %loadnames=&Apache::lonnet::get('environment',
3510: ['firstname','middlename','lastname','generation','nickname'],
3511: $udom,$uname);
3512: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3513: return %loadnames;
3514: }
3515: }
3516:
3517: # -------------------------------------------------------------------- getemails
3518:
3519: =pod
3520:
3521: =item * &getemails($uname,$udom)
3522:
3523: Gets a user's email information and returns it as a hash with keys:
3524: notification, critnotification, permanentemail
3525:
3526: For notification and critnotification, values are comma-separated lists
3527: of e-mail addresses; for permanentemail, value is a single e-mail address.
3528:
3529:
3530: =cut
3531:
3532:
3533: sub getemails {
3534: my ($uname,$udom)=@_;
3535: if ($udom eq 'public' && $uname eq 'public') {
3536: return;
3537: }
3538: if (!$udom) { $udom=$env{'user.domain'}; }
3539: if (!$uname) { $uname=$env{'user.name'}; }
3540: my $id=$uname.':'.$udom;
3541: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3542: if ($cached) {
3543: return %{$names};
3544: } else {
3545: my %loadnames=&Apache::lonnet::get('environment',
3546: ['notification','critnotification',
3547: 'permanentemail'],
3548: $udom,$uname);
3549: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3550: return %loadnames;
3551: }
3552: }
3553:
3554: sub flush_email_cache {
3555: my ($uname,$udom)=@_;
3556: if (!$udom) { $udom =$env{'user.domain'}; }
3557: if (!$uname) { $uname=$env{'user.name'}; }
3558: return if ($udom eq 'public' && $uname eq 'public');
3559: my $id=$uname.':'.$udom;
3560: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3561: }
3562:
3563: # -------------------------------------------------------------------- getlangs
3564:
3565: =pod
3566:
3567: =item * &getlangs($uname,$udom)
3568:
3569: Gets a user's language preference and returns it as a hash with key:
3570: language.
3571:
3572: =cut
3573:
3574:
3575: sub getlangs {
3576: my ($uname,$udom) = @_;
3577: if (!$udom) { $udom =$env{'user.domain'}; }
3578: if (!$uname) { $uname=$env{'user.name'}; }
3579: my $id=$uname.':'.$udom;
3580: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3581: if ($cached) {
3582: return %{$langs};
3583: } else {
3584: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3585: $udom,$uname);
3586: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3587: return %loadlangs;
3588: }
3589: }
3590:
3591: sub flush_langs_cache {
3592: my ($uname,$udom)=@_;
3593: if (!$udom) { $udom =$env{'user.domain'}; }
3594: if (!$uname) { $uname=$env{'user.name'}; }
3595: return if ($udom eq 'public' && $uname eq 'public');
3596: my $id=$uname.':'.$udom;
3597: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3598: }
3599:
3600: # ------------------------------------------------------------------ Screenname
3601:
3602: =pod
3603:
3604: =item * &screenname($uname,$udom)
3605:
3606: Gets a users screenname and returns it as a string
3607:
3608: =cut
3609:
3610: sub screenname {
3611: my ($uname,$udom)=@_;
3612: if ($uname eq $env{'user.name'} &&
3613: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3614: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3615: return $names{'screenname'};
3616: }
3617:
3618:
3619: # ------------------------------------------------------------- Confirm Wrapper
3620: =pod
3621:
3622: =item * &confirmwrapper($message)
3623:
3624: Wrap messages about completion of operation in box
3625:
3626: =cut
3627:
3628: sub confirmwrapper {
3629: my ($message)=@_;
3630: if ($message) {
3631: return "\n".'<div class="LC_confirm_box">'."\n"
3632: .$message."\n"
3633: .'</div>'."\n";
3634: } else {
3635: return $message;
3636: }
3637: }
3638:
3639: # ------------------------------------------------------------- Message Wrapper
3640:
3641: sub messagewrapper {
3642: my ($link,$username,$domain,$subject,$text)=@_;
3643: return
3644: '<a href="/adm/email?compose=individual&'.
3645: 'recname='.$username.'&recdom='.$domain.
3646: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3647: 'title="'.&mt('Send message').'">'.$link.'</a>';
3648: }
3649:
3650: # --------------------------------------------------------------- Notes Wrapper
3651:
3652: sub noteswrapper {
3653: my ($link,$un,$do)=@_;
3654: return
3655: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3656: }
3657:
3658: # ------------------------------------------------------------- Aboutme Wrapper
3659:
3660: sub aboutmewrapper {
3661: my ($link,$username,$domain,$target,$class)=@_;
3662: if (!defined($username) && !defined($domain)) {
3663: return;
3664: }
3665: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3666: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3667: }
3668:
3669: # ------------------------------------------------------------ Syllabus Wrapper
3670:
3671: sub syllabuswrapper {
3672: my ($linktext,$coursedir,$domain)=@_;
3673: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3674: }
3675:
3676: # -----------------------------------------------------------------------------
3677:
3678: sub track_student_link {
3679: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3680: my $link ="/adm/trackstudent?";
3681: my $title = 'View recent activity';
3682: if (defined($sname) && $sname !~ /^\s*$/ &&
3683: defined($sdom) && $sdom !~ /^\s*$/) {
3684: $link .= "selected_student=$sname:$sdom";
3685: $title .= ' of this student';
3686: }
3687: if (defined($target) && $target !~ /^\s*$/) {
3688: $target = qq{target="$target"};
3689: } else {
3690: $target = '';
3691: }
3692: if ($start) { $link.='&start='.$start; }
3693: if ($only_body) { $link .= '&only_body=1'; }
3694: $title = &mt($title);
3695: $linktext = &mt($linktext);
3696: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3697: &help_open_topic('View_recent_activity');
3698: }
3699:
3700: sub slot_reservations_link {
3701: my ($linktext,$sname,$sdom,$target) = @_;
3702: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3703: my $title = 'View slot reservation history';
3704: if (defined($sname) && $sname !~ /^\s*$/ &&
3705: defined($sdom) && $sdom !~ /^\s*$/) {
3706: $link .= "&uname=$sname&udom=$sdom";
3707: $title .= ' of this student';
3708: }
3709: if (defined($target) && $target !~ /^\s*$/) {
3710: $target = qq{target="$target"};
3711: } else {
3712: $target = '';
3713: }
3714: $title = &mt($title);
3715: $linktext = &mt($linktext);
3716: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3717: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3718:
3719: }
3720:
3721: # ===================================================== Display a student photo
3722:
3723:
3724: sub student_image_tag {
3725: my ($domain,$user)=@_;
3726: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3727: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3728: return '<img src="'.$imgsrc.'" align="right" />';
3729: } else {
3730: return '';
3731: }
3732: }
3733:
3734: =pod
3735:
3736: =back
3737:
3738: =head1 Access .tab File Data
3739:
3740: =over 4
3741:
3742: =item * &languageids()
3743:
3744: returns list of all language ids
3745:
3746: =cut
3747:
3748: sub languageids {
3749: return sort(keys(%language));
3750: }
3751:
3752: =pod
3753:
3754: =item * &languagedescription()
3755:
3756: returns description of a specified language id
3757:
3758: =cut
3759:
3760: sub languagedescription {
3761: my $code=shift;
3762: return ($supported_language{$code}?'* ':'').
3763: $language{$code}.
3764: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3765: }
3766:
3767: =pod
3768:
3769: =item * &plainlanguagedescription
3770:
3771: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3772: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3773:
3774: =cut
3775:
3776: sub plainlanguagedescription {
3777: my $code=shift;
3778: return $language{$code};
3779: }
3780:
3781: =pod
3782:
3783: =item * &supportedlanguagecode
3784:
3785: Returns the supported language code (e.g. sptutf maps to pt) given a language
3786: code.
3787:
3788: =cut
3789:
3790: sub supportedlanguagecode {
3791: my $code=shift;
3792: return $supported_language{$code};
3793: }
3794:
3795: =pod
3796:
3797: =item * &latexlanguage()
3798:
3799: Given a language key code returns the correspondnig language to use
3800: to select the correct hyphenation on LaTeX printouts. This is undef if there
3801: is no supported hyphenation for the language code.
3802:
3803: =cut
3804:
3805: sub latexlanguage {
3806: my $code = shift;
3807: return $latex_language{$code};
3808: }
3809:
3810: =pod
3811:
3812: =item * &latexhyphenation()
3813:
3814: Same as above but what's supplied is the language as it might be stored
3815: in the metadata.
3816:
3817: =cut
3818:
3819: sub latexhyphenation {
3820: my $key = shift;
3821: return $latex_language_bykey{$key};
3822: }
3823:
3824: =pod
3825:
3826: =item * ©rightids()
3827:
3828: returns list of all copyrights
3829:
3830: =cut
3831:
3832: sub copyrightids {
3833: return sort(keys(%cprtag));
3834: }
3835:
3836: =pod
3837:
3838: =item * ©rightdescription()
3839:
3840: returns description of a specified copyright id
3841:
3842: =cut
3843:
3844: sub copyrightdescription {
3845: return &mt($cprtag{shift(@_)});
3846: }
3847:
3848: =pod
3849:
3850: =item * &source_copyrightids()
3851:
3852: returns list of all source copyrights
3853:
3854: =cut
3855:
3856: sub source_copyrightids {
3857: return sort(keys(%scprtag));
3858: }
3859:
3860: =pod
3861:
3862: =item * &source_copyrightdescription()
3863:
3864: returns description of a specified source copyright id
3865:
3866: =cut
3867:
3868: sub source_copyrightdescription {
3869: return &mt($scprtag{shift(@_)});
3870: }
3871:
3872: =pod
3873:
3874: =item * &filecategories()
3875:
3876: returns list of all file categories
3877:
3878: =cut
3879:
3880: sub filecategories {
3881: return sort(keys(%category_extensions));
3882: }
3883:
3884: =pod
3885:
3886: =item * &filecategorytypes()
3887:
3888: returns list of file types belonging to a given file
3889: category
3890:
3891: =cut
3892:
3893: sub filecategorytypes {
3894: my ($cat) = @_;
3895: return @{$category_extensions{lc($cat)}};
3896: }
3897:
3898: =pod
3899:
3900: =item * &fileembstyle()
3901:
3902: returns embedding style for a specified file type
3903:
3904: =cut
3905:
3906: sub fileembstyle {
3907: return $fe{lc(shift(@_))};
3908: }
3909:
3910: sub filemimetype {
3911: return $fm{lc(shift(@_))};
3912: }
3913:
3914:
3915: sub filecategoryselect {
3916: my ($name,$value)=@_;
3917: return &select_form($value,$name,
3918: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3919: }
3920:
3921: =pod
3922:
3923: =item * &filedescription()
3924:
3925: returns description for a specified file type
3926:
3927: =cut
3928:
3929: sub filedescription {
3930: my $file_description = $fd{lc(shift())};
3931: $file_description =~ s:([\[\]]):~$1:g;
3932: return &mt($file_description);
3933: }
3934:
3935: =pod
3936:
3937: =item * &filedescriptionex()
3938:
3939: returns description for a specified file type with
3940: extra formatting
3941:
3942: =cut
3943:
3944: sub filedescriptionex {
3945: my $ex=shift;
3946: my $file_description = $fd{lc($ex)};
3947: $file_description =~ s:([\[\]]):~$1:g;
3948: return '.'.$ex.' '.&mt($file_description);
3949: }
3950:
3951: # End of .tab access
3952: =pod
3953:
3954: =back
3955:
3956: =cut
3957:
3958: # ------------------------------------------------------------------ File Types
3959: sub fileextensions {
3960: return sort(keys(%fe));
3961: }
3962:
3963: # ----------------------------------------------------------- Display Languages
3964: # returns a hash with all desired display languages
3965: #
3966:
3967: sub display_languages {
3968: my %languages=();
3969: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3970: $languages{$lang}=1;
3971: }
3972: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3973: if ($env{'form.displaylanguage'}) {
3974: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3975: $languages{$lang}=1;
3976: }
3977: }
3978: return %languages;
3979: }
3980:
3981: sub languages {
3982: my ($possible_langs) = @_;
3983: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3984: if (!ref($possible_langs)) {
3985: if( wantarray ) {
3986: return @preferred_langs;
3987: } else {
3988: return $preferred_langs[0];
3989: }
3990: }
3991: my %possibilities = map { $_ => 1 } (@$possible_langs);
3992: my @preferred_possibilities;
3993: foreach my $preferred_lang (@preferred_langs) {
3994: if (exists($possibilities{$preferred_lang})) {
3995: push(@preferred_possibilities, $preferred_lang);
3996: }
3997: }
3998: if( wantarray ) {
3999: return @preferred_possibilities;
4000: }
4001: return $preferred_possibilities[0];
4002: }
4003:
4004: sub user_lang {
4005: my ($touname,$toudom,$fromcid) = @_;
4006: my @userlangs;
4007: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4008: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4009: $env{'course.'.$fromcid.'.languages'}));
4010: } else {
4011: my %langhash = &getlangs($touname,$toudom);
4012: if ($langhash{'languages'} ne '') {
4013: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4014: } else {
4015: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4016: if ($domdefs{'lang_def'} ne '') {
4017: @userlangs = ($domdefs{'lang_def'});
4018: }
4019: }
4020: }
4021: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4022: my $user_lh = Apache::localize->get_handle(@languages);
4023: return $user_lh;
4024: }
4025:
4026:
4027: ###############################################################
4028: ## Student Answer Attempts ##
4029: ###############################################################
4030:
4031: =pod
4032:
4033: =head1 Alternate Problem Views
4034:
4035: =over 4
4036:
4037: =item * &get_previous_attempt($symb, $username, $domain, $course,
4038: $getattempt, $regexp, $gradesub, $usec, $identifier)
4039:
4040: Return string with previous attempt on problem. Arguments:
4041:
4042: =over 4
4043:
4044: =item * $symb: Problem, including path
4045:
4046: =item * $username: username of the desired student
4047:
4048: =item * $domain: domain of the desired student
4049:
4050: =item * $course: Course ID
4051:
4052: =item * $getattempt: Leave blank for all attempts, otherwise put
4053: something
4054:
4055: =item * $regexp: if string matches this regexp, the string will be
4056: sent to $gradesub
4057:
4058: =item * $gradesub: routine that processes the string if it matches $regexp
4059:
4060: =item * $usec: section of the desired student
4061:
4062: =item * $identifier: counter for student (multiple students one problem) or
4063: problem (one student; whole sequence).
4064:
4065: =back
4066:
4067: The output string is a table containing all desired attempts, if any.
4068:
4069: =cut
4070:
4071: sub get_previous_attempt {
4072: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4073: my $prevattempts='';
4074: no strict 'refs';
4075: if ($symb) {
4076: my (%returnhash)=
4077: &Apache::lonnet::restore($symb,$course,$domain,$username);
4078: if ($returnhash{'version'}) {
4079: my %lasthash=();
4080: my $version;
4081: for ($version=1;$version<=$returnhash{'version'};$version++) {
4082: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4083: if ($key =~ /\.rawrndseed$/) {
4084: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4085: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4086: } else {
4087: $lasthash{$key}=$returnhash{$version.':'.$key};
4088: }
4089: }
4090: }
4091: $prevattempts=&start_data_table().&start_data_table_header_row();
4092: $prevattempts.='<th>'.&mt('History').'</th>';
4093: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4094: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4095: foreach my $key (sort(keys(%lasthash))) {
4096: my ($ign,@parts) = split(/\./,$key);
4097: if ($#parts > 0) {
4098: my $data=$parts[-1];
4099: next if ($data eq 'foilorder');
4100: pop(@parts);
4101: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4102: if ($data eq 'type') {
4103: unless ($showsurv) {
4104: my $id = join(',',@parts);
4105: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4106: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4107: $lasthidden{$ign.'.'.$id} = 1;
4108: }
4109: }
4110: if ($identifier ne '') {
4111: my $id = join(',',@parts);
4112: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4113: $domain,$username,$usec,undef,$course) =~ /^no/) {
4114: $hidestatus{$ign.'.'.$id} = 1;
4115: }
4116: }
4117: } elsif ($data eq 'regrader') {
4118: if (($identifier ne '') && (@parts)) {
4119: my $id = join(',',@parts);
4120: $regraded{$ign.'.'.$id} = 1;
4121: }
4122: }
4123: } else {
4124: if ($#parts == 0) {
4125: $prevattempts.='<th>'.$parts[0].'</th>';
4126: } else {
4127: $prevattempts.='<th>'.$ign.'</th>';
4128: }
4129: }
4130: }
4131: $prevattempts.=&end_data_table_header_row();
4132: if ($getattempt eq '') {
4133: my (%solved,%resets,%probstatus);
4134: if (($identifier ne '') && (keys(%regraded) > 0)) {
4135: for ($version=1;$version<=$returnhash{'version'};$version++) {
4136: foreach my $id (keys(%regraded)) {
4137: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4138: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4139: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4140: push(@{$resets{$id}},$version);
4141: }
4142: }
4143: }
4144: }
4145: for ($version=1;$version<=$returnhash{'version'};$version++) {
4146: my (@hidden,@unsolved);
4147: if (%typeparts) {
4148: foreach my $id (keys(%typeparts)) {
4149: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4150: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4151: push(@hidden,$id);
4152: } elsif ($identifier ne '') {
4153: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4154: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4155: ($hidestatus{$id})) {
4156: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4157: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4158: push(@{$solved{$id}},$version);
4159: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4160: (ref($solved{$id}) eq 'ARRAY')) {
4161: my $skip;
4162: if (ref($resets{$id}) eq 'ARRAY') {
4163: foreach my $reset (@{$resets{$id}}) {
4164: if ($reset > $solved{$id}[-1]) {
4165: $skip=1;
4166: last;
4167: }
4168: }
4169: }
4170: unless ($skip) {
4171: my ($ign,$partslist) = split(/\./,$id,2);
4172: push(@unsolved,$partslist);
4173: }
4174: }
4175: }
4176: }
4177: }
4178: }
4179: $prevattempts.=&start_data_table_row().
4180: '<td>'.&mt('Transaction [_1]',$version);
4181: if (@unsolved) {
4182: $prevattempts .= '<span class="LC_nobreak"><label>'.
4183: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4184: &mt('Hide').'</label></span>';
4185: }
4186: $prevattempts .= '</td>';
4187: if (@hidden) {
4188: foreach my $key (sort(keys(%lasthash))) {
4189: next if ($key =~ /\.foilorder$/);
4190: my $hide;
4191: foreach my $id (@hidden) {
4192: if ($key =~ /^\Q$id\E/) {
4193: $hide = 1;
4194: last;
4195: }
4196: }
4197: if ($hide) {
4198: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4199: if (($data eq 'award') || ($data eq 'awarddetail')) {
4200: my $value = &format_previous_attempt_value($key,
4201: $returnhash{$version.':'.$key});
4202: $prevattempts.='<td>'.$value.' </td>';
4203: } else {
4204: $prevattempts.='<td> </td>';
4205: }
4206: } else {
4207: if ($key =~ /\./) {
4208: my $value = $returnhash{$version.':'.$key};
4209: if ($key =~ /\.rndseed$/) {
4210: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4211: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4212: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4213: }
4214: }
4215: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4216: ' </td>';
4217: } else {
4218: $prevattempts.='<td> </td>';
4219: }
4220: }
4221: }
4222: } else {
4223: foreach my $key (sort(keys(%lasthash))) {
4224: next if ($key =~ /\.foilorder$/);
4225: my $value = $returnhash{$version.':'.$key};
4226: if ($key =~ /\.rndseed$/) {
4227: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4228: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4229: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4230: }
4231: }
4232: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4233: ' </td>';
4234: }
4235: }
4236: $prevattempts.=&end_data_table_row();
4237: }
4238: }
4239: my @currhidden = keys(%lasthidden);
4240: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4241: foreach my $key (sort(keys(%lasthash))) {
4242: next if ($key =~ /\.foilorder$/);
4243: if (%typeparts) {
4244: my $hidden;
4245: foreach my $id (@currhidden) {
4246: if ($key =~ /^\Q$id\E/) {
4247: $hidden = 1;
4248: last;
4249: }
4250: }
4251: if ($hidden) {
4252: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4253: if (($data eq 'award') || ($data eq 'awarddetail')) {
4254: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4255: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4256: $value = &$gradesub($value);
4257: }
4258: $prevattempts.='<td>'.$value.' </td>';
4259: } else {
4260: $prevattempts.='<td> </td>';
4261: }
4262: } else {
4263: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4264: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4265: $value = &$gradesub($value);
4266: }
4267: $prevattempts.='<td>'.$value.' </td>';
4268: }
4269: } else {
4270: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4271: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4272: $value = &$gradesub($value);
4273: }
4274: $prevattempts.='<td>'.$value.' </td>';
4275: }
4276: }
4277: $prevattempts.= &end_data_table_row().&end_data_table();
4278: } else {
4279: $prevattempts=
4280: &start_data_table().&start_data_table_row().
4281: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
4282: &end_data_table_row().&end_data_table();
4283: }
4284: } else {
4285: $prevattempts=
4286: &start_data_table().&start_data_table_row().
4287: '<td>'.&mt('No data.').'</td>'.
4288: &end_data_table_row().&end_data_table();
4289: }
4290: }
4291:
4292: sub format_previous_attempt_value {
4293: my ($key,$value) = @_;
4294: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4295: $value = &Apache::lonlocal::locallocaltime($value);
4296: } elsif (ref($value) eq 'ARRAY') {
4297: $value = '('.join(', ', @{ $value }).')';
4298: } elsif ($key =~ /answerstring$/) {
4299: my %answers = &Apache::lonnet::str2hash($value);
4300: my @anskeys = sort(keys(%answers));
4301: if (@anskeys == 1) {
4302: my $answer = $answers{$anskeys[0]};
4303: if ($answer =~ m{\0}) {
4304: $answer =~ s{\0}{,}g;
4305: }
4306: my $tag_internal_answer_name = 'INTERNAL';
4307: if ($anskeys[0] eq $tag_internal_answer_name) {
4308: $value = $answer;
4309: } else {
4310: $value = $anskeys[0].'='.$answer;
4311: }
4312: } else {
4313: foreach my $ans (@anskeys) {
4314: my $answer = $answers{$ans};
4315: if ($answer =~ m{\0}) {
4316: $answer =~ s{\0}{,}g;
4317: }
4318: $value .= $ans.'='.$answer.'<br />';;
4319: }
4320: }
4321: } else {
4322: $value = &unescape($value);
4323: }
4324: return $value;
4325: }
4326:
4327:
4328: sub relative_to_absolute {
4329: my ($url,$output)=@_;
4330: my $parser=HTML::TokeParser->new(\$output);
4331: my $token;
4332: my $thisdir=$url;
4333: my @rlinks=();
4334: while ($token=$parser->get_token) {
4335: if ($token->[0] eq 'S') {
4336: if ($token->[1] eq 'a') {
4337: if ($token->[2]->{'href'}) {
4338: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4339: }
4340: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4341: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4342: } elsif ($token->[1] eq 'base') {
4343: $thisdir=$token->[2]->{'href'};
4344: }
4345: }
4346: }
4347: $thisdir=~s-/[^/]*$--;
4348: foreach my $link (@rlinks) {
4349: unless (($link=~/^https?\:\/\//i) ||
4350: ($link=~/^\//) ||
4351: ($link=~/^javascript:/i) ||
4352: ($link=~/^mailto:/i) ||
4353: ($link=~/^\#/)) {
4354: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4355: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4356: }
4357: }
4358: # -------------------------------------------------- Deal with Applet codebases
4359: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4360: return $output;
4361: }
4362:
4363: =pod
4364:
4365: =item * &get_student_view()
4366:
4367: show a snapshot of what student was looking at
4368:
4369: =cut
4370:
4371: sub get_student_view {
4372: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4373: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4374: my (%form);
4375: my @elements=('symb','courseid','domain','username');
4376: foreach my $element (@elements) {
4377: $form{'grade_'.$element}=eval '$'.$element #'
4378: }
4379: if (defined($moreenv)) {
4380: %form=(%form,%{$moreenv});
4381: }
4382: if (defined($target)) { $form{'grade_target'} = $target; }
4383: $feedurl=&Apache::lonnet::clutter($feedurl);
4384: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4385: $userview=~s/\<body[^\>]*\>//gi;
4386: $userview=~s/\<\/body\>//gi;
4387: $userview=~s/\<html\>//gi;
4388: $userview=~s/\<\/html\>//gi;
4389: $userview=~s/\<head\>//gi;
4390: $userview=~s/\<\/head\>//gi;
4391: $userview=~s/action\s*\=/would_be_action\=/gi;
4392: $userview=&relative_to_absolute($feedurl,$userview);
4393: if (wantarray) {
4394: return ($userview,$response);
4395: } else {
4396: return $userview;
4397: }
4398: }
4399:
4400: sub get_student_view_with_retries {
4401: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4402:
4403: my $ok = 0; # True if we got a good response.
4404: my $content;
4405: my $response;
4406:
4407: # Try to get the student_view done. within the retries count:
4408:
4409: do {
4410: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4411: $ok = $response->is_success;
4412: if (!$ok) {
4413: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4414: }
4415: $retries--;
4416: } while (!$ok && ($retries > 0));
4417:
4418: if (!$ok) {
4419: $content = ''; # On error return an empty content.
4420: }
4421: if (wantarray) {
4422: return ($content, $response);
4423: } else {
4424: return $content;
4425: }
4426: }
4427:
4428: =pod
4429:
4430: =item * &get_student_answers()
4431:
4432: show a snapshot of how student was answering problem
4433:
4434: =cut
4435:
4436: sub get_student_answers {
4437: my ($symb,$username,$domain,$courseid,%form) = @_;
4438: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4439: my (%moreenv);
4440: my @elements=('symb','courseid','domain','username');
4441: foreach my $element (@elements) {
4442: $moreenv{'grade_'.$element}=eval '$'.$element #'
4443: }
4444: $moreenv{'grade_target'}='answer';
4445: %moreenv=(%form,%moreenv);
4446: $feedurl = &Apache::lonnet::clutter($feedurl);
4447: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4448: return $userview;
4449: }
4450:
4451: =pod
4452:
4453: =item * &submlink()
4454:
4455: Inputs: $text $uname $udom $symb $target
4456:
4457: Returns: A link to grades.pm such as to see the SUBM view of a student
4458:
4459: =cut
4460:
4461: ###############################################
4462: sub submlink {
4463: my ($text,$uname,$udom,$symb,$target)=@_;
4464: if (!($uname && $udom)) {
4465: (my $cursymb, my $courseid,$udom,$uname)=
4466: &Apache::lonnet::whichuser($symb);
4467: if (!$symb) { $symb=$cursymb; }
4468: }
4469: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4470: $symb=&escape($symb);
4471: if ($target) { $target=" target=\"$target\""; }
4472: return
4473: '<a href="/adm/grades?command=submission'.
4474: '&symb='.$symb.
4475: '&student='.$uname.
4476: '&userdom='.$udom.'"'.
4477: $target.'>'.$text.'</a>';
4478: }
4479: ##############################################
4480:
4481: =pod
4482:
4483: =item * &pgrdlink()
4484:
4485: Inputs: $text $uname $udom $symb $target
4486:
4487: Returns: A link to grades.pm such as to see the PGRD view of a student
4488:
4489: =cut
4490:
4491: ###############################################
4492: sub pgrdlink {
4493: my $link=&submlink(@_);
4494: $link=~s/(&command=submission)/$1&showgrading=yes/;
4495: return $link;
4496: }
4497: ##############################################
4498:
4499: =pod
4500:
4501: =item * &pprmlink()
4502:
4503: Inputs: $text $uname $udom $symb $target
4504:
4505: Returns: A link to parmset.pm such as to see the PPRM view of a
4506: student and a specific resource
4507:
4508: =cut
4509:
4510: ###############################################
4511: sub pprmlink {
4512: my ($text,$uname,$udom,$symb,$target)=@_;
4513: if (!($uname && $udom)) {
4514: (my $cursymb, my $courseid,$udom,$uname)=
4515: &Apache::lonnet::whichuser($symb);
4516: if (!$symb) { $symb=$cursymb; }
4517: }
4518: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4519: $symb=&escape($symb);
4520: if ($target) { $target="target=\"$target\""; }
4521: return '<a href="/adm/parmset?command=set&'.
4522: 'symb='.$symb.'&uname='.$uname.
4523: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4524: }
4525: ##############################################
4526:
4527: =pod
4528:
4529: =back
4530:
4531: =cut
4532:
4533: ###############################################
4534:
4535:
4536: sub timehash {
4537: my ($thistime) = @_;
4538: my $timezone = &Apache::lonlocal::gettimezone();
4539: my $dt = DateTime->from_epoch(epoch => $thistime)
4540: ->set_time_zone($timezone);
4541: my $wday = $dt->day_of_week();
4542: if ($wday == 7) { $wday = 0; }
4543: return ( 'second' => $dt->second(),
4544: 'minute' => $dt->minute(),
4545: 'hour' => $dt->hour(),
4546: 'day' => $dt->day_of_month(),
4547: 'month' => $dt->month(),
4548: 'year' => $dt->year(),
4549: 'weekday' => $wday,
4550: 'dayyear' => $dt->day_of_year(),
4551: 'dlsav' => $dt->is_dst() );
4552: }
4553:
4554: sub utc_string {
4555: my ($date)=@_;
4556: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4557: }
4558:
4559: sub maketime {
4560: my %th=@_;
4561: my ($epoch_time,$timezone,$dt);
4562: $timezone = &Apache::lonlocal::gettimezone();
4563: eval {
4564: $dt = DateTime->new( year => $th{'year'},
4565: month => $th{'month'},
4566: day => $th{'day'},
4567: hour => $th{'hour'},
4568: minute => $th{'minute'},
4569: second => $th{'second'},
4570: time_zone => $timezone,
4571: );
4572: };
4573: if (!$@) {
4574: $epoch_time = $dt->epoch;
4575: if ($epoch_time) {
4576: return $epoch_time;
4577: }
4578: }
4579: return POSIX::mktime(
4580: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4581: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4582: }
4583:
4584: #########################################
4585:
4586: sub findallcourses {
4587: my ($roles,$uname,$udom) = @_;
4588: my %roles;
4589: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4590: my %courses;
4591: my $now=time;
4592: if (!defined($uname)) {
4593: $uname = $env{'user.name'};
4594: }
4595: if (!defined($udom)) {
4596: $udom = $env{'user.domain'};
4597: }
4598: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4599: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4600: if (!%roles) {
4601: %roles = (
4602: cc => 1,
4603: co => 1,
4604: in => 1,
4605: ep => 1,
4606: ta => 1,
4607: cr => 1,
4608: st => 1,
4609: );
4610: }
4611: foreach my $entry (keys(%roleshash)) {
4612: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4613: if ($trole =~ /^cr/) {
4614: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4615: } else {
4616: next if (!exists($roles{$trole}));
4617: }
4618: if ($tend) {
4619: next if ($tend < $now);
4620: }
4621: if ($tstart) {
4622: next if ($tstart > $now);
4623: }
4624: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4625: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4626: my $value = $trole.'/'.$cdom.'/';
4627: if ($secpart eq '') {
4628: ($cnum,$role) = split(/_/,$cnumpart);
4629: $sec = 'none';
4630: $value .= $cnum.'/';
4631: } else {
4632: $cnum = $cnumpart;
4633: ($sec,$role) = split(/_/,$secpart);
4634: $value .= $cnum.'/'.$sec;
4635: }
4636: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4637: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4638: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4639: }
4640: } else {
4641: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4642: }
4643: }
4644: } else {
4645: foreach my $key (keys(%env)) {
4646: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4647: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4648: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4649: next if ($role eq 'ca' || $role eq 'aa');
4650: next if (%roles && !exists($roles{$role}));
4651: my ($starttime,$endtime)=split(/\./,$env{$key});
4652: my $active=1;
4653: if ($starttime) {
4654: if ($now<$starttime) { $active=0; }
4655: }
4656: if ($endtime) {
4657: if ($now>$endtime) { $active=0; }
4658: }
4659: if ($active) {
4660: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4661: if ($sec eq '') {
4662: $sec = 'none';
4663: } else {
4664: $value .= $sec;
4665: }
4666: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4667: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4668: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4669: }
4670: } else {
4671: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4672: }
4673: }
4674: }
4675: }
4676: }
4677: return %courses;
4678: }
4679:
4680: ###############################################
4681:
4682: sub blockcheck {
4683: my ($setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
4684:
4685: if (defined($udom) && defined($uname)) {
4686: # If uname and udom are for a course, check for blocks in the course.
4687: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4688: my ($startblock,$endblock,$triggerblock) =
4689: &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
4690: return ($startblock,$endblock,$triggerblock);
4691: }
4692: } else {
4693: $udom = $env{'user.domain'};
4694: $uname = $env{'user.name'};
4695: }
4696:
4697: my $startblock = 0;
4698: my $endblock = 0;
4699: my $triggerblock = '';
4700: my %live_courses = &findallcourses(undef,$uname,$udom);
4701:
4702: # If uname is for a user, and activity is course-specific, i.e.,
4703: # boards, chat or groups, check for blocking in current course only.
4704:
4705: if (($activity eq 'boards' || $activity eq 'chat' ||
4706: $activity eq 'groups' || $activity eq 'printout' ||
4707: $activity eq 'search' || $activity eq 'reinit' ||
4708: $activity eq 'alert') &&
4709: ($env{'request.course.id'})) {
4710: foreach my $key (keys(%live_courses)) {
4711: if ($key ne $env{'request.course.id'}) {
4712: delete($live_courses{$key});
4713: }
4714: }
4715: }
4716:
4717: my $otheruser = 0;
4718: my %own_courses;
4719: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4720: # Resource belongs to user other than current user.
4721: $otheruser = 1;
4722: # Gather courses for current user
4723: %own_courses =
4724: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4725: }
4726:
4727: # Gather active course roles - course coordinator, instructor,
4728: # exam proctor, ta, student, or custom role.
4729:
4730: foreach my $course (keys(%live_courses)) {
4731: my ($cdom,$cnum);
4732: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4733: $cdom = $env{'course.'.$course.'.domain'};
4734: $cnum = $env{'course.'.$course.'.num'};
4735: } else {
4736: ($cdom,$cnum) = split(/_/,$course);
4737: }
4738: my $no_ownblock = 0;
4739: my $no_userblock = 0;
4740: if ($otheruser && $activity ne 'com') {
4741: # Check if current user has 'evb' priv for this
4742: if (defined($own_courses{$course})) {
4743: foreach my $sec (keys(%{$own_courses{$course}})) {
4744: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4745: if ($sec ne 'none') {
4746: $checkrole .= '/'.$sec;
4747: }
4748: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4749: $no_ownblock = 1;
4750: last;
4751: }
4752: }
4753: }
4754: # if they have 'evb' priv and are currently not playing student
4755: next if (($no_ownblock) &&
4756: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4757: }
4758: foreach my $sec (keys(%{$live_courses{$course}})) {
4759: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4760: if ($sec ne 'none') {
4761: $checkrole .= '/'.$sec;
4762: }
4763: if ($otheruser) {
4764: # Resource belongs to user other than current user.
4765: # Assemble privs for that user, and check for 'evb' priv.
4766: my (%allroles,%userroles);
4767: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4768: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4769: my ($trole,$tdom,$tnum,$tsec);
4770: if ($entry =~ /^cr/) {
4771: ($trole,$tdom,$tnum,$tsec) =
4772: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4773: } else {
4774: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4775: }
4776: my ($spec,$area,$trest);
4777: $area = '/'.$tdom.'/'.$tnum;
4778: $trest = $tnum;
4779: if ($tsec ne '') {
4780: $area .= '/'.$tsec;
4781: $trest .= '/'.$tsec;
4782: }
4783: $spec = $trole.'.'.$area;
4784: if ($trole =~ /^cr/) {
4785: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4786: $tdom,$spec,$trest,$area);
4787: } else {
4788: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4789: $tdom,$spec,$trest,$area);
4790: }
4791: }
4792: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4793: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4794: if ($1) {
4795: $no_userblock = 1;
4796: last;
4797: }
4798: }
4799: }
4800: } else {
4801: # Resource belongs to current user
4802: # Check for 'evb' priv via lonnet::allowed().
4803: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4804: $no_ownblock = 1;
4805: last;
4806: }
4807: }
4808: }
4809: # if they have the evb priv and are currently not playing student
4810: next if (($no_ownblock) &&
4811: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4812: next if ($no_userblock);
4813:
4814: # Retrieve blocking times and identity of blocker for course
4815: # of specified user, unless user has 'evb' privilege.
4816:
4817: my ($start,$end,$trigger) =
4818: &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
4819: if (($start != 0) &&
4820: (($startblock == 0) || ($startblock > $start))) {
4821: $startblock = $start;
4822: if ($trigger ne '') {
4823: $triggerblock = $trigger;
4824: }
4825: }
4826: if (($end != 0) &&
4827: (($endblock == 0) || ($endblock < $end))) {
4828: $endblock = $end;
4829: if ($trigger ne '') {
4830: $triggerblock = $trigger;
4831: }
4832: }
4833: }
4834: return ($startblock,$endblock,$triggerblock);
4835: }
4836:
4837: sub get_blocks {
4838: my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
4839: my $startblock = 0;
4840: my $endblock = 0;
4841: my $triggerblock = '';
4842: my $course = $cdom.'_'.$cnum;
4843: $setters->{$course} = {};
4844: $setters->{$course}{'staff'} = [];
4845: $setters->{$course}{'times'} = [];
4846: $setters->{$course}{'triggers'} = [];
4847: my (@blockers,%triggered);
4848: my $now = time;
4849: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4850: if ($activity eq 'docs') {
4851: my ($blocked,$nosymbcache);
4852: if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
4853: $blocked = 1;
4854: $nosymbcache = 1;
4855: }
4856: @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$blocked,\%commblocks);
4857: foreach my $block (@blockers) {
4858: if ($block =~ /^firstaccess____(.+)$/) {
4859: my $item = $1;
4860: my $type = 'map';
4861: my $timersymb = $item;
4862: if ($item eq 'course') {
4863: $type = 'course';
4864: } elsif ($item =~ /___\d+___/) {
4865: $type = 'resource';
4866: } else {
4867: $timersymb = &Apache::lonnet::symbread($item);
4868: }
4869: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4870: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4871: $triggered{$block} = {
4872: start => $start,
4873: end => $end,
4874: type => $type,
4875: };
4876: }
4877: }
4878: } else {
4879: foreach my $block (keys(%commblocks)) {
4880: if ($block =~ m/^(\d+)____(\d+)$/) {
4881: my ($start,$end) = ($1,$2);
4882: if ($start <= time && $end >= time) {
4883: if (ref($commblocks{$block}) eq 'HASH') {
4884: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4885: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4886: unless(grep(/^\Q$block\E$/,@blockers)) {
4887: push(@blockers,$block);
4888: }
4889: }
4890: }
4891: }
4892: }
4893: } elsif ($block =~ /^firstaccess____(.+)$/) {
4894: my $item = $1;
4895: my $timersymb = $item;
4896: my $type = 'map';
4897: if ($item eq 'course') {
4898: $type = 'course';
4899: } elsif ($item =~ /___\d+___/) {
4900: $type = 'resource';
4901: } else {
4902: $timersymb = &Apache::lonnet::symbread($item);
4903: }
4904: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4905: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4906: if ($start && $end) {
4907: if (($start <= time) && ($end >= time)) {
4908: unless (grep(/^\Q$block\E$/,@blockers)) {
4909: push(@blockers,$block);
4910: $triggered{$block} = {
4911: start => $start,
4912: end => $end,
4913: type => $type,
4914: };
4915: }
4916: }
4917: }
4918: }
4919: }
4920: }
4921: foreach my $blocker (@blockers) {
4922: my ($staff_name,$staff_dom,$title,$blocks) =
4923: &parse_block_record($commblocks{$blocker});
4924: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4925: my ($start,$end,$triggertype);
4926: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4927: ($start,$end) = ($1,$2);
4928: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4929: $start = $triggered{$blocker}{'start'};
4930: $end = $triggered{$blocker}{'end'};
4931: $triggertype = $triggered{$blocker}{'type'};
4932: }
4933: if ($start) {
4934: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4935: if ($triggertype) {
4936: push(@{$$setters{$course}{'triggers'}},$triggertype);
4937: } else {
4938: push(@{$$setters{$course}{'triggers'}},0);
4939: }
4940: if ( ($startblock == 0) || ($startblock > $start) ) {
4941: $startblock = $start;
4942: if ($triggertype) {
4943: $triggerblock = $blocker;
4944: }
4945: }
4946: if ( ($endblock == 0) || ($endblock < $end) ) {
4947: $endblock = $end;
4948: if ($triggertype) {
4949: $triggerblock = $blocker;
4950: }
4951: }
4952: }
4953: }
4954: return ($startblock,$endblock,$triggerblock);
4955: }
4956:
4957: sub parse_block_record {
4958: my ($record) = @_;
4959: my ($setuname,$setudom,$title,$blocks);
4960: if (ref($record) eq 'HASH') {
4961: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4962: $title = &unescape($record->{'event'});
4963: $blocks = $record->{'blocks'};
4964: } else {
4965: my @data = split(/:/,$record,3);
4966: if (scalar(@data) eq 2) {
4967: $title = $data[1];
4968: ($setuname,$setudom) = split(/@/,$data[0]);
4969: } else {
4970: ($setuname,$setudom,$title) = @data;
4971: }
4972: $blocks = { 'com' => 'on' };
4973: }
4974: return ($setuname,$setudom,$title,$blocks);
4975: }
4976:
4977: sub blocking_status {
4978: my ($activity,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
4979: my %setters;
4980:
4981: # check for active blocking
4982: my ($startblock,$endblock,$triggerblock) =
4983: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course,$symb,$caller);
4984: my $blocked = 0;
4985: if ($startblock && $endblock) {
4986: $blocked = 1;
4987: }
4988:
4989: # caller just wants to know whether a block is active
4990: if (!wantarray) { return $blocked; }
4991:
4992: # build a link to a popup window containing the details
4993: my $querystring = "?activity=$activity";
4994: # $uname and $udom decide whose portfolio the user is trying to look at
4995: if (($activity eq 'port') || ($activity eq 'passwd')) {
4996: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
4997: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
4998: } elsif ($activity eq 'docs') {
4999: my $showurl = &Apache::lonenc::check_encrypt($url);
5000: $querystring .= '&url='.&HTML::Entities::encode($showurl,'\'&"<>');
5001: if ($symb) {
5002: my $showsymb = &Apache::lonenc::check_encrypt($symb);
5003: $querystring .= '&symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
5004: }
5005: }
5006:
5007: my $output .= <<'END_MYBLOCK';
5008: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5009: var options = "width=" + w + ",height=" + h + ",";
5010: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5011: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5012: var newWin = window.open(url, wdwName, options);
5013: newWin.focus();
5014: }
5015: END_MYBLOCK
5016:
5017: $output = Apache::lonhtmlcommon::scripttag($output);
5018:
5019: my $popupUrl = "/adm/blockingstatus/$querystring";
5020: my $text = &mt('Communication Blocked');
5021: my $class = 'LC_comblock';
5022: if ($activity eq 'docs') {
5023: $text = &mt('Content Access Blocked');
5024: $class = '';
5025: } elsif ($activity eq 'printout') {
5026: $text = &mt('Printing Blocked');
5027: } elsif ($activity eq 'passwd') {
5028: $text = &mt('Password Changing Blocked');
5029: } elsif ($activity eq 'grades') {
5030: $text = &mt('Gradebook Blocked');
5031: } elsif ($activity eq 'search') {
5032: $text = &mt('Search Blocked');
5033: } elsif ($activity eq 'alert') {
5034: $text = &mt('Checking Critical Messages Blocked');
5035: } elsif ($activity eq 'reinit') {
5036: $text = &mt('Checking Course Update Blocked');
5037: }
5038: $output .= <<"END_BLOCK";
5039: <div class='$class'>
5040: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5041: title='$text'>
5042: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5043: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5044: title='$text'>$text</a>
5045: </div>
5046:
5047: END_BLOCK
5048:
5049: return ($blocked, $output);
5050: }
5051:
5052: ###############################################
5053:
5054: sub check_ip_acc {
5055: my ($acc,$clientip)=@_;
5056: &Apache::lonxml::debug("acc is $acc");
5057: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5058: return 1;
5059: }
5060: my ($ip,$allowed);
5061: if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
5062: ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
5063: $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
5064: } else {
5065: $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
5066: }
5067:
5068: my $name;
5069: my %access = (
5070: allowfrom => 1,
5071: denyfrom => 0,
5072: );
5073: my @allows;
5074: my @denies;
5075: foreach my $item (split(',',$acc)) {
5076: $item =~ s/^\s*//;
5077: $item =~ s/\s*$//;
5078: if ($item =~ /^\!(.+)$/) {
5079: push(@denies,$1);
5080: } else {
5081: push(@allows,$item);
5082: }
5083: }
5084: my $numdenies = scalar(@denies);
5085: my $numallows = scalar(@allows);
5086: my $count = 0;
5087: foreach my $pattern (@denies,@allows) {
5088: $count ++;
5089: my $acctype = 'allowfrom';
5090: if ($count <= $numdenies) {
5091: $acctype = 'denyfrom';
5092: }
5093: if ($pattern =~ /\*$/) {
5094: #35.8.*
5095: $pattern=~s/\*//;
5096: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5097: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5098: #35.8.3.[34-56]
5099: my $low=$2;
5100: my $high=$3;
5101: $pattern=$1;
5102: if ($ip =~ /^\Q$pattern\E/) {
5103: my $last=(split(/\./,$ip))[3];
5104: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5105: }
5106: } elsif ($pattern =~ /^\*/) {
5107: #*.msu.edu
5108: $pattern=~s/\*//;
5109: if (!defined($name)) {
5110: use Socket;
5111: my $netaddr=inet_aton($ip);
5112: ($name)=gethostbyaddr($netaddr,AF_INET);
5113: }
5114: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5115: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5116: #127.0.0.1
5117: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5118: } else {
5119: #some.name.com
5120: if (!defined($name)) {
5121: use Socket;
5122: my $netaddr=inet_aton($ip);
5123: ($name)=gethostbyaddr($netaddr,AF_INET);
5124: }
5125: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5126: }
5127: if ($allowed =~ /^(0|1)$/) { last; }
5128: }
5129: if ($allowed eq '') {
5130: if ($numdenies && !$numallows) {
5131: $allowed = 1;
5132: } else {
5133: $allowed = 0;
5134: }
5135: }
5136: return $allowed;
5137: }
5138:
5139: ###############################################
5140:
5141: =pod
5142:
5143: =head1 Domain Template Functions
5144:
5145: =over 4
5146:
5147: =item * &determinedomain()
5148:
5149: Inputs: $domain (usually will be undef)
5150:
5151: Returns: Determines which domain should be used for designs
5152:
5153: =cut
5154:
5155: ###############################################
5156: sub determinedomain {
5157: my $domain=shift;
5158: if (! $domain) {
5159: # Determine domain if we have not been given one
5160: $domain = &Apache::lonnet::default_login_domain();
5161: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5162: if ($env{'request.role.domain'}) {
5163: $domain=$env{'request.role.domain'};
5164: }
5165: }
5166: return $domain;
5167: }
5168: ###############################################
5169:
5170: sub devalidate_domconfig_cache {
5171: my ($udom)=@_;
5172: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5173: }
5174:
5175: # ---------------------- Get domain configuration for a domain
5176: sub get_domainconf {
5177: my ($udom) = @_;
5178: my $cachetime=1800;
5179: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5180: if (defined($cached)) { return %{$result}; }
5181:
5182: my %domconfig = &Apache::lonnet::get_dom('configuration',
5183: ['login','rolecolors','autoenroll'],$udom);
5184: my (%designhash,%legacy);
5185: if (keys(%domconfig) > 0) {
5186: if (ref($domconfig{'login'}) eq 'HASH') {
5187: if (keys(%{$domconfig{'login'}})) {
5188: foreach my $key (keys(%{$domconfig{'login'}})) {
5189: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5190: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5191: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5192: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5193: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5194: if ($key eq 'loginvia') {
5195: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5196: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5197: $designhash{$udom.'.login.loginvia'} = $server;
5198: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5199: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5200: } else {
5201: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5202: }
5203: }
5204: } elsif ($key eq 'headtag') {
5205: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5206: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5207: }
5208: }
5209: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5210: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5211: }
5212: }
5213: }
5214: }
5215: } else {
5216: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5217: $designhash{$udom.'.login.'.$key.'_'.$img} =
5218: $domconfig{'login'}{$key}{$img};
5219: }
5220: }
5221: } else {
5222: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5223: }
5224: }
5225: } else {
5226: $legacy{'login'} = 1;
5227: }
5228: } else {
5229: $legacy{'login'} = 1;
5230: }
5231: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5232: if (keys(%{$domconfig{'rolecolors'}})) {
5233: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5234: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5235: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5236: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5237: }
5238: }
5239: }
5240: } else {
5241: $legacy{'rolecolors'} = 1;
5242: }
5243: } else {
5244: $legacy{'rolecolors'} = 1;
5245: }
5246: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5247: if ($domconfig{'autoenroll'}{'co-owners'}) {
5248: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5249: }
5250: }
5251: if (keys(%legacy) > 0) {
5252: my %legacyhash = &get_legacy_domconf($udom);
5253: foreach my $item (keys(%legacyhash)) {
5254: if ($item =~ /^\Q$udom\E\.login/) {
5255: if ($legacy{'login'}) {
5256: $designhash{$item} = $legacyhash{$item};
5257: }
5258: } else {
5259: if ($legacy{'rolecolors'}) {
5260: $designhash{$item} = $legacyhash{$item};
5261: }
5262: }
5263: }
5264: }
5265: } else {
5266: %designhash = &get_legacy_domconf($udom);
5267: }
5268: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5269: $cachetime);
5270: return %designhash;
5271: }
5272:
5273: sub get_legacy_domconf {
5274: my ($udom) = @_;
5275: my %legacyhash;
5276: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5277: my $designfile = $designdir.'/'.$udom.'.tab';
5278: if (-e $designfile) {
5279: if ( open (my $fh,'<',$designfile) ) {
5280: while (my $line = <$fh>) {
5281: next if ($line =~ /^\#/);
5282: chomp($line);
5283: my ($key,$val)=(split(/\=/,$line));
5284: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5285: }
5286: close($fh);
5287: }
5288: }
5289: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5290: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5291: }
5292: return %legacyhash;
5293: }
5294:
5295: =pod
5296:
5297: =item * &domainlogo()
5298:
5299: Inputs: $domain (usually will be undef)
5300:
5301: Returns: A link to a domain logo, if the domain logo exists.
5302: If the domain logo does not exist, a description of the domain.
5303:
5304: =cut
5305:
5306: ###############################################
5307: sub domainlogo {
5308: my $domain = &determinedomain(shift);
5309: my %designhash = &get_domainconf($domain);
5310: # See if there is a logo
5311: if ($designhash{$domain.'.login.domlogo'} ne '') {
5312: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5313: if ($imgsrc =~ m{^/(adm|res)/}) {
5314: if ($imgsrc =~ m{^/res/}) {
5315: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5316: &Apache::lonnet::repcopy($local_name);
5317: }
5318: $imgsrc = &lonhttpdurl($imgsrc);
5319: }
5320: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5321: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5322: return &Apache::lonnet::domain($domain,'description');
5323: } else {
5324: return '';
5325: }
5326: }
5327: ##############################################
5328:
5329: =pod
5330:
5331: =item * &designparm()
5332:
5333: Inputs: $which parameter; $domain (usually will be undef)
5334:
5335: Returns: value of designparamter $which
5336:
5337: =cut
5338:
5339:
5340: ##############################################
5341: sub designparm {
5342: my ($which,$domain)=@_;
5343: if (exists($env{'environment.color.'.$which})) {
5344: return $env{'environment.color.'.$which};
5345: }
5346: $domain=&determinedomain($domain);
5347: my %domdesign;
5348: unless ($domain eq 'public') {
5349: %domdesign = &get_domainconf($domain);
5350: }
5351: my $output;
5352: if ($domdesign{$domain.'.'.$which} ne '') {
5353: $output = $domdesign{$domain.'.'.$which};
5354: } else {
5355: $output = $defaultdesign{$which};
5356: }
5357: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5358: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5359: if ($output =~ m{^/(adm|res)/}) {
5360: if ($output =~ m{^/res/}) {
5361: my $local_name = &Apache::lonnet::filelocation('',$output);
5362: &Apache::lonnet::repcopy($local_name);
5363: }
5364: $output = &lonhttpdurl($output);
5365: }
5366: }
5367: return $output;
5368: }
5369:
5370: ##############################################
5371: =pod
5372:
5373: =item * &authorspace()
5374:
5375: Inputs: $url (usually will be undef).
5376:
5377: Returns: Path to Authoring Space containing the resource or
5378: directory being viewed (or for which action is being taken).
5379: If $url is provided, and begins /priv/<domain>/<uname>
5380: the path will be that portion of the $context argument.
5381: Otherwise the path will be for the author space of the current
5382: user when the current role is author, or for that of the
5383: co-author/assistant co-author space when the current role
5384: is co-author or assistant co-author.
5385:
5386: =cut
5387:
5388: sub authorspace {
5389: my ($url) = @_;
5390: if ($url ne '') {
5391: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5392: return $1;
5393: }
5394: }
5395: my $caname = '';
5396: my $cadom = '';
5397: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5398: ($cadom,$caname) =
5399: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5400: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5401: $caname = $env{'user.name'};
5402: $cadom = $env{'user.domain'};
5403: }
5404: if (($caname ne '') && ($cadom ne '')) {
5405: return "/priv/$cadom/$caname/";
5406: }
5407: return;
5408: }
5409:
5410: ##############################################
5411: =pod
5412:
5413: =item * &head_subbox()
5414:
5415: Inputs: $content (contains HTML code with page functions, etc.)
5416:
5417: Returns: HTML div with $content
5418: To be included in page header
5419:
5420: =cut
5421:
5422: sub head_subbox {
5423: my ($content)=@_;
5424: my $output =
5425: '<div class="LC_head_subbox">'
5426: .$content
5427: .'</div>'
5428: }
5429:
5430: ##############################################
5431: =pod
5432:
5433: =item * &CSTR_pageheader()
5434:
5435: Input: (optional) filename from which breadcrumb trail is built.
5436: In most cases no input as needed, as $env{'request.filename'}
5437: is appropriate for use in building the breadcrumb trail.
5438:
5439: Returns: HTML div with CSTR path and recent box
5440: To be included on Authoring Space pages
5441:
5442: =cut
5443:
5444: sub CSTR_pageheader {
5445: my ($trailfile) = @_;
5446: if ($trailfile eq '') {
5447: $trailfile = $env{'request.filename'};
5448: }
5449:
5450: # this is for resources; directories have customtitle, and crumbs
5451: # and select recent are created in lonpubdir.pm
5452:
5453: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5454: my ($udom,$uname,$thisdisfn)=
5455: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5456: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5457: $formaction =~ s{/+}{/}g;
5458:
5459: my $parentpath = '';
5460: my $lastitem = '';
5461: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5462: $parentpath = $1;
5463: $lastitem = $2;
5464: } else {
5465: $lastitem = $thisdisfn;
5466: }
5467:
5468: my $output =
5469: '<div>'
5470: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5471: .'<b>'.&mt('Authoring Space:').'</b> '
5472: .'<form name="dirs" method="post" action="'.$formaction
5473: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5474: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5475:
5476: if ($lastitem) {
5477: $output .=
5478: '<span class="LC_filename">'
5479: .$lastitem
5480: .'</span>';
5481: }
5482: $output .=
5483: '<br />'
5484: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5485: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5486: .'</form>'
5487: .&Apache::lonmenu::constspaceform()
5488: .'</div>';
5489:
5490: return $output;
5491: }
5492:
5493: ###############################################
5494: ###############################################
5495:
5496: =pod
5497:
5498: =back
5499:
5500: =head1 HTML Helpers
5501:
5502: =over 4
5503:
5504: =item * &bodytag()
5505:
5506: Returns a uniform header for LON-CAPA web pages.
5507:
5508: Inputs:
5509:
5510: =over 4
5511:
5512: =item * $title, A title to be displayed on the page.
5513:
5514: =item * $function, the current role (can be undef).
5515:
5516: =item * $addentries, extra parameters for the <body> tag.
5517:
5518: =item * $bodyonly, if defined, only return the <body> tag.
5519:
5520: =item * $domain, if defined, force a given domain.
5521:
5522: =item * $forcereg, if page should register as content page (relevant for
5523: text interface only)
5524:
5525: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5526: navigational links
5527:
5528: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5529:
5530: =item * $no_inline_link, if true and in remote mode, don't show the
5531: 'Switch To Inline Menu' link
5532:
5533: =item * $args, optional argument valid values are
5534: no_auto_mt_title -> prevents &mt()ing the title arg
5535: use_absolute -> for external resource or syllabus, this will
5536: contain https://<hostname> if server uses
5537: https (as per hosts.tab), but request is for http
5538: hostname -> hostname, from $r->hostname().
5539:
5540: =item * $advtoolsref, optional argument, ref to an array containing
5541: inlineremote items to be added in "Functions" menu below
5542: breadcrumbs.
5543:
5544: =back
5545:
5546: Returns: A uniform header for LON-CAPA web pages.
5547: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5548: If $bodyonly is undef or zero, an html string containing a <body> tag and
5549: other decorations will be returned.
5550:
5551: =cut
5552:
5553: sub bodytag {
5554: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5555: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
5556:
5557: my $public;
5558: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5559: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5560: $public = 1;
5561: }
5562: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5563: my $httphost = $args->{'use_absolute'};
5564: my $hostname = $args->{'hostname'};
5565:
5566: $function = &get_users_function() if (!$function);
5567: my $img = &designparm($function.'.img',$domain);
5568: my $font = &designparm($function.'.font',$domain);
5569: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5570:
5571: my %design = ( 'style' => 'margin-top: 0',
5572: 'bgcolor' => $pgbg,
5573: 'text' => $font,
5574: 'alink' => &designparm($function.'.alink',$domain),
5575: 'vlink' => &designparm($function.'.vlink',$domain),
5576: 'link' => &designparm($function.'.link',$domain),);
5577: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5578:
5579: # role and realm
5580: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5581: if ($realm) {
5582: $realm = '/'.$realm;
5583: }
5584: if ($role eq 'ca') {
5585: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5586: $realm = &plainname($rname,$rdom);
5587: }
5588: # realm
5589: if ($env{'request.course.id'}) {
5590: if ($env{'request.role'} !~ /^cr/) {
5591: $role = &Apache::lonnet::plaintext($role,&course_type());
5592: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
5593: if ($env{'request.role.desc'}) {
5594: $role = $env{'request.role.desc'};
5595: } else {
5596: $role = &mt('Helpdesk[_1]',' '.$2);
5597: }
5598: } else {
5599: $role = (split(/\//,$role,4))[-1];
5600: }
5601: if ($env{'request.course.sec'}) {
5602: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5603: }
5604: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5605: } else {
5606: $role = &Apache::lonnet::plaintext($role);
5607: }
5608:
5609: if (!$realm) { $realm=' '; }
5610:
5611: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5612:
5613: # construct main body tag
5614: my $bodytag = "<body $extra_body_attr>".
5615: &Apache::lontexconvert::init_math_support();
5616:
5617: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5618:
5619: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5620: return $bodytag;
5621: }
5622:
5623: if ($public) {
5624: undef($role);
5625: }
5626:
5627: my $titleinfo = '<h1>'.$title.'</h1>';
5628: #
5629: # Extra info if you are the DC
5630: my $dc_info = '';
5631: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5632: $env{'course.'.$env{'request.course.id'}.
5633: '.domain'}.'/'})) {
5634: my $cid = $env{'request.course.id'};
5635: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5636: $dc_info =~ s/\s+$//;
5637: }
5638:
5639: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
5640:
5641: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5642:
5643:
5644:
5645: my $funclist;
5646: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
5647: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
5648: Apache::lonmenu::serverform();
5649: my $forbodytag;
5650: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5651: $forcereg,$args->{'group'},
5652: $args->{'bread_crumbs'},
5653: $advtoolsref,'','',\$forbodytag);
5654: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5655: $funclist = $forbodytag;
5656: }
5657: } else {
5658:
5659: # if ($env{'request.state'} eq 'construct') {
5660: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5661: # }
5662:
5663: $bodytag .= Apache::lonhtmlcommon::scripttag(
5664: Apache::lonmenu::utilityfunctions($httphost), 'start');
5665:
5666: my ($left,$right) = Apache::lonmenu::primary_menu();
5667:
5668: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5669: if ($dc_info) {
5670: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5671: }
5672: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5673: <em>$realm</em> $dc_info</div>|;
5674: return $bodytag;
5675: }
5676:
5677: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5678: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5679: }
5680:
5681: $bodytag .= $right;
5682:
5683: if ($dc_info) {
5684: $dc_info = &dc_courseid_toggle($dc_info);
5685: }
5686: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5687:
5688: #if directed to not display the secondary menu, don't.
5689: if ($args->{'no_secondary_menu'}) {
5690: return $bodytag;
5691: }
5692: #don't show menus for public users
5693: if (!$public){
5694: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5695: $bodytag .= Apache::lonmenu::serverform();
5696: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5697: if ($env{'request.state'} eq 'construct') {
5698: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5699: $args->{'bread_crumbs'},'','',$hostname);
5700: } elsif ($forcereg) {
5701: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5702: $args->{'group'},
5703: $args->{'hide_buttons',
5704: $hostname});
5705: } else {
5706: my $forbodytag;
5707: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5708: $forcereg,$args->{'group'},
5709: $args->{'bread_crumbs'},
5710: $advtoolsref,'',$hostname,
5711: \$forbodytag);
5712: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5713: $bodytag .= $forbodytag;
5714: }
5715: }
5716: }else{
5717: # this is to seperate menu from content when there's no secondary
5718: # menu. Especially needed for public accessible ressources.
5719: $bodytag .= '<hr style="clear:both" />';
5720: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5721: }
5722:
5723: return $bodytag;
5724: }
5725:
5726: #
5727: # Top frame rendering, Remote is up
5728: #
5729:
5730: my $imgsrc = $img;
5731: if ($img =~ /^\/adm/) {
5732: $imgsrc = &lonhttpdurl($img);
5733: }
5734: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
5735:
5736: my $help=($no_inline_link?''
5737: :&Apache::loncommon::top_nav_help('Help'));
5738:
5739: # Explicit link to get inline menu
5740: my $menu= ($no_inline_link?''
5741: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
5742:
5743: if ($dc_info) {
5744: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
5745: }
5746:
5747: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5748: unless ($public) {
5749: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5750: undef,'LC_menubuttons_link');
5751: }
5752:
5753: unless ($env{'form.inhibitmenu'}) {
5754: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
5755: <ol class="LC_primary_menu LC_floatright LC_right">
5756: <li>$help</li>
5757: <li>$menu</li>
5758: </ol><div id="LC_realm"> $realm $dc_info</div>|;
5759: }
5760: if ($env{'request.state'} eq 'construct') {
5761: if (!$public){
5762: if ($env{'request.state'} eq 'construct') {
5763: $funclist = &Apache::lonhtmlcommon::scripttag(
5764: &Apache::lonmenu::utilityfunctions($httphost), 'start').
5765: &Apache::lonhtmlcommon::scripttag('','end').
5766: &Apache::lonmenu::innerregister($forcereg,
5767: $args->{'bread_crumbs'});
5768: }
5769: }
5770: }
5771: return $bodytag."\n".$funclist;
5772: }
5773:
5774: sub dc_courseid_toggle {
5775: my ($dc_info) = @_;
5776: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5777: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5778: &mt('(More ...)').'</a></span>'.
5779: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5780: }
5781:
5782: sub make_attr_string {
5783: my ($register,$attr_ref) = @_;
5784:
5785: if ($attr_ref && !ref($attr_ref)) {
5786: die("addentries Must be a hash ref ".
5787: join(':',caller(1))." ".
5788: join(':',caller(0))." ");
5789: }
5790:
5791: if ($register) {
5792: my ($on_load,$on_unload);
5793: foreach my $key (keys(%{$attr_ref})) {
5794: if (lc($key) eq 'onload') {
5795: $on_load.=$attr_ref->{$key}.';';
5796: delete($attr_ref->{$key});
5797:
5798: } elsif (lc($key) eq 'onunload') {
5799: $on_unload.=$attr_ref->{$key}.';';
5800: delete($attr_ref->{$key});
5801: }
5802: }
5803: if ($env{'environment.remote'} eq 'on') {
5804: $attr_ref->{'onload'} =
5805: &Apache::lonmenu::loadevents(). $on_load;
5806: $attr_ref->{'onunload'}=
5807: &Apache::lonmenu::unloadevents().$on_unload;
5808: } else {
5809: $attr_ref->{'onload'} = $on_load;
5810: $attr_ref->{'onunload'}= $on_unload;
5811: }
5812: }
5813:
5814: my $attr_string;
5815: foreach my $attr (sort(keys(%$attr_ref))) {
5816: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5817: }
5818: return $attr_string;
5819: }
5820:
5821:
5822: ###############################################
5823: ###############################################
5824:
5825: =pod
5826:
5827: =item * &endbodytag()
5828:
5829: Returns a uniform footer for LON-CAPA web pages.
5830:
5831: Inputs: 1 - optional reference to an args hash
5832: If in the hash, key for noredirectlink has a value which evaluates to true,
5833: a 'Continue' link is not displayed if the page contains an
5834: internal redirect in the <head></head> section,
5835: i.e., $env{'internal.head.redirect'} exists
5836:
5837: =cut
5838:
5839: sub endbodytag {
5840: my ($args) = @_;
5841: my $endbodytag;
5842: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5843: $endbodytag='</body>';
5844: }
5845: if ( exists( $env{'internal.head.redirect'} ) ) {
5846: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5847: $endbodytag=
5848: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5849: &mt('Continue').'</a>'.
5850: $endbodytag;
5851: }
5852: }
5853: return $endbodytag;
5854: }
5855:
5856: =pod
5857:
5858: =item * &standard_css()
5859:
5860: Returns a style sheet
5861:
5862: Inputs: (all optional)
5863: domain -> force to color decorate a page for a specific
5864: domain
5865: function -> force usage of a specific rolish color scheme
5866: bgcolor -> override the default page bgcolor
5867:
5868: =cut
5869:
5870: sub standard_css {
5871: my ($function,$domain,$bgcolor) = @_;
5872: $function = &get_users_function() if (!$function);
5873: my $img = &designparm($function.'.img', $domain);
5874: my $tabbg = &designparm($function.'.tabbg', $domain);
5875: my $font = &designparm($function.'.font', $domain);
5876: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5877: #second colour for later usage
5878: my $sidebg = &designparm($function.'.sidebg',$domain);
5879: my $pgbg_or_bgcolor =
5880: $bgcolor ||
5881: &designparm($function.'.pgbg', $domain);
5882: my $pgbg = &designparm($function.'.pgbg', $domain);
5883: my $alink = &designparm($function.'.alink', $domain);
5884: my $vlink = &designparm($function.'.vlink', $domain);
5885: my $link = &designparm($function.'.link', $domain);
5886:
5887: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5888: my $mono = 'monospace';
5889: my $data_table_head = $sidebg;
5890: my $data_table_light = '#FAFAFA';
5891: my $data_table_dark = '#E0E0E0';
5892: my $data_table_darker = '#CCCCCC';
5893: my $data_table_highlight = '#FFFF00';
5894: my $mail_new = '#FFBB77';
5895: my $mail_new_hover = '#DD9955';
5896: my $mail_read = '#BBBB77';
5897: my $mail_read_hover = '#999944';
5898: my $mail_replied = '#AAAA88';
5899: my $mail_replied_hover = '#888855';
5900: my $mail_other = '#99BBBB';
5901: my $mail_other_hover = '#669999';
5902: my $table_header = '#DDDDDD';
5903: my $feedback_link_bg = '#BBBBBB';
5904: my $lg_border_color = '#C8C8C8';
5905: my $button_hover = '#BF2317';
5906:
5907: my $border = ($env{'browser.type'} eq 'explorer' ||
5908: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5909: : '0 3px 0 4px';
5910:
5911:
5912: return <<END;
5913:
5914: /* needed for iframe to allow 100% height in FF */
5915: body, html {
5916: margin: 0;
5917: padding: 0 0.5%;
5918: height: 99%; /* to avoid scrollbars */
5919: }
5920:
5921: body {
5922: font-family: $sans;
5923: line-height:130%;
5924: font-size:0.83em;
5925: color:$font;
5926: }
5927:
5928: a:focus,
5929: a:focus img {
5930: color: red;
5931: }
5932:
5933: form, .inline {
5934: display: inline;
5935: }
5936:
5937: .LC_right {
5938: text-align:right;
5939: }
5940:
5941: .LC_middle {
5942: vertical-align:middle;
5943: }
5944:
5945: .LC_floatleft {
5946: float: left;
5947: }
5948:
5949: .LC_floatright {
5950: float: right;
5951: }
5952:
5953: .LC_400Box {
5954: width:400px;
5955: }
5956:
5957: .LC_iframecontainer {
5958: width: 98%;
5959: margin: 0;
5960: position: fixed;
5961: top: 8.5em;
5962: bottom: 0;
5963: }
5964:
5965: .LC_iframecontainer iframe{
5966: border: none;
5967: width: 100%;
5968: height: 100%;
5969: }
5970:
5971: .LC_filename {
5972: font-family: $mono;
5973: white-space:pre;
5974: font-size: 120%;
5975: }
5976:
5977: .LC_fileicon {
5978: border: none;
5979: height: 1.3em;
5980: vertical-align: text-bottom;
5981: margin-right: 0.3em;
5982: text-decoration:none;
5983: }
5984:
5985: .LC_setting {
5986: text-decoration:underline;
5987: }
5988:
5989: .LC_error {
5990: color: red;
5991: }
5992:
5993: .LC_warning {
5994: color: darkorange;
5995: }
5996:
5997: .LC_diff_removed {
5998: color: red;
5999: }
6000:
6001: .LC_info,
6002: .LC_success,
6003: .LC_diff_added {
6004: color: green;
6005: }
6006:
6007: div.LC_confirm_box {
6008: background-color: #FAFAFA;
6009: border: 1px solid $lg_border_color;
6010: margin-right: 0;
6011: padding: 5px;
6012: }
6013:
6014: div.LC_confirm_box .LC_error img,
6015: div.LC_confirm_box .LC_success img {
6016: vertical-align: middle;
6017: }
6018:
6019: .LC_maxwidth {
6020: max-width: 100%;
6021: height: auto;
6022: }
6023:
6024: .LC_textsize_mobile {
6025: \@media only screen and (max-device-width: 480px) {
6026: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
6027: }
6028: }
6029:
6030: .LC_icon {
6031: border: none;
6032: vertical-align: middle;
6033: }
6034:
6035: .LC_docs_spacer {
6036: width: 25px;
6037: height: 1px;
6038: border: none;
6039: }
6040:
6041: .LC_internal_info {
6042: color: #999999;
6043: }
6044:
6045: .LC_discussion {
6046: background: $data_table_dark;
6047: border: 1px solid black;
6048: margin: 2px;
6049: }
6050:
6051: .LC_disc_action_left {
6052: background: $sidebg;
6053: text-align: left;
6054: padding: 4px;
6055: margin: 2px;
6056: }
6057:
6058: .LC_disc_action_right {
6059: background: $sidebg;
6060: text-align: right;
6061: padding: 4px;
6062: margin: 2px;
6063: }
6064:
6065: .LC_disc_new_item {
6066: background: white;
6067: border: 2px solid red;
6068: margin: 4px;
6069: padding: 4px;
6070: }
6071:
6072: .LC_disc_old_item {
6073: background: white;
6074: margin: 4px;
6075: padding: 4px;
6076: }
6077:
6078: table.LC_pastsubmission {
6079: border: 1px solid black;
6080: margin: 2px;
6081: }
6082:
6083: table#LC_menubuttons {
6084: width: 100%;
6085: background: $pgbg;
6086: border: 2px;
6087: border-collapse: separate;
6088: padding: 0;
6089: }
6090:
6091: table#LC_title_bar a {
6092: color: $fontmenu;
6093: }
6094:
6095: table#LC_title_bar {
6096: clear: both;
6097: display: none;
6098: }
6099:
6100: table#LC_title_bar,
6101: table.LC_breadcrumbs, /* obsolete? */
6102: table#LC_title_bar.LC_with_remote {
6103: width: 100%;
6104: border-color: $pgbg;
6105: border-style: solid;
6106: border-width: $border;
6107: background: $pgbg;
6108: color: $fontmenu;
6109: border-collapse: collapse;
6110: padding: 0;
6111: margin: 0;
6112: }
6113:
6114: ul.LC_breadcrumb_tools_outerlist {
6115: margin: 0;
6116: padding: 0;
6117: position: relative;
6118: list-style: none;
6119: }
6120: ul.LC_breadcrumb_tools_outerlist li {
6121: display: inline;
6122: }
6123:
6124: .LC_breadcrumb_tools_navigation {
6125: padding: 0;
6126: margin: 0;
6127: float: left;
6128: }
6129: .LC_breadcrumb_tools_tools {
6130: padding: 0;
6131: margin: 0;
6132: float: right;
6133: }
6134:
6135: table#LC_title_bar td {
6136: background: $tabbg;
6137: }
6138:
6139: table#LC_menubuttons img {
6140: border: none;
6141: }
6142:
6143: .LC_breadcrumbs_component {
6144: float: right;
6145: margin: 0 1em;
6146: }
6147: .LC_breadcrumbs_component img {
6148: vertical-align: middle;
6149: }
6150:
6151: .LC_breadcrumbs_hoverable {
6152: background: $sidebg;
6153: }
6154:
6155: td.LC_table_cell_checkbox {
6156: text-align: center;
6157: }
6158:
6159: .LC_fontsize_small {
6160: font-size: 70%;
6161: }
6162:
6163: #LC_breadcrumbs {
6164: clear:both;
6165: background: $sidebg;
6166: border-bottom: 1px solid $lg_border_color;
6167: line-height: 2.5em;
6168: overflow: hidden;
6169: margin: 0;
6170: padding: 0;
6171: text-align: left;
6172: }
6173:
6174: .LC_head_subbox, .LC_actionbox {
6175: clear:both;
6176: background: #F8F8F8; /* $sidebg; */
6177: border: 1px solid $sidebg;
6178: margin: 0 0 10px 0;
6179: padding: 3px;
6180: text-align: left;
6181: }
6182:
6183: .LC_fontsize_medium {
6184: font-size: 85%;
6185: }
6186:
6187: .LC_fontsize_large {
6188: font-size: 120%;
6189: }
6190:
6191: .LC_menubuttons_inline_text {
6192: color: $font;
6193: font-size: 90%;
6194: padding-left:3px;
6195: }
6196:
6197: .LC_menubuttons_inline_text img{
6198: vertical-align: middle;
6199: }
6200:
6201: li.LC_menubuttons_inline_text img {
6202: cursor:pointer;
6203: text-decoration: none;
6204: }
6205:
6206: .LC_menubuttons_link {
6207: text-decoration: none;
6208: }
6209:
6210: .LC_menubuttons_category {
6211: color: $font;
6212: background: $pgbg;
6213: font-size: larger;
6214: font-weight: bold;
6215: }
6216:
6217: td.LC_menubuttons_text {
6218: color: $font;
6219: }
6220:
6221: .LC_current_location {
6222: background: $tabbg;
6223: }
6224:
6225: td.LC_zero_height {
6226: line-height: 0;
6227: cellpadding: 0;
6228: }
6229:
6230: table.LC_data_table {
6231: border: 1px solid #000000;
6232: border-collapse: separate;
6233: border-spacing: 1px;
6234: background: $pgbg;
6235: }
6236:
6237: .LC_data_table_dense {
6238: font-size: small;
6239: }
6240:
6241: table.LC_nested_outer {
6242: border: 1px solid #000000;
6243: border-collapse: collapse;
6244: border-spacing: 0;
6245: width: 100%;
6246: }
6247:
6248: table.LC_innerpickbox,
6249: table.LC_nested {
6250: border: none;
6251: border-collapse: collapse;
6252: border-spacing: 0;
6253: width: 100%;
6254: }
6255:
6256: table.LC_data_table tr th,
6257: table.LC_calendar tr th,
6258: table.LC_prior_tries tr th,
6259: table.LC_innerpickbox tr th {
6260: font-weight: bold;
6261: background-color: $data_table_head;
6262: color:$fontmenu;
6263: font-size:90%;
6264: }
6265:
6266: table.LC_innerpickbox tr th,
6267: table.LC_innerpickbox tr td {
6268: vertical-align: top;
6269: }
6270:
6271: table.LC_data_table tr.LC_info_row > td {
6272: background-color: #CCCCCC;
6273: font-weight: bold;
6274: text-align: left;
6275: }
6276:
6277: table.LC_data_table tr.LC_odd_row > td {
6278: background-color: $data_table_light;
6279: padding: 2px;
6280: vertical-align: top;
6281: }
6282:
6283: table.LC_pick_box tr > td.LC_odd_row {
6284: background-color: $data_table_light;
6285: vertical-align: top;
6286: }
6287:
6288: table.LC_data_table tr.LC_even_row > td {
6289: background-color: $data_table_dark;
6290: padding: 2px;
6291: vertical-align: top;
6292: }
6293:
6294: table.LC_pick_box tr > td.LC_even_row {
6295: background-color: $data_table_dark;
6296: vertical-align: top;
6297: }
6298:
6299: table.LC_data_table tr.LC_data_table_highlight td {
6300: background-color: $data_table_darker;
6301: }
6302:
6303: table.LC_data_table tr td.LC_leftcol_header {
6304: background-color: $data_table_head;
6305: font-weight: bold;
6306: }
6307:
6308: table.LC_data_table tr.LC_empty_row td,
6309: table.LC_nested tr.LC_empty_row td {
6310: font-weight: bold;
6311: font-style: italic;
6312: text-align: center;
6313: padding: 8px;
6314: }
6315:
6316: table.LC_data_table tr.LC_empty_row td,
6317: table.LC_data_table tr.LC_footer_row td {
6318: background-color: $sidebg;
6319: }
6320:
6321: table.LC_nested tr.LC_empty_row td {
6322: background-color: #FFFFFF;
6323: }
6324:
6325: table.LC_caption {
6326: }
6327:
6328: table.LC_nested tr.LC_empty_row td {
6329: padding: 4ex
6330: }
6331:
6332: table.LC_nested_outer tr th {
6333: font-weight: bold;
6334: color:$fontmenu;
6335: background-color: $data_table_head;
6336: font-size: small;
6337: border-bottom: 1px solid #000000;
6338: }
6339:
6340: table.LC_nested_outer tr td.LC_subheader {
6341: background-color: $data_table_head;
6342: font-weight: bold;
6343: font-size: small;
6344: border-bottom: 1px solid #000000;
6345: text-align: right;
6346: }
6347:
6348: table.LC_nested tr.LC_info_row td {
6349: background-color: #CCCCCC;
6350: font-weight: bold;
6351: font-size: small;
6352: text-align: center;
6353: }
6354:
6355: table.LC_nested tr.LC_info_row td.LC_left_item,
6356: table.LC_nested_outer tr th.LC_left_item {
6357: text-align: left;
6358: }
6359:
6360: table.LC_nested td {
6361: background-color: #FFFFFF;
6362: font-size: small;
6363: }
6364:
6365: table.LC_nested_outer tr th.LC_right_item,
6366: table.LC_nested tr.LC_info_row td.LC_right_item,
6367: table.LC_nested tr.LC_odd_row td.LC_right_item,
6368: table.LC_nested tr td.LC_right_item {
6369: text-align: right;
6370: }
6371:
6372: table.LC_nested tr.LC_odd_row td {
6373: background-color: #EEEEEE;
6374: }
6375:
6376: table.LC_createuser {
6377: }
6378:
6379: table.LC_createuser tr.LC_section_row td {
6380: font-size: small;
6381: }
6382:
6383: table.LC_createuser tr.LC_info_row td {
6384: background-color: #CCCCCC;
6385: font-weight: bold;
6386: text-align: center;
6387: }
6388:
6389: table.LC_calendar {
6390: border: 1px solid #000000;
6391: border-collapse: collapse;
6392: width: 98%;
6393: }
6394:
6395: table.LC_calendar_pickdate {
6396: font-size: xx-small;
6397: }
6398:
6399: table.LC_calendar tr td {
6400: border: 1px solid #000000;
6401: vertical-align: top;
6402: width: 14%;
6403: }
6404:
6405: table.LC_calendar tr td.LC_calendar_day_empty {
6406: background-color: $data_table_dark;
6407: }
6408:
6409: table.LC_calendar tr td.LC_calendar_day_current {
6410: background-color: $data_table_highlight;
6411: }
6412:
6413: table.LC_data_table tr td.LC_mail_new {
6414: background-color: $mail_new;
6415: }
6416:
6417: table.LC_data_table tr.LC_mail_new:hover {
6418: background-color: $mail_new_hover;
6419: }
6420:
6421: table.LC_data_table tr td.LC_mail_read {
6422: background-color: $mail_read;
6423: }
6424:
6425: /*
6426: table.LC_data_table tr.LC_mail_read:hover {
6427: background-color: $mail_read_hover;
6428: }
6429: */
6430:
6431: table.LC_data_table tr td.LC_mail_replied {
6432: background-color: $mail_replied;
6433: }
6434:
6435: /*
6436: table.LC_data_table tr.LC_mail_replied:hover {
6437: background-color: $mail_replied_hover;
6438: }
6439: */
6440:
6441: table.LC_data_table tr td.LC_mail_other {
6442: background-color: $mail_other;
6443: }
6444:
6445: /*
6446: table.LC_data_table tr.LC_mail_other:hover {
6447: background-color: $mail_other_hover;
6448: }
6449: */
6450:
6451: table.LC_data_table tr > td.LC_browser_file,
6452: table.LC_data_table tr > td.LC_browser_file_published {
6453: background: #AAEE77;
6454: }
6455:
6456: table.LC_data_table tr > td.LC_browser_file_locked,
6457: table.LC_data_table tr > td.LC_browser_file_unpublished {
6458: background: #FFAA99;
6459: }
6460:
6461: table.LC_data_table tr > td.LC_browser_file_obsolete {
6462: background: #888888;
6463: }
6464:
6465: table.LC_data_table tr > td.LC_browser_file_modified,
6466: table.LC_data_table tr > td.LC_browser_file_metamodified {
6467: background: #F8F866;
6468: }
6469:
6470: table.LC_data_table tr.LC_browser_folder > td {
6471: background: #E0E8FF;
6472: }
6473:
6474: table.LC_data_table tr > td.LC_roles_is {
6475: /* background: #77FF77; */
6476: }
6477:
6478: table.LC_data_table tr > td.LC_roles_future {
6479: border-right: 8px solid #FFFF77;
6480: }
6481:
6482: table.LC_data_table tr > td.LC_roles_will {
6483: border-right: 8px solid #FFAA77;
6484: }
6485:
6486: table.LC_data_table tr > td.LC_roles_expired {
6487: border-right: 8px solid #FF7777;
6488: }
6489:
6490: table.LC_data_table tr > td.LC_roles_will_not {
6491: border-right: 8px solid #AAFF77;
6492: }
6493:
6494: table.LC_data_table tr > td.LC_roles_selected {
6495: border-right: 8px solid #11CC55;
6496: }
6497:
6498: span.LC_current_location {
6499: font-size:larger;
6500: background: $pgbg;
6501: }
6502:
6503: span.LC_current_nav_location {
6504: font-weight:bold;
6505: background: $sidebg;
6506: }
6507:
6508: span.LC_parm_menu_item {
6509: font-size: larger;
6510: }
6511:
6512: span.LC_parm_scope_all {
6513: color: red;
6514: }
6515:
6516: span.LC_parm_scope_folder {
6517: color: green;
6518: }
6519:
6520: span.LC_parm_scope_resource {
6521: color: orange;
6522: }
6523:
6524: span.LC_parm_part {
6525: color: blue;
6526: }
6527:
6528: span.LC_parm_folder,
6529: span.LC_parm_symb {
6530: font-size: x-small;
6531: font-family: $mono;
6532: color: #AAAAAA;
6533: }
6534:
6535: ul.LC_parm_parmlist li {
6536: display: inline-block;
6537: padding: 0.3em 0.8em;
6538: vertical-align: top;
6539: width: 150px;
6540: border-top:1px solid $lg_border_color;
6541: }
6542:
6543: td.LC_parm_overview_level_menu,
6544: td.LC_parm_overview_map_menu,
6545: td.LC_parm_overview_parm_selectors,
6546: td.LC_parm_overview_restrictions {
6547: border: 1px solid black;
6548: border-collapse: collapse;
6549: }
6550:
6551: table.LC_parm_overview_restrictions td {
6552: border-width: 1px 4px 1px 4px;
6553: border-style: solid;
6554: border-color: $pgbg;
6555: text-align: center;
6556: }
6557:
6558: table.LC_parm_overview_restrictions th {
6559: background: $tabbg;
6560: border-width: 1px 4px 1px 4px;
6561: border-style: solid;
6562: border-color: $pgbg;
6563: }
6564:
6565: table#LC_helpmenu {
6566: border: none;
6567: height: 55px;
6568: border-spacing: 0;
6569: }
6570:
6571: table#LC_helpmenu fieldset legend {
6572: font-size: larger;
6573: }
6574:
6575: table#LC_helpmenu_links {
6576: width: 100%;
6577: border: 1px solid black;
6578: background: $pgbg;
6579: padding: 0;
6580: border-spacing: 1px;
6581: }
6582:
6583: table#LC_helpmenu_links tr td {
6584: padding: 1px;
6585: background: $tabbg;
6586: text-align: center;
6587: font-weight: bold;
6588: }
6589:
6590: table#LC_helpmenu_links a:link,
6591: table#LC_helpmenu_links a:visited,
6592: table#LC_helpmenu_links a:active {
6593: text-decoration: none;
6594: color: $font;
6595: }
6596:
6597: table#LC_helpmenu_links a:hover {
6598: text-decoration: underline;
6599: color: $vlink;
6600: }
6601:
6602: .LC_chrt_popup_exists {
6603: border: 1px solid #339933;
6604: margin: -1px;
6605: }
6606:
6607: .LC_chrt_popup_up {
6608: border: 1px solid yellow;
6609: margin: -1px;
6610: }
6611:
6612: .LC_chrt_popup {
6613: border: 1px solid #8888FF;
6614: background: #CCCCFF;
6615: }
6616:
6617: table.LC_pick_box {
6618: border-collapse: separate;
6619: background: white;
6620: border: 1px solid black;
6621: border-spacing: 1px;
6622: }
6623:
6624: table.LC_pick_box td.LC_pick_box_title {
6625: background: $sidebg;
6626: font-weight: bold;
6627: text-align: left;
6628: vertical-align: top;
6629: width: 184px;
6630: padding: 8px;
6631: }
6632:
6633: table.LC_pick_box td.LC_pick_box_value {
6634: text-align: left;
6635: padding: 8px;
6636: }
6637:
6638: table.LC_pick_box td.LC_pick_box_select {
6639: text-align: left;
6640: padding: 8px;
6641: }
6642:
6643: table.LC_pick_box td.LC_pick_box_separator {
6644: padding: 0;
6645: height: 1px;
6646: background: black;
6647: }
6648:
6649: table.LC_pick_box td.LC_pick_box_submit {
6650: text-align: right;
6651: }
6652:
6653: table.LC_pick_box td.LC_evenrow_value {
6654: text-align: left;
6655: padding: 8px;
6656: background-color: $data_table_light;
6657: }
6658:
6659: table.LC_pick_box td.LC_oddrow_value {
6660: text-align: left;
6661: padding: 8px;
6662: background-color: $data_table_light;
6663: }
6664:
6665: span.LC_helpform_receipt_cat {
6666: font-weight: bold;
6667: }
6668:
6669: table.LC_group_priv_box {
6670: background: white;
6671: border: 1px solid black;
6672: border-spacing: 1px;
6673: }
6674:
6675: table.LC_group_priv_box td.LC_pick_box_title {
6676: background: $tabbg;
6677: font-weight: bold;
6678: text-align: right;
6679: width: 184px;
6680: }
6681:
6682: table.LC_group_priv_box td.LC_groups_fixed {
6683: background: $data_table_light;
6684: text-align: center;
6685: }
6686:
6687: table.LC_group_priv_box td.LC_groups_optional {
6688: background: $data_table_dark;
6689: text-align: center;
6690: }
6691:
6692: table.LC_group_priv_box td.LC_groups_functionality {
6693: background: $data_table_darker;
6694: text-align: center;
6695: font-weight: bold;
6696: }
6697:
6698: table.LC_group_priv td {
6699: text-align: left;
6700: padding: 0;
6701: }
6702:
6703: .LC_navbuttons {
6704: margin: 2ex 0ex 2ex 0ex;
6705: }
6706:
6707: .LC_topic_bar {
6708: font-weight: bold;
6709: background: $tabbg;
6710: margin: 1em 0em 1em 2em;
6711: padding: 3px;
6712: font-size: 1.2em;
6713: }
6714:
6715: .LC_topic_bar span {
6716: left: 0.5em;
6717: position: absolute;
6718: vertical-align: middle;
6719: font-size: 1.2em;
6720: }
6721:
6722: table.LC_course_group_status {
6723: margin: 20px;
6724: }
6725:
6726: table.LC_status_selector td {
6727: vertical-align: top;
6728: text-align: center;
6729: padding: 4px;
6730: }
6731:
6732: div.LC_feedback_link {
6733: clear: both;
6734: background: $sidebg;
6735: width: 100%;
6736: padding-bottom: 10px;
6737: border: 1px $tabbg solid;
6738: height: 22px;
6739: line-height: 22px;
6740: padding-top: 5px;
6741: }
6742:
6743: div.LC_feedback_link img {
6744: height: 22px;
6745: vertical-align:middle;
6746: }
6747:
6748: div.LC_feedback_link a {
6749: text-decoration: none;
6750: }
6751:
6752: div.LC_comblock {
6753: display:inline;
6754: color:$font;
6755: font-size:90%;
6756: }
6757:
6758: div.LC_feedback_link div.LC_comblock {
6759: padding-left:5px;
6760: }
6761:
6762: div.LC_feedback_link div.LC_comblock a {
6763: color:$font;
6764: }
6765:
6766: span.LC_feedback_link {
6767: /* background: $feedback_link_bg; */
6768: font-size: larger;
6769: }
6770:
6771: span.LC_message_link {
6772: /* background: $feedback_link_bg; */
6773: font-size: larger;
6774: position: absolute;
6775: right: 1em;
6776: }
6777:
6778: table.LC_prior_tries {
6779: border: 1px solid #000000;
6780: border-collapse: separate;
6781: border-spacing: 1px;
6782: }
6783:
6784: table.LC_prior_tries td {
6785: padding: 2px;
6786: }
6787:
6788: .LC_answer_correct {
6789: background: lightgreen;
6790: color: darkgreen;
6791: padding: 6px;
6792: }
6793:
6794: .LC_answer_charged_try {
6795: background: #FFAAAA;
6796: color: darkred;
6797: padding: 6px;
6798: }
6799:
6800: .LC_answer_not_charged_try,
6801: .LC_answer_no_grade,
6802: .LC_answer_late {
6803: background: lightyellow;
6804: color: black;
6805: padding: 6px;
6806: }
6807:
6808: .LC_answer_previous {
6809: background: lightblue;
6810: color: darkblue;
6811: padding: 6px;
6812: }
6813:
6814: .LC_answer_no_message {
6815: background: #FFFFFF;
6816: color: black;
6817: padding: 6px;
6818: }
6819:
6820: .LC_answer_unknown,
6821: .LC_answer_warning {
6822: background: orange;
6823: color: black;
6824: padding: 6px;
6825: }
6826:
6827: span.LC_prior_numerical,
6828: span.LC_prior_string,
6829: span.LC_prior_custom,
6830: span.LC_prior_reaction,
6831: span.LC_prior_math {
6832: font-family: $mono;
6833: white-space: pre;
6834: }
6835:
6836: span.LC_prior_string {
6837: font-family: $mono;
6838: white-space: pre;
6839: }
6840:
6841: table.LC_prior_option {
6842: width: 100%;
6843: border-collapse: collapse;
6844: }
6845:
6846: table.LC_prior_rank,
6847: table.LC_prior_match {
6848: border-collapse: collapse;
6849: }
6850:
6851: table.LC_prior_option tr td,
6852: table.LC_prior_rank tr td,
6853: table.LC_prior_match tr td {
6854: border: 1px solid #000000;
6855: }
6856:
6857: .LC_nobreak {
6858: white-space: nowrap;
6859: }
6860:
6861: span.LC_cusr_emph {
6862: font-style: italic;
6863: }
6864:
6865: span.LC_cusr_subheading {
6866: font-weight: normal;
6867: font-size: 85%;
6868: }
6869:
6870: div.LC_docs_entry_move {
6871: border: 1px solid #BBBBBB;
6872: background: #DDDDDD;
6873: width: 22px;
6874: padding: 1px;
6875: margin: 0;
6876: }
6877:
6878: table.LC_data_table tr > td.LC_docs_entry_commands,
6879: table.LC_data_table tr > td.LC_docs_entry_parameter {
6880: font-size: x-small;
6881: }
6882:
6883: .LC_docs_entry_parameter {
6884: white-space: nowrap;
6885: }
6886:
6887: .LC_docs_copy {
6888: color: #000099;
6889: }
6890:
6891: .LC_docs_cut {
6892: color: #550044;
6893: }
6894:
6895: .LC_docs_rename {
6896: color: #009900;
6897: }
6898:
6899: .LC_docs_remove {
6900: color: #990000;
6901: }
6902:
6903: .LC_domprefs_email,
6904: .LC_docs_reinit_warn,
6905: .LC_docs_ext_edit {
6906: font-size: x-small;
6907: }
6908:
6909: table.LC_docs_adddocs td,
6910: table.LC_docs_adddocs th {
6911: border: 1px solid #BBBBBB;
6912: padding: 4px;
6913: background: #DDDDDD;
6914: }
6915:
6916: table.LC_sty_begin {
6917: background: #BBFFBB;
6918: }
6919:
6920: table.LC_sty_end {
6921: background: #FFBBBB;
6922: }
6923:
6924: table.LC_double_column {
6925: border-width: 0;
6926: border-collapse: collapse;
6927: width: 100%;
6928: padding: 2px;
6929: }
6930:
6931: table.LC_double_column tr td.LC_left_col {
6932: top: 2px;
6933: left: 2px;
6934: width: 47%;
6935: vertical-align: top;
6936: }
6937:
6938: table.LC_double_column tr td.LC_right_col {
6939: top: 2px;
6940: right: 2px;
6941: width: 47%;
6942: vertical-align: top;
6943: }
6944:
6945: div.LC_left_float {
6946: float: left;
6947: padding-right: 5%;
6948: padding-bottom: 4px;
6949: }
6950:
6951: div.LC_clear_float_header {
6952: padding-bottom: 2px;
6953: }
6954:
6955: div.LC_clear_float_footer {
6956: padding-top: 10px;
6957: clear: both;
6958: }
6959:
6960: div.LC_grade_show_user {
6961: /* border-left: 5px solid $sidebg; */
6962: border-top: 5px solid #000000;
6963: margin: 50px 0 0 0;
6964: padding: 15px 0 5px 10px;
6965: }
6966:
6967: div.LC_grade_show_user_odd_row {
6968: /* border-left: 5px solid #000000; */
6969: }
6970:
6971: div.LC_grade_show_user div.LC_Box {
6972: margin-right: 50px;
6973: }
6974:
6975: div.LC_grade_submissions,
6976: div.LC_grade_message_center,
6977: div.LC_grade_info_links {
6978: margin: 5px;
6979: width: 99%;
6980: background: #FFFFFF;
6981: }
6982:
6983: div.LC_grade_submissions_header,
6984: div.LC_grade_message_center_header {
6985: font-weight: bold;
6986: font-size: large;
6987: }
6988:
6989: div.LC_grade_submissions_body,
6990: div.LC_grade_message_center_body {
6991: border: 1px solid black;
6992: width: 99%;
6993: background: #FFFFFF;
6994: }
6995:
6996: table.LC_scantron_action {
6997: width: 100%;
6998: }
6999:
7000: table.LC_scantron_action tr th {
7001: font-weight:bold;
7002: font-style:normal;
7003: }
7004:
7005: .LC_edit_problem_header,
7006: div.LC_edit_problem_footer {
7007: font-weight: normal;
7008: font-size: medium;
7009: margin: 2px;
7010: background-color: $sidebg;
7011: }
7012:
7013: div.LC_edit_problem_header,
7014: div.LC_edit_problem_header div,
7015: div.LC_edit_problem_footer,
7016: div.LC_edit_problem_footer div,
7017: div.LC_edit_problem_editxml_header,
7018: div.LC_edit_problem_editxml_header div {
7019: z-index: 100;
7020: }
7021:
7022: div.LC_edit_problem_header_title {
7023: font-weight: bold;
7024: font-size: larger;
7025: background: $tabbg;
7026: padding: 3px;
7027: margin: 0 0 5px 0;
7028: }
7029:
7030: table.LC_edit_problem_header_title {
7031: width: 100%;
7032: background: $tabbg;
7033: }
7034:
7035: div.LC_edit_actionbar {
7036: background-color: $sidebg;
7037: margin: 0;
7038: padding: 0;
7039: line-height: 200%;
7040: }
7041:
7042: div.LC_edit_actionbar div{
7043: padding: 0;
7044: margin: 0;
7045: display: inline-block;
7046: }
7047:
7048: .LC_edit_opt {
7049: padding-left: 1em;
7050: white-space: nowrap;
7051: }
7052:
7053: .LC_edit_problem_latexhelper{
7054: text-align: right;
7055: }
7056:
7057: #LC_edit_problem_colorful div{
7058: margin-left: 40px;
7059: }
7060:
7061: #LC_edit_problem_codemirror div{
7062: margin-left: 0px;
7063: }
7064:
7065: img.stift {
7066: border-width: 0;
7067: vertical-align: middle;
7068: }
7069:
7070: table td.LC_mainmenu_col_fieldset {
7071: vertical-align: top;
7072: }
7073:
7074: div.LC_createcourse {
7075: margin: 10px 10px 10px 10px;
7076: }
7077:
7078: .LC_dccid {
7079: float: right;
7080: margin: 0.2em 0 0 0;
7081: padding: 0;
7082: font-size: 90%;
7083: display:none;
7084: }
7085:
7086: ol.LC_primary_menu a:hover,
7087: ol#LC_MenuBreadcrumbs a:hover,
7088: ol#LC_PathBreadcrumbs a:hover,
7089: ul#LC_secondary_menu a:hover,
7090: .LC_FormSectionClearButton input:hover
7091: ul.LC_TabContent li:hover a {
7092: color:$button_hover;
7093: text-decoration:none;
7094: }
7095:
7096: h1 {
7097: padding: 0;
7098: line-height:130%;
7099: }
7100:
7101: h2,
7102: h3,
7103: h4,
7104: h5,
7105: h6 {
7106: margin: 5px 0 5px 0;
7107: padding: 0;
7108: line-height:130%;
7109: }
7110:
7111: .LC_hcell {
7112: padding:3px 15px 3px 15px;
7113: margin: 0;
7114: background-color:$tabbg;
7115: color:$fontmenu;
7116: border-bottom:solid 1px $lg_border_color;
7117: }
7118:
7119: .LC_Box > .LC_hcell {
7120: margin: 0 -10px 10px -10px;
7121: }
7122:
7123: .LC_noBorder {
7124: border: 0;
7125: }
7126:
7127: .LC_FormSectionClearButton input {
7128: background-color:transparent;
7129: border: none;
7130: cursor:pointer;
7131: text-decoration:underline;
7132: }
7133:
7134: .LC_help_open_topic {
7135: color: #FFFFFF;
7136: background-color: #EEEEFF;
7137: margin: 1px;
7138: padding: 4px;
7139: border: 1px solid #000033;
7140: white-space: nowrap;
7141: /* vertical-align: middle; */
7142: }
7143:
7144: dl,
7145: ul,
7146: div,
7147: fieldset {
7148: margin: 10px 10px 10px 0;
7149: /* overflow: hidden; */
7150: }
7151:
7152: article.geogebraweb div {
7153: margin: 0;
7154: }
7155:
7156: fieldset > legend {
7157: font-weight: bold;
7158: padding: 0 5px 0 5px;
7159: }
7160:
7161: #LC_nav_bar {
7162: float: left;
7163: background-color: $pgbg_or_bgcolor;
7164: margin: 0 0 2px 0;
7165: }
7166:
7167: #LC_realm {
7168: margin: 0.2em 0 0 0;
7169: padding: 0;
7170: font-weight: bold;
7171: text-align: center;
7172: background-color: $pgbg_or_bgcolor;
7173: }
7174:
7175: #LC_nav_bar em {
7176: font-weight: bold;
7177: font-style: normal;
7178: }
7179:
7180: ol.LC_primary_menu {
7181: margin: 0;
7182: padding: 0;
7183: }
7184:
7185: ol#LC_PathBreadcrumbs {
7186: margin: 0;
7187: }
7188:
7189: ol.LC_primary_menu li {
7190: color: RGB(80, 80, 80);
7191: vertical-align: middle;
7192: text-align: left;
7193: list-style: none;
7194: position: relative;
7195: float: left;
7196: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7197: line-height: 1.5em;
7198: }
7199:
7200: ol.LC_primary_menu li a,
7201: ol.LC_primary_menu li p {
7202: display: block;
7203: margin: 0;
7204: padding: 0 5px 0 10px;
7205: text-decoration: none;
7206: }
7207:
7208: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7209: display: inline-block;
7210: width: 95%;
7211: text-align: left;
7212: }
7213:
7214: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7215: display: inline-block;
7216: width: 5%;
7217: float: right;
7218: text-align: right;
7219: font-size: 70%;
7220: }
7221:
7222: ol.LC_primary_menu ul {
7223: display: none;
7224: width: 15em;
7225: background-color: $data_table_light;
7226: position: absolute;
7227: top: 100%;
7228: }
7229:
7230: ol.LC_primary_menu ul ul {
7231: left: 100%;
7232: top: 0;
7233: }
7234:
7235: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7236: display: block;
7237: position: absolute;
7238: margin: 0;
7239: padding: 0;
7240: z-index: 2;
7241: }
7242:
7243: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7244: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7245: font-size: 90%;
7246: vertical-align: top;
7247: float: none;
7248: border-left: 1px solid black;
7249: border-right: 1px solid black;
7250: /* A dark bottom border to visualize different menu options;
7251: overwritten in the create_submenu routine for the last border-bottom of the menu */
7252: border-bottom: 1px solid $data_table_dark;
7253: }
7254:
7255: ol.LC_primary_menu li li p:hover {
7256: color:$button_hover;
7257: text-decoration:none;
7258: background-color:$data_table_dark;
7259: }
7260:
7261: ol.LC_primary_menu li li a:hover {
7262: color:$button_hover;
7263: background-color:$data_table_dark;
7264: }
7265:
7266: /* Font-size equal to the size of the predecessors*/
7267: ol.LC_primary_menu li:hover li li {
7268: font-size: 100%;
7269: }
7270:
7271: ol.LC_primary_menu li img {
7272: vertical-align: bottom;
7273: height: 1.1em;
7274: margin: 0.2em 0 0 0;
7275: }
7276:
7277: ol.LC_primary_menu a {
7278: color: RGB(80, 80, 80);
7279: text-decoration: none;
7280: }
7281:
7282: ol.LC_primary_menu a.LC_new_message {
7283: font-weight:bold;
7284: color: darkred;
7285: }
7286:
7287: ol.LC_docs_parameters {
7288: margin-left: 0;
7289: padding: 0;
7290: list-style: none;
7291: }
7292:
7293: ol.LC_docs_parameters li {
7294: margin: 0;
7295: padding-right: 20px;
7296: display: inline;
7297: }
7298:
7299: ol.LC_docs_parameters li:before {
7300: content: "\\002022 \\0020";
7301: }
7302:
7303: li.LC_docs_parameters_title {
7304: font-weight: bold;
7305: }
7306:
7307: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7308: content: "";
7309: }
7310:
7311: ul#LC_secondary_menu {
7312: clear: right;
7313: color: $fontmenu;
7314: background: $tabbg;
7315: list-style: none;
7316: padding: 0;
7317: margin: 0;
7318: width: 100%;
7319: text-align: left;
7320: float: left;
7321: }
7322:
7323: ul#LC_secondary_menu li {
7324: font-weight: bold;
7325: line-height: 1.8em;
7326: border-right: 1px solid black;
7327: float: left;
7328: }
7329:
7330: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7331: background-color: $data_table_light;
7332: }
7333:
7334: ul#LC_secondary_menu li a {
7335: padding: 0 0.8em;
7336: }
7337:
7338: ul#LC_secondary_menu li ul {
7339: display: none;
7340: }
7341:
7342: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7343: display: block;
7344: position: absolute;
7345: margin: 0;
7346: padding: 0;
7347: list-style:none;
7348: float: none;
7349: background-color: $data_table_light;
7350: z-index: 2;
7351: margin-left: -1px;
7352: }
7353:
7354: ul#LC_secondary_menu li ul li {
7355: font-size: 90%;
7356: vertical-align: top;
7357: border-left: 1px solid black;
7358: border-right: 1px solid black;
7359: background-color: $data_table_light;
7360: list-style:none;
7361: float: none;
7362: }
7363:
7364: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7365: background-color: $data_table_dark;
7366: }
7367:
7368: ul.LC_TabContent {
7369: display:block;
7370: background: $sidebg;
7371: border-bottom: solid 1px $lg_border_color;
7372: list-style:none;
7373: margin: -1px -10px 0 -10px;
7374: padding: 0;
7375: }
7376:
7377: ul.LC_TabContent li,
7378: ul.LC_TabContentBigger li {
7379: float:left;
7380: }
7381:
7382: ul#LC_secondary_menu li a {
7383: color: $fontmenu;
7384: text-decoration: none;
7385: }
7386:
7387: ul.LC_TabContent {
7388: min-height:20px;
7389: }
7390:
7391: ul.LC_TabContent li {
7392: vertical-align:middle;
7393: padding: 0 16px 0 10px;
7394: background-color:$tabbg;
7395: border-bottom:solid 1px $lg_border_color;
7396: border-left: solid 1px $font;
7397: }
7398:
7399: ul.LC_TabContent .right {
7400: float:right;
7401: }
7402:
7403: ul.LC_TabContent li a,
7404: ul.LC_TabContent li {
7405: color:rgb(47,47,47);
7406: text-decoration:none;
7407: font-size:95%;
7408: font-weight:bold;
7409: min-height:20px;
7410: }
7411:
7412: ul.LC_TabContent li a:hover,
7413: ul.LC_TabContent li a:focus {
7414: color: $button_hover;
7415: background:none;
7416: outline:none;
7417: }
7418:
7419: ul.LC_TabContent li:hover {
7420: color: $button_hover;
7421: cursor:pointer;
7422: }
7423:
7424: ul.LC_TabContent li.active {
7425: color: $font;
7426: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7427: border-bottom:solid 1px #FFFFFF;
7428: cursor: default;
7429: }
7430:
7431: ul.LC_TabContent li.active a {
7432: color:$font;
7433: background:#FFFFFF;
7434: outline: none;
7435: }
7436:
7437: ul.LC_TabContent li.goback {
7438: float: left;
7439: border-left: none;
7440: }
7441:
7442: #maincoursedoc {
7443: clear:both;
7444: }
7445:
7446: ul.LC_TabContentBigger {
7447: display:block;
7448: list-style:none;
7449: padding: 0;
7450: }
7451:
7452: ul.LC_TabContentBigger li {
7453: vertical-align:bottom;
7454: height: 30px;
7455: font-size:110%;
7456: font-weight:bold;
7457: color: #737373;
7458: }
7459:
7460: ul.LC_TabContentBigger li.active {
7461: position: relative;
7462: top: 1px;
7463: }
7464:
7465: ul.LC_TabContentBigger li a {
7466: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7467: height: 30px;
7468: line-height: 30px;
7469: text-align: center;
7470: display: block;
7471: text-decoration: none;
7472: outline: none;
7473: }
7474:
7475: ul.LC_TabContentBigger li.active a {
7476: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7477: color:$font;
7478: }
7479:
7480: ul.LC_TabContentBigger li b {
7481: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7482: display: block;
7483: float: left;
7484: padding: 0 30px;
7485: border-bottom: 1px solid $lg_border_color;
7486: }
7487:
7488: ul.LC_TabContentBigger li:hover b {
7489: color:$button_hover;
7490: }
7491:
7492: ul.LC_TabContentBigger li.active b {
7493: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7494: color:$font;
7495: border: 0;
7496: }
7497:
7498:
7499: ul.LC_CourseBreadcrumbs {
7500: background: $sidebg;
7501: height: 2em;
7502: padding-left: 10px;
7503: margin: 0;
7504: list-style-position: inside;
7505: }
7506:
7507: ol#LC_MenuBreadcrumbs,
7508: ol#LC_PathBreadcrumbs {
7509: padding-left: 10px;
7510: margin: 0;
7511: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7512: }
7513:
7514: ol#LC_MenuBreadcrumbs li,
7515: ol#LC_PathBreadcrumbs li,
7516: ul.LC_CourseBreadcrumbs li {
7517: display: inline;
7518: white-space: normal;
7519: }
7520:
7521: ol#LC_MenuBreadcrumbs li a,
7522: ul.LC_CourseBreadcrumbs li a {
7523: text-decoration: none;
7524: font-size:90%;
7525: }
7526:
7527: ol#LC_MenuBreadcrumbs h1 {
7528: display: inline;
7529: font-size: 90%;
7530: line-height: 2.5em;
7531: margin: 0;
7532: padding: 0;
7533: }
7534:
7535: ol#LC_PathBreadcrumbs li a {
7536: text-decoration:none;
7537: font-size:100%;
7538: font-weight:bold;
7539: }
7540:
7541: .LC_Box {
7542: border: solid 1px $lg_border_color;
7543: padding: 0 10px 10px 10px;
7544: }
7545:
7546: .LC_DocsBox {
7547: border: solid 1px $lg_border_color;
7548: padding: 0 0 10px 10px;
7549: }
7550:
7551: .LC_AboutMe_Image {
7552: float:left;
7553: margin-right:10px;
7554: }
7555:
7556: .LC_Clear_AboutMe_Image {
7557: clear:left;
7558: }
7559:
7560: dl.LC_ListStyleClean dt {
7561: padding-right: 5px;
7562: display: table-header-group;
7563: }
7564:
7565: dl.LC_ListStyleClean dd {
7566: display: table-row;
7567: }
7568:
7569: .LC_ListStyleClean,
7570: .LC_ListStyleSimple,
7571: .LC_ListStyleNormal,
7572: .LC_ListStyleSpecial {
7573: /* display:block; */
7574: list-style-position: inside;
7575: list-style-type: none;
7576: overflow: hidden;
7577: padding: 0;
7578: }
7579:
7580: .LC_ListStyleSimple li,
7581: .LC_ListStyleSimple dd,
7582: .LC_ListStyleNormal li,
7583: .LC_ListStyleNormal dd,
7584: .LC_ListStyleSpecial li,
7585: .LC_ListStyleSpecial dd {
7586: margin: 0;
7587: padding: 5px 5px 5px 10px;
7588: clear: both;
7589: }
7590:
7591: .LC_ListStyleClean li,
7592: .LC_ListStyleClean dd {
7593: padding-top: 0;
7594: padding-bottom: 0;
7595: }
7596:
7597: .LC_ListStyleSimple dd,
7598: .LC_ListStyleSimple li {
7599: border-bottom: solid 1px $lg_border_color;
7600: }
7601:
7602: .LC_ListStyleSpecial li,
7603: .LC_ListStyleSpecial dd {
7604: list-style-type: none;
7605: background-color: RGB(220, 220, 220);
7606: margin-bottom: 4px;
7607: }
7608:
7609: table.LC_SimpleTable {
7610: margin:5px;
7611: border:solid 1px $lg_border_color;
7612: }
7613:
7614: table.LC_SimpleTable tr {
7615: padding: 0;
7616: border:solid 1px $lg_border_color;
7617: }
7618:
7619: table.LC_SimpleTable thead {
7620: background:rgb(220,220,220);
7621: }
7622:
7623: div.LC_columnSection {
7624: display: block;
7625: clear: both;
7626: overflow: hidden;
7627: margin: 0;
7628: }
7629:
7630: div.LC_columnSection>* {
7631: float: left;
7632: margin: 10px 20px 10px 0;
7633: overflow:hidden;
7634: }
7635:
7636: table em {
7637: font-weight: bold;
7638: font-style: normal;
7639: }
7640:
7641: table.LC_tableBrowseRes,
7642: table.LC_tableOfContent {
7643: border:none;
7644: border-spacing: 1px;
7645: padding: 3px;
7646: background-color: #FFFFFF;
7647: font-size: 90%;
7648: }
7649:
7650: table.LC_tableOfContent {
7651: border-collapse: collapse;
7652: }
7653:
7654: table.LC_tableBrowseRes a,
7655: table.LC_tableOfContent a {
7656: background-color: transparent;
7657: text-decoration: none;
7658: }
7659:
7660: table.LC_tableOfContent img {
7661: border: none;
7662: height: 1.3em;
7663: vertical-align: text-bottom;
7664: margin-right: 0.3em;
7665: }
7666:
7667: a#LC_content_toolbar_firsthomework {
7668: background-image:url(/res/adm/pages/open-first-problem.gif);
7669: }
7670:
7671: a#LC_content_toolbar_everything {
7672: background-image:url(/res/adm/pages/show-all.gif);
7673: }
7674:
7675: a#LC_content_toolbar_uncompleted {
7676: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7677: }
7678:
7679: #LC_content_toolbar_clearbubbles {
7680: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7681: }
7682:
7683: a#LC_content_toolbar_changefolder {
7684: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7685: }
7686:
7687: a#LC_content_toolbar_changefolder_toggled {
7688: background-image:url(/res/adm/pages/open-all-folders.gif);
7689: }
7690:
7691: a#LC_content_toolbar_edittoplevel {
7692: background-image:url(/res/adm/pages/edittoplevel.gif);
7693: }
7694:
7695: ul#LC_toolbar li a:hover {
7696: background-position: bottom center;
7697: }
7698:
7699: ul#LC_toolbar {
7700: padding: 0;
7701: margin: 2px;
7702: list-style:none;
7703: position:relative;
7704: background-color:white;
7705: overflow: auto;
7706: }
7707:
7708: ul#LC_toolbar li {
7709: border:1px solid white;
7710: padding: 0;
7711: margin: 0;
7712: float: left;
7713: display:inline;
7714: vertical-align:middle;
7715: white-space: nowrap;
7716: }
7717:
7718:
7719: a.LC_toolbarItem {
7720: display:block;
7721: padding: 0;
7722: margin: 0;
7723: height: 32px;
7724: width: 32px;
7725: color:white;
7726: border: none;
7727: background-repeat:no-repeat;
7728: background-color:transparent;
7729: }
7730:
7731: ul.LC_funclist {
7732: margin: 0;
7733: padding: 0.5em 1em 0.5em 0;
7734: }
7735:
7736: ul.LC_funclist > li:first-child {
7737: font-weight:bold;
7738: margin-left:0.8em;
7739: }
7740:
7741: ul.LC_funclist + ul.LC_funclist {
7742: /*
7743: left border as a seperator if we have more than
7744: one list
7745: */
7746: border-left: 1px solid $sidebg;
7747: /*
7748: this hides the left border behind the border of the
7749: outer box if element is wrapped to the next 'line'
7750: */
7751: margin-left: -1px;
7752: }
7753:
7754: ul.LC_funclist li {
7755: display: inline;
7756: white-space: nowrap;
7757: margin: 0 0 0 25px;
7758: line-height: 150%;
7759: }
7760:
7761: .LC_hidden {
7762: display: none;
7763: }
7764:
7765: .LCmodal-overlay {
7766: position:fixed;
7767: top:0;
7768: right:0;
7769: bottom:0;
7770: left:0;
7771: height:100%;
7772: width:100%;
7773: margin:0;
7774: padding:0;
7775: background:#999;
7776: opacity:.75;
7777: filter: alpha(opacity=75);
7778: -moz-opacity: 0.75;
7779: z-index:101;
7780: }
7781:
7782: * html .LCmodal-overlay {
7783: position: absolute;
7784: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7785: }
7786:
7787: .LCmodal-window {
7788: position:fixed;
7789: top:50%;
7790: left:50%;
7791: margin:0;
7792: padding:0;
7793: z-index:102;
7794: }
7795:
7796: * html .LCmodal-window {
7797: position:absolute;
7798: }
7799:
7800: .LCclose-window {
7801: position:absolute;
7802: width:32px;
7803: height:32px;
7804: right:8px;
7805: top:8px;
7806: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7807: text-indent:-99999px;
7808: overflow:hidden;
7809: cursor:pointer;
7810: }
7811:
7812: pre.LC_wordwrap {
7813: white-space: pre-wrap;
7814: white-space: -moz-pre-wrap;
7815: white-space: -pre-wrap;
7816: white-space: -o-pre-wrap;
7817: word-wrap: break-word;
7818: }
7819:
7820: /*
7821: styles used by TTH when "Default set of options to pass to tth/m
7822: when converting TeX" in course settings has been set
7823:
7824: option passed: -t
7825:
7826: */
7827:
7828: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7829: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7830: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7831: td div.norm {line-height:normal;}
7832:
7833: /*
7834: option passed -y3
7835: */
7836:
7837: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7838: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7839: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7840:
7841: #LC_minitab_header {
7842: float:left;
7843: width:100%;
7844: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
7845: font-size:93%;
7846: line-height:normal;
7847: margin: 0.5em 0 0.5em 0;
7848: }
7849: #LC_minitab_header ul {
7850: margin:0;
7851: padding:10px 10px 0;
7852: list-style:none;
7853: }
7854: #LC_minitab_header li {
7855: float:left;
7856: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
7857: margin:0;
7858: padding:0 0 0 9px;
7859: }
7860: #LC_minitab_header a {
7861: display:block;
7862: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
7863: padding:5px 15px 4px 6px;
7864: }
7865: #LC_minitab_header #LC_current_minitab {
7866: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
7867: }
7868: #LC_minitab_header #LC_current_minitab a {
7869: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
7870: padding-bottom:5px;
7871: }
7872:
7873:
7874: END
7875: }
7876:
7877: =pod
7878:
7879: =item * &headtag()
7880:
7881: Returns a uniform footer for LON-CAPA web pages.
7882:
7883: Inputs: $title - optional title for the head
7884: $head_extra - optional extra HTML to put inside the <head>
7885: $args - optional arguments
7886: force_register - if is true call registerurl so the remote is
7887: informed
7888: redirect -> array ref of
7889: 1- seconds before redirect occurs
7890: 2- url to redirect to
7891: 3- whether the side effect should occur
7892: (side effect of setting
7893: $env{'internal.head.redirect'} to the url
7894: redirected too)
7895: domain -> force to color decorate a page for a specific
7896: domain
7897: function -> force usage of a specific rolish color scheme
7898: bgcolor -> override the default page bgcolor
7899: no_auto_mt_title
7900: -> prevent &mt()ing the title arg
7901:
7902: =cut
7903:
7904: sub headtag {
7905: my ($title,$head_extra,$args) = @_;
7906:
7907: my $function = $args->{'function'} || &get_users_function();
7908: my $domain = $args->{'domain'} || &determinedomain();
7909: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7910: my $httphost = $args->{'use_absolute'};
7911: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7912: $Apache::lonnet::perlvar{'lonVersion'},
7913: #time(),
7914: $env{'environment.color.timestamp'},
7915: $function,$domain,$bgcolor);
7916:
7917: $url = '/adm/css/'.&escape($url).'.css';
7918:
7919: my $result =
7920: '<head>'.
7921: &font_settings($args);
7922:
7923: my $inhibitprint;
7924: if ($args->{'print_suppress'}) {
7925: $inhibitprint = &print_suppression();
7926: }
7927:
7928: if (!$args->{'frameset'}) {
7929: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7930: }
7931: if ($args->{'force_register'}) {
7932: $result .= &Apache::lonmenu::registerurl(1);
7933: }
7934: if (!$args->{'no_nav_bar'}
7935: && !$args->{'only_body'}
7936: && !$args->{'frameset'}) {
7937: $result .= &help_menu_js($httphost);
7938: $result.=&modal_window();
7939: $result.=&togglebox_script();
7940: $result.=&wishlist_window();
7941: $result.=&LCprogressbarUpdate_script();
7942: } else {
7943: if ($args->{'add_modal'}) {
7944: $result.=&modal_window();
7945: }
7946: if ($args->{'add_wishlist'}) {
7947: $result.=&wishlist_window();
7948: }
7949: if ($args->{'add_togglebox'}) {
7950: $result.=&togglebox_script();
7951: }
7952: if ($args->{'add_progressbar'}) {
7953: $result.=&LCprogressbarUpdate_script();
7954: }
7955: }
7956: if (ref($args->{'redirect'})) {
7957: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7958: $url = &Apache::lonenc::check_encrypt($url);
7959: if (!$inhibit_continue) {
7960: $env{'internal.head.redirect'} = $url;
7961: }
7962: $result.=<<ADDMETA
7963: <meta http-equiv="pragma" content="no-cache" />
7964: <meta http-equiv="Refresh" content="$time; url=$url" />
7965: ADDMETA
7966: } else {
7967: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
7968: my $requrl = $env{'request.uri'};
7969: if ($requrl eq '') {
7970: $requrl = $ENV{'REQUEST_URI'};
7971: $requrl =~ s/\?.+$//;
7972: }
7973: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
7974: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
7975: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
7976: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
7977: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
7978: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
7979: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
7980: my $offload;
7981: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
7982: if ($domdefs{'offloadnow'}{$lonhost}) {
7983: $offload = 1;
7984: }
7985: }
7986: unless ($offload) {
7987: if (ref($domdefs{'offloadoth'}) eq 'HASH') {
7988: if ($domdefs{'offloadoth'}{$lonhost}) {
7989: if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
7990: (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
7991: unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
7992: $offload = 1;
7993: $dom_in_use = $env{'user.domain'};
7994: }
7995: }
7996: }
7997: }
7998: }
7999: if ($offload) {
8000: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
8001: if (($newserver) && ($newserver ne $lonhost)) {
8002: my $numsec = 5;
8003: my $timeout = $numsec * 1000;
8004: my ($newurl,$locknum,%locks,$msg);
8005: if ($env{'request.role.adv'}) {
8006: ($locknum,%locks) = &Apache::lonnet::get_locks();
8007: }
8008: my $disable_submit = 0;
8009: if ($requrl =~ /$LONCAPA::assess_re/) {
8010: $disable_submit = 1;
8011: }
8012: if ($locknum) {
8013: my @lockinfo = sort(values(%locks));
8014: $msg = &mt('Once the following tasks are complete: ')."\n".
8015: join(", ",sort(values(%locks)))."\n";
8016: if (&show_course()) {
8017: $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
8018: } else {
8019: $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
8020: }
8021: } else {
8022: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
8023: $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
8024: }
8025: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
8026: $newurl = '/adm/switchserver?otherserver='.$newserver;
8027: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
8028: $newurl .= '&role='.$env{'request.role'};
8029: }
8030: if ($env{'request.symb'}) {
8031: my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
8032: if ($shownsymb =~ m{^/enc/}) {
8033: my $reqdmajor = 2;
8034: my $reqdminor = 11;
8035: my $reqdsubminor = 3;
8036: my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
8037: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
8038: my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
8039: if (($major eq '' && $minor eq '') ||
8040: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
8041: (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
8042: ($reqdsubminor > $subminor))))) {
8043: undef($shownsymb);
8044: }
8045: }
8046: if ($shownsymb) {
8047: &js_escape(\$shownsymb);
8048: $newurl .= '&symb='.$shownsymb;
8049: }
8050: } else {
8051: my $shownurl = &Apache::lonenc::check_encrypt($requrl);
8052: &js_escape(\$shownurl);
8053: $newurl .= '&origurl='.$shownurl;
8054: }
8055: }
8056: &js_escape(\$msg);
8057: $result.=<<OFFLOAD
8058: <meta http-equiv="pragma" content="no-cache" />
8059: <script type="text/javascript">
8060: // <![CDATA[
8061: function LC_Offload_Now() {
8062: var dest = "$newurl";
8063: if (dest != '') {
8064: window.location.href="$newurl";
8065: }
8066: }
8067: \$(document).ready(function () {
8068: window.alert('$msg');
8069: if ($disable_submit) {
8070: \$(".LC_hwk_submit").prop("disabled", true);
8071: \$( ".LC_textline" ).prop( "readonly", "readonly");
8072: }
8073: setTimeout('LC_Offload_Now()', $timeout);
8074: });
8075: // ]]>
8076: </script>
8077: OFFLOAD
8078: }
8079: }
8080: }
8081: }
8082: }
8083: }
8084: if (!defined($title)) {
8085: $title = 'The LearningOnline Network with CAPA';
8086: }
8087: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
8088: $result .= '<title> LON-CAPA '.$title.'</title>'
8089: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
8090: if (!$args->{'frameset'}) {
8091: $result .= ' /';
8092: }
8093: $result .= '>'
8094: .$inhibitprint
8095: .$head_extra;
8096: my $clientmobile;
8097: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
8098: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
8099: } else {
8100: $clientmobile = $env{'browser.mobile'};
8101: }
8102: if ($clientmobile) {
8103: $result .= '
8104: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
8105: <meta name="apple-mobile-web-app-capable" content="yes" />';
8106: }
8107: $result .= '<meta name="google" content="notranslate" />'."\n";
8108: return $result.'</head>';
8109: }
8110:
8111: =pod
8112:
8113: =item * &font_settings()
8114:
8115: Returns neccessary <meta> to set the proper encoding
8116:
8117: Inputs: optional reference to HASH -- $args passed to &headtag()
8118:
8119: =cut
8120:
8121: sub font_settings {
8122: my ($args) = @_;
8123: my $headerstring='';
8124: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
8125: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
8126: $headerstring.=
8127: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
8128: if (!$args->{'frameset'}) {
8129: $headerstring.= ' /';
8130: }
8131: $headerstring .= '>'."\n";
8132: }
8133: return $headerstring;
8134: }
8135:
8136: =pod
8137:
8138: =item * &print_suppression()
8139:
8140: In course context returns css which causes the body to be blank when media="print",
8141: if printout generation is unavailable for the current resource.
8142:
8143: This could be because:
8144:
8145: (a) printstartdate is in the future
8146:
8147: (b) printenddate is in the past
8148:
8149: (c) there is an active exam block with "printout"
8150: functionality blocked
8151:
8152: Users with pav, pfo or evb privileges are exempt.
8153:
8154: Inputs: none
8155:
8156: =cut
8157:
8158:
8159: sub print_suppression {
8160: my $noprint;
8161: if ($env{'request.course.id'}) {
8162: my $scope = $env{'request.course.id'};
8163: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8164: (&Apache::lonnet::allowed('pfo',$scope))) {
8165: return;
8166: }
8167: if ($env{'request.course.sec'} ne '') {
8168: $scope .= "/$env{'request.course.sec'}";
8169: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8170: (&Apache::lonnet::allowed('pfo',$scope))) {
8171: return;
8172: }
8173: }
8174: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8175: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8176: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
8177: if ($blocked) {
8178: my $checkrole = "cm./$cdom/$cnum";
8179: if ($env{'request.course.sec'} ne '') {
8180: $checkrole .= "/$env{'request.course.sec'}";
8181: }
8182: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
8183: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
8184: $noprint = 1;
8185: }
8186: }
8187: unless ($noprint) {
8188: my $symb = &Apache::lonnet::symbread();
8189: if ($symb ne '') {
8190: my $navmap = Apache::lonnavmaps::navmap->new();
8191: if (ref($navmap)) {
8192: my $res = $navmap->getBySymb($symb);
8193: if (ref($res)) {
8194: if (!$res->resprintable()) {
8195: $noprint = 1;
8196: }
8197: }
8198: }
8199: }
8200: }
8201: if ($noprint) {
8202: return <<"ENDSTYLE";
8203: <style type="text/css" media="print">
8204: body { display:none }
8205: </style>
8206: ENDSTYLE
8207: }
8208: }
8209: return;
8210: }
8211:
8212: =pod
8213:
8214: =item * &xml_begin()
8215:
8216: Returns the needed doctype and <html>
8217:
8218: Inputs: none
8219:
8220: =cut
8221:
8222: sub xml_begin {
8223: my ($is_frameset) = @_;
8224: my $output='';
8225:
8226: if ($env{'browser.mathml'}) {
8227: $output='<?xml version="1.0"?>'
8228: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8229: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8230:
8231: # .'<!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">] >'
8232: .'<!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">'
8233: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8234: .'xmlns="http://www.w3.org/1999/xhtml">';
8235: } elsif ($is_frameset) {
8236: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8237: '<html>'."\n";
8238: } else {
8239: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8240: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8241: }
8242: return $output;
8243: }
8244:
8245: =pod
8246:
8247: =item * &start_page()
8248:
8249: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8250:
8251: Inputs:
8252:
8253: =over 4
8254:
8255: $title - optional title for the page
8256:
8257: $head_extra - optional extra HTML to incude inside the <head>
8258:
8259: $args - additional optional args supported are:
8260:
8261: =over 8
8262:
8263: only_body -> is true will set &bodytag() onlybodytag
8264: arg on
8265: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8266: add_entries -> additional attributes to add to the <body>
8267: domain -> force to color decorate a page for a
8268: specific domain
8269: function -> force usage of a specific rolish color
8270: scheme
8271: redirect -> see &headtag()
8272: bgcolor -> override the default page bg color
8273: js_ready -> return a string ready for being used in
8274: a javascript writeln
8275: html_encode -> return a string ready for being used in
8276: a html attribute
8277: force_register -> if is true will turn on the &bodytag()
8278: $forcereg arg
8279: frameset -> if true will start with a <frameset>
8280: rather than <body>
8281: skip_phases -> hash ref of
8282: head -> skip the <html><head> generation
8283: body -> skip all <body> generation
8284: no_inline_link -> if true and in remote mode, don't show the
8285: 'Switch To Inline Menu' link
8286: no_auto_mt_title -> prevent &mt()ing the title arg
8287: bread_crumbs -> Array containing breadcrumbs
8288: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8289: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
8290: to lonhtmlcommon::breadcrumbs
8291: group -> includes the current group, if page is for a
8292: specific group
8293: use_absolute -> for request for external resource or syllabus, this
8294: will contain https://<hostname> if server uses
8295: https (as per hosts.tab), but request is for http
8296: hostname -> hostname, originally from $r->hostname(), (optional).
8297:
8298: =back
8299:
8300: =back
8301:
8302: =cut
8303:
8304: sub start_page {
8305: my ($title,$head_extra,$args) = @_;
8306: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8307:
8308: $env{'internal.start_page'}++;
8309: my ($result,@advtools);
8310:
8311: if (! exists($args->{'skip_phases'}{'head'}) ) {
8312: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8313: }
8314:
8315: if (! exists($args->{'skip_phases'}{'body'}) ) {
8316: if ($args->{'frameset'}) {
8317: my $attr_string = &make_attr_string($args->{'force_register'},
8318: $args->{'add_entries'});
8319: $result .= "\n<frameset $attr_string>\n";
8320: } else {
8321: $result .=
8322: &bodytag($title,
8323: $args->{'function'}, $args->{'add_entries'},
8324: $args->{'only_body'}, $args->{'domain'},
8325: $args->{'force_register'}, $args->{'no_nav_bar'},
8326: $args->{'bgcolor'}, $args->{'no_inline_link'},
8327: $args, \@advtools);
8328: }
8329: }
8330:
8331: if ($args->{'js_ready'}) {
8332: $result = &js_ready($result);
8333: }
8334: if ($args->{'html_encode'}) {
8335: $result = &html_encode($result);
8336: }
8337:
8338: # Preparation for new and consistent functionlist at top of screen
8339: # if ($args->{'functionlist'}) {
8340: # $result .= &build_functionlist();
8341: #}
8342:
8343: # Don't add anything more if only_body wanted or in const space
8344: return $result if $args->{'only_body'}
8345: || $env{'request.state'} eq 'construct';
8346:
8347: #Breadcrumbs
8348: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8349: &Apache::lonhtmlcommon::clear_breadcrumbs();
8350: #if any br links exists, add them to the breadcrumbs
8351: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8352: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8353: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8354: }
8355: }
8356: # if @advtools array contains items add then to the breadcrumbs
8357: if (@advtools > 0) {
8358: &Apache::lonmenu::advtools_crumbs(@advtools);
8359: }
8360: my $menulink;
8361: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
8362: if (exists($args->{'bread_crumbs_nomenu'})) {
8363: $menulink = 0;
8364: } else {
8365: undef($menulink);
8366: }
8367: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8368: if(exists($args->{'bread_crumbs_component'})){
8369: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
8370: }else{
8371: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
8372: }
8373: } elsif (($env{'environment.remote'} eq 'on') &&
8374: ($env{'form.inhibitmenu'} ne 'yes') &&
8375: ($env{'request.noversionuri'} =~ m{^/res/}) &&
8376: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
8377: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
8378: }
8379: return $result;
8380: }
8381:
8382: sub end_page {
8383: my ($args) = @_;
8384: $env{'internal.end_page'}++;
8385: my $result;
8386: if ($args->{'discussion'}) {
8387: my ($target,$parser);
8388: if (ref($args->{'discussion'})) {
8389: ($target,$parser) =($args->{'discussion'}{'target'},
8390: $args->{'discussion'}{'parser'});
8391: }
8392: $result .= &Apache::lonxml::xmlend($target,$parser);
8393: }
8394: if ($args->{'frameset'}) {
8395: $result .= '</frameset>';
8396: } else {
8397: $result .= &endbodytag($args);
8398: }
8399: unless ($args->{'notbody'}) {
8400: $result .= "\n</html>";
8401: }
8402:
8403: if ($args->{'js_ready'}) {
8404: $result = &js_ready($result);
8405: }
8406:
8407: if ($args->{'html_encode'}) {
8408: $result = &html_encode($result);
8409: }
8410:
8411: return $result;
8412: }
8413:
8414: sub wishlist_window {
8415: return(<<'ENDWISHLIST');
8416: <script type="text/javascript">
8417: // <![CDATA[
8418: // <!-- BEGIN LON-CAPA Internal
8419: function set_wishlistlink(title, path) {
8420: if (!title) {
8421: title = document.title;
8422: title = title.replace(/^LON-CAPA /,'');
8423: }
8424: title = encodeURIComponent(title);
8425: title = title.replace("'","\\\'");
8426: if (!path) {
8427: path = location.pathname;
8428: }
8429: path = encodeURIComponent(path);
8430: path = path.replace("'","\\\'");
8431: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8432: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8433: }
8434: // END LON-CAPA Internal -->
8435: // ]]>
8436: </script>
8437: ENDWISHLIST
8438: }
8439:
8440: sub modal_window {
8441: return(<<'ENDMODAL');
8442: <script type="text/javascript">
8443: // <![CDATA[
8444: // <!-- BEGIN LON-CAPA Internal
8445: var modalWindow = {
8446: parent:"body",
8447: windowId:null,
8448: content:null,
8449: width:null,
8450: height:null,
8451: close:function()
8452: {
8453: $(".LCmodal-window").remove();
8454: $(".LCmodal-overlay").remove();
8455: },
8456: open:function()
8457: {
8458: var modal = "";
8459: modal += "<div class=\"LCmodal-overlay\"></div>";
8460: 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;\">";
8461: modal += this.content;
8462: modal += "</div>";
8463:
8464: $(this.parent).append(modal);
8465:
8466: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8467: $(".LCclose-window").click(function(){modalWindow.close();});
8468: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8469: }
8470: };
8471: var openMyModal = function(source,width,height,scrolling,transparency,style)
8472: {
8473: source = source.replace(/'/g,"'");
8474: modalWindow.windowId = "myModal";
8475: modalWindow.width = width;
8476: modalWindow.height = height;
8477: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8478: modalWindow.open();
8479: };
8480: // END LON-CAPA Internal -->
8481: // ]]>
8482: </script>
8483: ENDMODAL
8484: }
8485:
8486: sub modal_link {
8487: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8488: unless ($width) { $width=480; }
8489: unless ($height) { $height=400; }
8490: unless ($scrolling) { $scrolling='yes'; }
8491: unless ($transparency) { $transparency='true'; }
8492:
8493: my $target_attr;
8494: if (defined($target)) {
8495: $target_attr = 'target="'.$target.'"';
8496: }
8497: return <<"ENDLINK";
8498: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
8499: ENDLINK
8500: }
8501:
8502: sub modal_adhoc_script {
8503: my ($funcname,$width,$height,$content)=@_;
8504: return (<<ENDADHOC);
8505: <script type="text/javascript">
8506: // <![CDATA[
8507: var $funcname = function()
8508: {
8509: modalWindow.windowId = "myModal";
8510: modalWindow.width = $width;
8511: modalWindow.height = $height;
8512: modalWindow.content = '$content';
8513: modalWindow.open();
8514: };
8515: // ]]>
8516: </script>
8517: ENDADHOC
8518: }
8519:
8520: sub modal_adhoc_inner {
8521: my ($funcname,$width,$height,$content)=@_;
8522: my $innerwidth=$width-20;
8523: $content=&js_ready(
8524: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8525: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8526: $content.
8527: &end_scrollbox().
8528: &end_page()
8529: );
8530: return &modal_adhoc_script($funcname,$width,$height,$content);
8531: }
8532:
8533: sub modal_adhoc_window {
8534: my ($funcname,$width,$height,$content,$linktext)=@_;
8535: return &modal_adhoc_inner($funcname,$width,$height,$content).
8536: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8537: }
8538:
8539: sub modal_adhoc_launch {
8540: my ($funcname,$width,$height,$content)=@_;
8541: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8542: <script type="text/javascript">
8543: // <![CDATA[
8544: $funcname();
8545: // ]]>
8546: </script>
8547: ENDLAUNCH
8548: }
8549:
8550: sub modal_adhoc_close {
8551: return (<<ENDCLOSE);
8552: <script type="text/javascript">
8553: // <![CDATA[
8554: modalWindow.close();
8555: // ]]>
8556: </script>
8557: ENDCLOSE
8558: }
8559:
8560: sub togglebox_script {
8561: return(<<ENDTOGGLE);
8562: <script type="text/javascript">
8563: // <![CDATA[
8564: function LCtoggleDisplay(id,hidetext,showtext) {
8565: link = document.getElementById(id + "link").childNodes[0];
8566: with (document.getElementById(id).style) {
8567: if (display == "none" ) {
8568: display = "inline";
8569: link.nodeValue = hidetext;
8570: } else {
8571: display = "none";
8572: link.nodeValue = showtext;
8573: }
8574: }
8575: }
8576: // ]]>
8577: </script>
8578: ENDTOGGLE
8579: }
8580:
8581: sub start_togglebox {
8582: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8583: unless ($heading) { $heading=''; } else { $heading.=' '; }
8584: unless ($showtext) { $showtext=&mt('show'); }
8585: unless ($hidetext) { $hidetext=&mt('hide'); }
8586: unless ($headerbg) { $headerbg='#FFFFFF'; }
8587: return &start_data_table().
8588: &start_data_table_header_row().
8589: '<td bgcolor="'.$headerbg.'">'.$heading.
8590: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8591: $showtext.'\')">'.$showtext.'</a>]</td>'.
8592: &end_data_table_header_row().
8593: '<tr id="'.$id.'" style="display:none""><td>';
8594: }
8595:
8596: sub end_togglebox {
8597: return '</td></tr>'.&end_data_table();
8598: }
8599:
8600: sub LCprogressbar_script {
8601: my ($id,$number_to_do)=@_;
8602: if ($number_to_do) {
8603: return(<<ENDPROGRESS);
8604: <script type="text/javascript">
8605: // <![CDATA[
8606: \$('#progressbar$id').progressbar({
8607: value: 0,
8608: change: function(event, ui) {
8609: var newVal = \$(this).progressbar('option', 'value');
8610: \$('.pblabel', this).text(LCprogressTxt);
8611: }
8612: });
8613: // ]]>
8614: </script>
8615: ENDPROGRESS
8616: } else {
8617: return(<<ENDPROGRESS);
8618: <script type="text/javascript">
8619: // <![CDATA[
8620: \$('#progressbar$id').progressbar({
8621: value: false,
8622: create: function(event, ui) {
8623: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
8624: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
8625: }
8626: });
8627: // ]]>
8628: </script>
8629: ENDPROGRESS
8630: }
8631: }
8632:
8633: sub LCprogressbarUpdate_script {
8634: return(<<ENDPROGRESSUPDATE);
8635: <style type="text/css">
8636: .ui-progressbar { position:relative; }
8637: .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%; }
8638: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
8639: </style>
8640: <script type="text/javascript">
8641: // <![CDATA[
8642: var LCprogressTxt='---';
8643:
8644: function LCupdateProgress(percent,progresstext,id,maxnum) {
8645: LCprogressTxt=progresstext;
8646: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
8647: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
8648: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
8649: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
8650: } else {
8651: \$('#progressbar'+id).progressbar('value',percent);
8652: }
8653: }
8654: // ]]>
8655: </script>
8656: ENDPROGRESSUPDATE
8657: }
8658:
8659: my $LClastpercent;
8660: my $LCidcnt;
8661: my $LCcurrentid;
8662:
8663: sub LCprogressbar {
8664: my ($r,$number_to_do,$preamble)=@_;
8665: $LClastpercent=0;
8666: $LCidcnt++;
8667: $LCcurrentid=$$.'_'.$LCidcnt;
8668: my ($starting,$content);
8669: if ($number_to_do) {
8670: $starting=&mt('Starting');
8671: $content=(<<ENDPROGBAR);
8672: $preamble
8673: <div id="progressbar$LCcurrentid">
8674: <span class="pblabel">$starting</span>
8675: </div>
8676: ENDPROGBAR
8677: } else {
8678: $starting=&mt('Loading...');
8679: $LClastpercent='false';
8680: $content=(<<ENDPROGBAR);
8681: $preamble
8682: <div id="progressbar$LCcurrentid">
8683: <div class="progress-label">$starting</div>
8684: </div>
8685: ENDPROGBAR
8686: }
8687: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
8688: }
8689:
8690: sub LCprogressbarUpdate {
8691: my ($r,$val,$text,$number_to_do)=@_;
8692: if ($number_to_do) {
8693: unless ($val) {
8694: if ($LClastpercent) {
8695: $val=$LClastpercent;
8696: } else {
8697: $val=0;
8698: }
8699: }
8700: if ($val<0) { $val=0; }
8701: if ($val>100) { $val=0; }
8702: $LClastpercent=$val;
8703: unless ($text) { $text=$val.'%'; }
8704: } else {
8705: $val = 'false';
8706: }
8707: $text=&js_ready($text);
8708: &r_print($r,<<ENDUPDATE);
8709: <script type="text/javascript">
8710: // <![CDATA[
8711: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
8712: // ]]>
8713: </script>
8714: ENDUPDATE
8715: }
8716:
8717: sub LCprogressbarClose {
8718: my ($r)=@_;
8719: $LClastpercent=0;
8720: &r_print($r,<<ENDCLOSE);
8721: <script type="text/javascript">
8722: // <![CDATA[
8723: \$("#progressbar$LCcurrentid").hide('slow');
8724: // ]]>
8725: </script>
8726: ENDCLOSE
8727: }
8728:
8729: sub r_print {
8730: my ($r,$to_print)=@_;
8731: if ($r) {
8732: $r->print($to_print);
8733: $r->rflush();
8734: } else {
8735: print($to_print);
8736: }
8737: }
8738:
8739: sub html_encode {
8740: my ($result) = @_;
8741:
8742: $result = &HTML::Entities::encode($result,'<>&"');
8743:
8744: return $result;
8745: }
8746:
8747: sub js_ready {
8748: my ($result) = @_;
8749:
8750: $result =~ s/[\n\r]/ /xmsg;
8751: $result =~ s/\\/\\\\/xmsg;
8752: $result =~ s/'/\\'/xmsg;
8753: $result =~ s{</}{<\\/}xmsg;
8754:
8755: return $result;
8756: }
8757:
8758: sub validate_page {
8759: if ( exists($env{'internal.start_page'})
8760: && $env{'internal.start_page'} > 1) {
8761: &Apache::lonnet::logthis('start_page called multiple times '.
8762: $env{'internal.start_page'}.' '.
8763: $ENV{'request.filename'});
8764: }
8765: if ( exists($env{'internal.end_page'})
8766: && $env{'internal.end_page'} > 1) {
8767: &Apache::lonnet::logthis('end_page called multiple times '.
8768: $env{'internal.end_page'}.' '.
8769: $env{'request.filename'});
8770: }
8771: if ( exists($env{'internal.start_page'})
8772: && ! exists($env{'internal.end_page'})) {
8773: &Apache::lonnet::logthis('start_page called without end_page '.
8774: $env{'request.filename'});
8775: }
8776: if ( ! exists($env{'internal.start_page'})
8777: && exists($env{'internal.end_page'})) {
8778: &Apache::lonnet::logthis('end_page called without start_page'.
8779: $env{'request.filename'});
8780: }
8781: }
8782:
8783:
8784: sub start_scrollbox {
8785: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8786: unless ($outerwidth) { $outerwidth='520px'; }
8787: unless ($width) { $width='500px'; }
8788: unless ($height) { $height='200px'; }
8789: my ($table_id,$div_id,$tdcol);
8790: if ($id ne '') {
8791: $table_id = ' id="table_'.$id.'"';
8792: $div_id = ' id="div_'.$id.'"';
8793: }
8794: if ($bgcolor ne '') {
8795: $tdcol = "background-color: $bgcolor;";
8796: }
8797: my $nicescroll_js;
8798: if ($env{'browser.mobile'}) {
8799: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8800: }
8801: return <<"END";
8802: $nicescroll_js
8803:
8804: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8805: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8806: END
8807: }
8808:
8809: sub end_scrollbox {
8810: return '</div></td></tr></table>';
8811: }
8812:
8813: sub nicescroll_javascript {
8814: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8815: my %options;
8816: if (ref($cursor) eq 'HASH') {
8817: %options = %{$cursor};
8818: }
8819: unless ($options{'railalign'} =~ /^left|right$/) {
8820: $options{'railalign'} = 'left';
8821: }
8822: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8823: my $function = &get_users_function();
8824: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8825: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8826: $options{'cursorcolor'} = '#00F';
8827: }
8828: }
8829: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8830: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8831: $options{'cursoropacity'}='1.0';
8832: }
8833: } else {
8834: $options{'cursoropacity'}='1.0';
8835: }
8836: if ($options{'cursorfixedheight'} eq 'none') {
8837: delete($options{'cursorfixedheight'});
8838: } else {
8839: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8840: }
8841: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8842: delete($options{'railoffset'});
8843: }
8844: my @niceoptions;
8845: while (my($key,$value) = each(%options)) {
8846: if ($value =~ /^\{.+\}$/) {
8847: push(@niceoptions,$key.':'.$value);
8848: } else {
8849: push(@niceoptions,$key.':"'.$value.'"');
8850: }
8851: }
8852: my $nicescroll_js = '
8853: $(document).ready(
8854: function() {
8855: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8856: }
8857: );
8858: ';
8859: if ($framecheck) {
8860: $nicescroll_js .= '
8861: function expand_div(caller) {
8862: if (top === self) {
8863: document.getElementById("'.$id.'").style.width = "auto";
8864: document.getElementById("'.$id.'").style.height = "auto";
8865: } else {
8866: try {
8867: if (parent.frames) {
8868: if (parent.frames.length > 1) {
8869: var framesrc = parent.frames[1].location.href;
8870: var currsrc = framesrc.replace(/\#.*$/,"");
8871: if ((caller == "search") || (currsrc == "'.$location.'")) {
8872: document.getElementById("'.$id.'").style.width = "auto";
8873: document.getElementById("'.$id.'").style.height = "auto";
8874: }
8875: }
8876: }
8877: } catch (e) {
8878: return;
8879: }
8880: }
8881: return;
8882: }
8883: ';
8884: }
8885: if ($needjsready) {
8886: $nicescroll_js = '
8887: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8888: } else {
8889: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8890: }
8891: return $nicescroll_js;
8892: }
8893:
8894: sub simple_error_page {
8895: my ($r,$title,$msg,$args) = @_;
8896: if (ref($args) eq 'HASH') {
8897: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8898: } else {
8899: $msg = &mt($msg);
8900: }
8901:
8902: my $page =
8903: &Apache::loncommon::start_page($title).
8904: '<p class="LC_error">'.$msg.'</p>'.
8905: &Apache::loncommon::end_page();
8906: if (ref($r)) {
8907: $r->print($page);
8908: return;
8909: }
8910: return $page;
8911: }
8912:
8913: {
8914: my @row_count;
8915:
8916: sub start_data_table_count {
8917: unshift(@row_count, 0);
8918: return;
8919: }
8920:
8921: sub end_data_table_count {
8922: shift(@row_count);
8923: return;
8924: }
8925:
8926: sub start_data_table {
8927: my ($add_class,$id) = @_;
8928: my $css_class = (join(' ','LC_data_table',$add_class));
8929: my $table_id;
8930: if (defined($id)) {
8931: $table_id = ' id="'.$id.'"';
8932: }
8933: &start_data_table_count();
8934: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8935: }
8936:
8937: sub end_data_table {
8938: &end_data_table_count();
8939: return '</table>'."\n";;
8940: }
8941:
8942: sub start_data_table_row {
8943: my ($add_class, $id) = @_;
8944: $row_count[0]++;
8945: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8946: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8947: $id = (' id="'.$id.'"') unless ($id eq '');
8948: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8949: }
8950:
8951: sub continue_data_table_row {
8952: my ($add_class, $id) = @_;
8953: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8954: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8955: $id = (' id="'.$id.'"') unless ($id eq '');
8956: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8957: }
8958:
8959: sub end_data_table_row {
8960: return '</tr>'."\n";;
8961: }
8962:
8963: sub start_data_table_empty_row {
8964: # $row_count[0]++;
8965: return '<tr class="LC_empty_row" >'."\n";;
8966: }
8967:
8968: sub end_data_table_empty_row {
8969: return '</tr>'."\n";;
8970: }
8971:
8972: sub start_data_table_header_row {
8973: return '<tr class="LC_header_row">'."\n";;
8974: }
8975:
8976: sub end_data_table_header_row {
8977: return '</tr>'."\n";;
8978: }
8979:
8980: sub data_table_caption {
8981: my $caption = shift;
8982: return "<caption class=\"LC_caption\">$caption</caption>";
8983: }
8984: }
8985:
8986: =pod
8987:
8988: =item * &inhibit_menu_check($arg)
8989:
8990: Checks for a inhibitmenu state and generates output to preserve it
8991:
8992: Inputs: $arg - can be any of
8993: - undef - in which case the return value is a string
8994: to add into arguments list of a uri
8995: - 'input' - in which case the return value is a HTML
8996: <form> <input> field of type hidden to
8997: preserve the value
8998: - a url - in which case the return value is the url with
8999: the neccesary cgi args added to preserve the
9000: inhibitmenu state
9001: - a ref to a url - no return value, but the string is
9002: updated to include the neccessary cgi
9003: args to preserve the inhibitmenu state
9004:
9005: =cut
9006:
9007: sub inhibit_menu_check {
9008: my ($arg) = @_;
9009: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
9010: if ($arg eq 'input') {
9011: if ($env{'form.inhibitmenu'}) {
9012: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
9013: } else {
9014: return
9015: }
9016: }
9017: if ($env{'form.inhibitmenu'}) {
9018: if (ref($arg)) {
9019: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9020: } elsif ($arg eq '') {
9021: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
9022: } else {
9023: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9024: }
9025: }
9026: if (!ref($arg)) {
9027: return $arg;
9028: }
9029: }
9030:
9031: ###############################################
9032:
9033: =pod
9034:
9035: =back
9036:
9037: =head1 User Information Routines
9038:
9039: =over 4
9040:
9041: =item * &get_users_function()
9042:
9043: Used by &bodytag to determine the current users primary role.
9044: Returns either 'student','coordinator','admin', or 'author'.
9045:
9046: =cut
9047:
9048: ###############################################
9049: sub get_users_function {
9050: my $function = 'norole';
9051: if ($env{'request.role'}=~/^(st)/) {
9052: $function='student';
9053: }
9054: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
9055: $function='coordinator';
9056: }
9057: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
9058: $function='admin';
9059: }
9060: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
9061: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
9062: $function='author';
9063: }
9064: return $function;
9065: }
9066:
9067: ###############################################
9068:
9069: =pod
9070:
9071: =item * &show_course()
9072:
9073: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
9074: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
9075:
9076: Inputs:
9077: None
9078:
9079: Outputs:
9080: Scalar: 1 if 'Course' to be used, 0 otherwise.
9081:
9082: =cut
9083:
9084: ###############################################
9085: sub show_course {
9086: my $course = !$env{'user.adv'};
9087: if (!$env{'user.adv'}) {
9088: foreach my $env (keys(%env)) {
9089: next if ($env !~ m/^user\.priv\./);
9090: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
9091: $course = 0;
9092: last;
9093: }
9094: }
9095: }
9096: return $course;
9097: }
9098:
9099: ###############################################
9100:
9101: =pod
9102:
9103: =item * &check_user_status()
9104:
9105: Determines current status of supplied role for a
9106: specific user. Roles can be active, previous or future.
9107:
9108: Inputs:
9109: user's domain, user's username, course's domain,
9110: course's number, optional section ID.
9111:
9112: Outputs:
9113: role status: active, previous or future.
9114:
9115: =cut
9116:
9117: sub check_user_status {
9118: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
9119: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
9120: my @uroles = keys(%userinfo);
9121: my $srchstr;
9122: my $active_chk = 'none';
9123: my $now = time;
9124: if (@uroles > 0) {
9125: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
9126: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
9127: } else {
9128: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
9129: }
9130: if (grep/^\Q$srchstr\E$/,@uroles) {
9131: my $role_end = 0;
9132: my $role_start = 0;
9133: $active_chk = 'active';
9134: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
9135: $role_end = $1;
9136: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
9137: $role_start = $1;
9138: }
9139: }
9140: if ($role_start > 0) {
9141: if ($now < $role_start) {
9142: $active_chk = 'future';
9143: }
9144: }
9145: if ($role_end > 0) {
9146: if ($now > $role_end) {
9147: $active_chk = 'previous';
9148: }
9149: }
9150: }
9151: }
9152: return $active_chk;
9153: }
9154:
9155: ###############################################
9156:
9157: =pod
9158:
9159: =item * &get_sections()
9160:
9161: Determines all the sections for a course including
9162: sections with students and sections containing other roles.
9163: Incoming parameters:
9164:
9165: 1. domain
9166: 2. course number
9167: 3. reference to array containing roles for which sections should
9168: be gathered (optional).
9169: 4. reference to array containing status types for which sections
9170: should be gathered (optional).
9171:
9172: If the third argument is undefined, sections are gathered for any role.
9173: If the fourth argument is undefined, sections are gathered for any status.
9174: Permissible values are 'active' or 'future' or 'previous'.
9175:
9176: Returns section hash (keys are section IDs, values are
9177: number of users in each section), subject to the
9178: optional roles filter, optional status filter
9179:
9180: =cut
9181:
9182: ###############################################
9183: sub get_sections {
9184: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
9185: if (!defined($cdom) || !defined($cnum)) {
9186: my $cid = $env{'request.course.id'};
9187:
9188: return if (!defined($cid));
9189:
9190: $cdom = $env{'course.'.$cid.'.domain'};
9191: $cnum = $env{'course.'.$cid.'.num'};
9192: }
9193:
9194: my %sectioncount;
9195: my $now = time;
9196:
9197: my $check_students = 1;
9198: my $only_students = 0;
9199: if (ref($possible_roles) eq 'ARRAY') {
9200: if (grep(/^st$/,@{$possible_roles})) {
9201: if (@{$possible_roles} == 1) {
9202: $only_students = 1;
9203: }
9204: } else {
9205: $check_students = 0;
9206: }
9207: }
9208:
9209: if ($check_students) {
9210: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9211: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9212: my $status_index = &Apache::loncoursedata::CL_STATUS();
9213: my $start_index = &Apache::loncoursedata::CL_START();
9214: my $end_index = &Apache::loncoursedata::CL_END();
9215: my $status;
9216: while (my ($student,$data) = each(%$classlist)) {
9217: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9218: $data->[$status_index],
9219: $data->[$start_index],
9220: $data->[$end_index]);
9221: if ($stu_status eq 'Active') {
9222: $status = 'active';
9223: } elsif ($end < $now) {
9224: $status = 'previous';
9225: } elsif ($start > $now) {
9226: $status = 'future';
9227: }
9228: if ($section ne '-1' && $section !~ /^\s*$/) {
9229: if ((!defined($possible_status)) || (($status ne '') &&
9230: (grep/^\Q$status\E$/,@{$possible_status}))) {
9231: $sectioncount{$section}++;
9232: }
9233: }
9234: }
9235: }
9236: if ($only_students) {
9237: return %sectioncount;
9238: }
9239: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9240: foreach my $user (sort(keys(%courseroles))) {
9241: if ($user !~ /^(\w{2})/) { next; }
9242: my ($role) = ($user =~ /^(\w{2})/);
9243: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9244: my ($section,$status);
9245: if ($role eq 'cr' &&
9246: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9247: $section=$1;
9248: }
9249: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9250: if (!defined($section) || $section eq '-1') { next; }
9251: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9252: if ($end == -1 && $start == -1) {
9253: next; #deleted role
9254: }
9255: if (!defined($possible_status)) {
9256: $sectioncount{$section}++;
9257: } else {
9258: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9259: $status = 'active';
9260: } elsif ($end < $now) {
9261: $status = 'future';
9262: } elsif ($start > $now) {
9263: $status = 'previous';
9264: }
9265: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9266: $sectioncount{$section}++;
9267: }
9268: }
9269: }
9270: return %sectioncount;
9271: }
9272:
9273: ###############################################
9274:
9275: =pod
9276:
9277: =item * &get_course_users()
9278:
9279: Retrieves usernames:domains for users in the specified course
9280: with specific role(s), and access status.
9281:
9282: Incoming parameters:
9283: 1. course domain
9284: 2. course number
9285: 3. access status: users must have - either active,
9286: previous, future, or all.
9287: 4. reference to array of permissible roles
9288: 5. reference to array of section restrictions (optional)
9289: 6. reference to results object (hash of hashes).
9290: 7. reference to optional userdata hash
9291: 8. reference to optional statushash
9292: 9. flag if privileged users (except those set to unhide in
9293: course settings) should be excluded
9294: Keys of top level results hash are roles.
9295: Keys of inner hashes are username:domain, with
9296: values set to access type.
9297: Optional userdata hash returns an array with arguments in the
9298: same order as loncoursedata::get_classlist() for student data.
9299:
9300: Optional statushash returns
9301:
9302: Entries for end, start, section and status are blank because
9303: of the possibility of multiple values for non-student roles.
9304:
9305: =cut
9306:
9307: ###############################################
9308:
9309: sub get_course_users {
9310: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9311: my %idx = ();
9312: my %seclists;
9313:
9314: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9315: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9316: $idx{end} = &Apache::loncoursedata::CL_END();
9317: $idx{start} = &Apache::loncoursedata::CL_START();
9318: $idx{id} = &Apache::loncoursedata::CL_ID();
9319: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9320: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9321: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9322:
9323: if (grep(/^st$/,@{$roles})) {
9324: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9325: my $now = time;
9326: foreach my $student (keys(%{$classlist})) {
9327: my $match = 0;
9328: my $secmatch = 0;
9329: my $section = $$classlist{$student}[$idx{section}];
9330: my $status = $$classlist{$student}[$idx{status}];
9331: if ($section eq '') {
9332: $section = 'none';
9333: }
9334: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9335: if (grep(/^all$/,@{$sections})) {
9336: $secmatch = 1;
9337: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9338: if (grep(/^none$/,@{$sections})) {
9339: $secmatch = 1;
9340: }
9341: } else {
9342: if (grep(/^\Q$section\E$/,@{$sections})) {
9343: $secmatch = 1;
9344: }
9345: }
9346: if (!$secmatch) {
9347: next;
9348: }
9349: }
9350: if (defined($$types{'active'})) {
9351: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9352: push(@{$$users{st}{$student}},'active');
9353: $match = 1;
9354: }
9355: }
9356: if (defined($$types{'previous'})) {
9357: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9358: push(@{$$users{st}{$student}},'previous');
9359: $match = 1;
9360: }
9361: }
9362: if (defined($$types{'future'})) {
9363: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9364: push(@{$$users{st}{$student}},'future');
9365: $match = 1;
9366: }
9367: }
9368: if ($match) {
9369: push(@{$seclists{$student}},$section);
9370: if (ref($userdata) eq 'HASH') {
9371: $$userdata{$student} = $$classlist{$student};
9372: }
9373: if (ref($statushash) eq 'HASH') {
9374: $statushash->{$student}{'st'}{$section} = $status;
9375: }
9376: }
9377: }
9378: }
9379: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9380: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9381: my $now = time;
9382: my %displaystatus = ( previous => 'Expired',
9383: active => 'Active',
9384: future => 'Future',
9385: );
9386: my (%nothide,@possdoms);
9387: if ($hidepriv) {
9388: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9389: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9390: if ($user !~ /:/) {
9391: $nothide{join(':',split(/[\@]/,$user))}=1;
9392: } else {
9393: $nothide{$user} = 1;
9394: }
9395: }
9396: my @possdoms = ($cdom);
9397: if ($coursehash{'checkforpriv'}) {
9398: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9399: }
9400: }
9401: foreach my $person (sort(keys(%coursepersonnel))) {
9402: my $match = 0;
9403: my $secmatch = 0;
9404: my $status;
9405: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9406: $user =~ s/:$//;
9407: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9408: if ($end == -1 || $start == -1) {
9409: next;
9410: }
9411: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9412: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9413: my ($uname,$udom) = split(/:/,$user);
9414: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9415: if (grep(/^all$/,@{$sections})) {
9416: $secmatch = 1;
9417: } elsif ($usec eq '') {
9418: if (grep(/^none$/,@{$sections})) {
9419: $secmatch = 1;
9420: }
9421: } else {
9422: if (grep(/^\Q$usec\E$/,@{$sections})) {
9423: $secmatch = 1;
9424: }
9425: }
9426: if (!$secmatch) {
9427: next;
9428: }
9429: }
9430: if ($usec eq '') {
9431: $usec = 'none';
9432: }
9433: if ($uname ne '' && $udom ne '') {
9434: if ($hidepriv) {
9435: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9436: (!$nothide{$uname.':'.$udom})) {
9437: next;
9438: }
9439: }
9440: if ($end > 0 && $end < $now) {
9441: $status = 'previous';
9442: } elsif ($start > $now) {
9443: $status = 'future';
9444: } else {
9445: $status = 'active';
9446: }
9447: foreach my $type (keys(%{$types})) {
9448: if ($status eq $type) {
9449: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9450: push(@{$$users{$role}{$user}},$type);
9451: }
9452: $match = 1;
9453: }
9454: }
9455: if (($match) && (ref($userdata) eq 'HASH')) {
9456: if (!exists($$userdata{$uname.':'.$udom})) {
9457: &get_user_info($udom,$uname,\%idx,$userdata);
9458: }
9459: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9460: push(@{$seclists{$uname.':'.$udom}},$usec);
9461: }
9462: if (ref($statushash) eq 'HASH') {
9463: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9464: }
9465: }
9466: }
9467: }
9468: }
9469: if (grep(/^ow$/,@{$roles})) {
9470: if ((defined($cdom)) && (defined($cnum))) {
9471: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9472: if ( defined($csettings{'internal.courseowner'}) ) {
9473: my $owner = $csettings{'internal.courseowner'};
9474: next if ($owner eq '');
9475: my ($ownername,$ownerdom);
9476: if ($owner =~ /^([^:]+):([^:]+)$/) {
9477: $ownername = $1;
9478: $ownerdom = $2;
9479: } else {
9480: $ownername = $owner;
9481: $ownerdom = $cdom;
9482: $owner = $ownername.':'.$ownerdom;
9483: }
9484: @{$$users{'ow'}{$owner}} = 'any';
9485: if (defined($userdata) &&
9486: !exists($$userdata{$owner})) {
9487: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9488: if (!grep(/^none$/,@{$seclists{$owner}})) {
9489: push(@{$seclists{$owner}},'none');
9490: }
9491: if (ref($statushash) eq 'HASH') {
9492: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9493: }
9494: }
9495: }
9496: }
9497: }
9498: foreach my $user (keys(%seclists)) {
9499: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9500: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9501: }
9502: }
9503: return;
9504: }
9505:
9506: sub get_user_info {
9507: my ($udom,$uname,$idx,$userdata) = @_;
9508: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9509: &plainname($uname,$udom,'lastname');
9510: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9511: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9512: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9513: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9514: return;
9515: }
9516:
9517: ###############################################
9518:
9519: =pod
9520:
9521: =item * &get_user_quota()
9522:
9523: Retrieves quota assigned for storage of user files.
9524: Default is to report quota for portfolio files.
9525:
9526: Incoming parameters:
9527: 1. user's username
9528: 2. user's domain
9529: 3. quota name - portfolio, author, or course
9530: (if no quota name provided, defaults to portfolio).
9531: 4. crstype - official, unofficial, textbook or community, if quota name is
9532: course
9533:
9534: Returns:
9535: 1. Disk quota (in MB) assigned to student.
9536: 2. (Optional) Type of setting: custom or default
9537: (individually assigned or default for user's
9538: institutional status).
9539: 3. (Optional) - User's institutional status (e.g., faculty, staff
9540: or student - types as defined in localenroll::inst_usertypes
9541: for user's domain, which determines default quota for user.
9542: 4. (Optional) - Default quota which would apply to the user.
9543:
9544: If a value has been stored in the user's environment,
9545: it will return that, otherwise it returns the maximal default
9546: defined for the user's institutional status(es) in the domain.
9547:
9548: =cut
9549:
9550: ###############################################
9551:
9552:
9553: sub get_user_quota {
9554: my ($uname,$udom,$quotaname,$crstype) = @_;
9555: my ($quota,$quotatype,$settingstatus,$defquota);
9556: if (!defined($udom)) {
9557: $udom = $env{'user.domain'};
9558: }
9559: if (!defined($uname)) {
9560: $uname = $env{'user.name'};
9561: }
9562: if (($udom eq '' || $uname eq '') ||
9563: ($udom eq 'public') && ($uname eq 'public')) {
9564: $quota = 0;
9565: $quotatype = 'default';
9566: $defquota = 0;
9567: } else {
9568: my $inststatus;
9569: if ($quotaname eq 'course') {
9570: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9571: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9572: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9573: } else {
9574: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9575: $quota = $cenv{'internal.uploadquota'};
9576: }
9577: } else {
9578: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9579: if ($quotaname eq 'author') {
9580: $quota = $env{'environment.authorquota'};
9581: } else {
9582: $quota = $env{'environment.portfolioquota'};
9583: }
9584: $inststatus = $env{'environment.inststatus'};
9585: } else {
9586: my %userenv =
9587: &Apache::lonnet::get('environment',['portfolioquota',
9588: 'authorquota','inststatus'],$udom,$uname);
9589: my ($tmp) = keys(%userenv);
9590: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9591: if ($quotaname eq 'author') {
9592: $quota = $userenv{'authorquota'};
9593: } else {
9594: $quota = $userenv{'portfolioquota'};
9595: }
9596: $inststatus = $userenv{'inststatus'};
9597: } else {
9598: undef(%userenv);
9599: }
9600: }
9601: }
9602: if ($quota eq '' || wantarray) {
9603: if ($quotaname eq 'course') {
9604: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9605: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9606: ($crstype eq 'community') || ($crstype eq 'textbook')) {
9607: $defquota = $domdefs{$crstype.'quota'};
9608: }
9609: if ($defquota eq '') {
9610: $defquota = 500;
9611: }
9612: } else {
9613: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9614: }
9615: if ($quota eq '') {
9616: $quota = $defquota;
9617: $quotatype = 'default';
9618: } else {
9619: $quotatype = 'custom';
9620: }
9621: }
9622: }
9623: if (wantarray) {
9624: return ($quota,$quotatype,$settingstatus,$defquota);
9625: } else {
9626: return $quota;
9627: }
9628: }
9629:
9630: ###############################################
9631:
9632: =pod
9633:
9634: =item * &default_quota()
9635:
9636: Retrieves default quota assigned for storage of user portfolio files,
9637: given an (optional) user's institutional status.
9638:
9639: Incoming parameters:
9640:
9641: 1. domain
9642: 2. (Optional) institutional status(es). This is a : separated list of
9643: status types (e.g., faculty, staff, student etc.)
9644: which apply to the user for whom the default is being retrieved.
9645: If the institutional status string in undefined, the domain
9646: default quota will be returned.
9647: 3. quota name - portfolio, author, or course
9648: (if no quota name provided, defaults to portfolio).
9649:
9650: Returns:
9651:
9652: 1. Default disk quota (in MB) for user portfolios in the domain.
9653: 2. (Optional) institutional type which determined the value of the
9654: default quota.
9655:
9656: If a value has been stored in the domain's configuration db,
9657: it will return that, otherwise it returns 20 (for backwards
9658: compatibility with domains which have not set up a configuration
9659: db file; the original statically defined portfolio quota was 20 MB).
9660:
9661: If the user's status includes multiple types (e.g., staff and student),
9662: the largest default quota which applies to the user determines the
9663: default quota returned.
9664:
9665: =cut
9666:
9667: ###############################################
9668:
9669:
9670: sub default_quota {
9671: my ($udom,$inststatus,$quotaname) = @_;
9672: my ($defquota,$settingstatus);
9673: my %quotahash = &Apache::lonnet::get_dom('configuration',
9674: ['quotas'],$udom);
9675: my $key = 'defaultquota';
9676: if ($quotaname eq 'author') {
9677: $key = 'authorquota';
9678: }
9679: if (ref($quotahash{'quotas'}) eq 'HASH') {
9680: if ($inststatus ne '') {
9681: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
9682: foreach my $item (@statuses) {
9683: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9684: if ($quotahash{'quotas'}{$key}{$item} ne '') {
9685: if ($defquota eq '') {
9686: $defquota = $quotahash{'quotas'}{$key}{$item};
9687: $settingstatus = $item;
9688: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
9689: $defquota = $quotahash{'quotas'}{$key}{$item};
9690: $settingstatus = $item;
9691: }
9692: }
9693: } elsif ($key eq 'defaultquota') {
9694: if ($quotahash{'quotas'}{$item} ne '') {
9695: if ($defquota eq '') {
9696: $defquota = $quotahash{'quotas'}{$item};
9697: $settingstatus = $item;
9698: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
9699: $defquota = $quotahash{'quotas'}{$item};
9700: $settingstatus = $item;
9701: }
9702: }
9703: }
9704: }
9705: }
9706: if ($defquota eq '') {
9707: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9708: $defquota = $quotahash{'quotas'}{$key}{'default'};
9709: } elsif ($key eq 'defaultquota') {
9710: $defquota = $quotahash{'quotas'}{'default'};
9711: }
9712: $settingstatus = 'default';
9713: if ($defquota eq '') {
9714: if ($quotaname eq 'author') {
9715: $defquota = 500;
9716: }
9717: }
9718: }
9719: } else {
9720: $settingstatus = 'default';
9721: if ($quotaname eq 'author') {
9722: $defquota = 500;
9723: } else {
9724: $defquota = 20;
9725: }
9726: }
9727: if (wantarray) {
9728: return ($defquota,$settingstatus);
9729: } else {
9730: return $defquota;
9731: }
9732: }
9733:
9734: ###############################################
9735:
9736: =pod
9737:
9738: =item * &excess_filesize_warning()
9739:
9740: Returns warning message if upload of file to authoring space, or copying
9741: of existing file within authoring space will cause quota for the authoring
9742: space to be exceeded.
9743:
9744: Same, if upload of a file directly to a course/community via Course Editor
9745: will cause quota for uploaded content for the course to be exceeded.
9746:
9747: Inputs: 7
9748: 1. username or coursenum
9749: 2. domain
9750: 3. context ('author' or 'course')
9751: 4. filename of file for which action is being requested
9752: 5. filesize (kB) of file
9753: 6. action being taken: copy or upload.
9754: 7. quotatype (in course context -- official, unofficial, community or textbook).
9755:
9756: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9757: otherwise return null.
9758:
9759: =back
9760:
9761: =cut
9762:
9763: sub excess_filesize_warning {
9764: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9765: my $current_disk_usage = 0;
9766: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9767: if ($context eq 'author') {
9768: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9769: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9770: } else {
9771: foreach my $subdir ('docs','supplemental') {
9772: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9773: }
9774: }
9775: $disk_quota = int($disk_quota * 1000);
9776: if (($current_disk_usage + $filesize) > $disk_quota) {
9777: return '<p class="LC_warning">'.
9778: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9779: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9780: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9781: $disk_quota,$current_disk_usage).
9782: '</p>';
9783: }
9784: return;
9785: }
9786:
9787: ###############################################
9788:
9789:
9790: sub get_secgrprole_info {
9791: my ($cdom,$cnum,$needroles,$type) = @_;
9792: my %sections_count = &get_sections($cdom,$cnum);
9793: my @sections = (sort {$a <=> $b} keys(%sections_count));
9794: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9795: my @groups = sort(keys(%curr_groups));
9796: my $allroles = [];
9797: my $rolehash;
9798: my $accesshash = {
9799: active => 'Currently has access',
9800: future => 'Will have future access',
9801: previous => 'Previously had access',
9802: };
9803: if ($needroles) {
9804: $rolehash = {'all' => 'all'};
9805: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9806: if (&Apache::lonnet::error(%user_roles)) {
9807: undef(%user_roles);
9808: }
9809: foreach my $item (keys(%user_roles)) {
9810: my ($role)=split(/\:/,$item,2);
9811: if ($role eq 'cr') { next; }
9812: if ($role =~ /^cr/) {
9813: $$rolehash{$role} = (split('/',$role))[3];
9814: } else {
9815: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9816: }
9817: }
9818: foreach my $key (sort(keys(%{$rolehash}))) {
9819: push(@{$allroles},$key);
9820: }
9821: push (@{$allroles},'st');
9822: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9823: }
9824: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9825: }
9826:
9827: sub user_picker {
9828: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
9829: my $currdom = $dom;
9830: my @alldoms = &Apache::lonnet::all_domains();
9831: if (@alldoms == 1) {
9832: my %domsrch = &Apache::lonnet::get_dom('configuration',
9833: ['directorysrch'],$alldoms[0]);
9834: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
9835: my $showdom = $domdesc;
9836: if ($showdom eq '') {
9837: $showdom = $dom;
9838: }
9839: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
9840: if ((!$domsrch{'directorysrch'}{'available'}) &&
9841: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
9842: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
9843: }
9844: }
9845: }
9846: my %curr_selected = (
9847: srchin => 'dom',
9848: srchby => 'lastname',
9849: );
9850: my $srchterm;
9851: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9852: if ($srch->{'srchby'} ne '') {
9853: $curr_selected{'srchby'} = $srch->{'srchby'};
9854: }
9855: if ($srch->{'srchin'} ne '') {
9856: $curr_selected{'srchin'} = $srch->{'srchin'};
9857: }
9858: if ($srch->{'srchtype'} ne '') {
9859: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9860: }
9861: if ($srch->{'srchdomain'} ne '') {
9862: $currdom = $srch->{'srchdomain'};
9863: }
9864: $srchterm = $srch->{'srchterm'};
9865: }
9866: my %html_lt=&Apache::lonlocal::texthash(
9867: 'usr' => 'Search criteria',
9868: 'doma' => 'Domain/institution to search',
9869: 'uname' => 'username',
9870: 'lastname' => 'last name',
9871: 'lastfirst' => 'last name, first name',
9872: 'crs' => 'in this course',
9873: 'dom' => 'in selected LON-CAPA domain',
9874: 'alc' => 'all LON-CAPA',
9875: 'instd' => 'in institutional directory for selected domain',
9876: 'exact' => 'is',
9877: 'contains' => 'contains',
9878: 'begins' => 'begins with',
9879: );
9880: my %js_lt=&Apache::lonlocal::texthash(
9881: 'youm' => "You must include some text to search for.",
9882: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9883: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9884: 'yomc' => "You must choose a domain when using an institutional directory search.",
9885: 'ymcd' => "You must choose a domain when using a domain search.",
9886: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9887: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9888: 'thfo' => "The following need to be corrected before the search can be run:",
9889: );
9890: &html_escape(\%html_lt);
9891: &js_escape(\%js_lt);
9892: my $domform;
9893: my $allow_blank = 1;
9894: if ($fixeddom) {
9895: $allow_blank = 0;
9896: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
9897: } else {
9898: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
9899: }
9900: my $srchinsel = ' <select name="srchin">';
9901:
9902: my @srchins = ('crs','dom','alc','instd');
9903:
9904: foreach my $option (@srchins) {
9905: # FIXME 'alc' option unavailable until
9906: # loncreateuser::print_user_query_page()
9907: # has been completed.
9908: next if ($option eq 'alc');
9909: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9910: next if ($option eq 'crs' && !$env{'request.course.id'});
9911: next if (($option eq 'instd') && ($noinstd));
9912: if ($curr_selected{'srchin'} eq $option) {
9913: $srchinsel .= '
9914: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9915: } else {
9916: $srchinsel .= '
9917: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9918: }
9919: }
9920: $srchinsel .= "\n </select>\n";
9921:
9922: my $srchbysel = ' <select name="srchby">';
9923: foreach my $option ('lastname','lastfirst','uname') {
9924: if ($curr_selected{'srchby'} eq $option) {
9925: $srchbysel .= '
9926: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9927: } else {
9928: $srchbysel .= '
9929: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9930: }
9931: }
9932: $srchbysel .= "\n </select>\n";
9933:
9934: my $srchtypesel = ' <select name="srchtype">';
9935: foreach my $option ('begins','contains','exact') {
9936: if ($curr_selected{'srchtype'} eq $option) {
9937: $srchtypesel .= '
9938: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9939: } else {
9940: $srchtypesel .= '
9941: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9942: }
9943: }
9944: $srchtypesel .= "\n </select>\n";
9945:
9946: my ($newuserscript,$new_user_create);
9947: my $context_dom = $env{'request.role.domain'};
9948: if ($context eq 'requestcrs') {
9949: if ($env{'form.coursedom'} ne '') {
9950: $context_dom = $env{'form.coursedom'};
9951: }
9952: }
9953: if ($forcenewuser) {
9954: if (ref($srch) eq 'HASH') {
9955: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9956: if ($cancreate) {
9957: $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>';
9958: } else {
9959: my $helplink = 'javascript:helpMenu('."'display'".')';
9960: my %usertypetext = (
9961: official => 'institutional',
9962: unofficial => 'non-institutional',
9963: );
9964: $new_user_create = '<p class="LC_warning">'
9965: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9966: .' '
9967: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9968: ,'<a href="'.$helplink.'">','</a>')
9969: .'</p><br />';
9970: }
9971: }
9972: }
9973:
9974: $newuserscript = <<"ENDSCRIPT";
9975:
9976: function setSearch(createnew,callingForm) {
9977: if (createnew == 1) {
9978: for (var i=0; i<callingForm.srchby.length; i++) {
9979: if (callingForm.srchby.options[i].value == 'uname') {
9980: callingForm.srchby.selectedIndex = i;
9981: }
9982: }
9983: for (var i=0; i<callingForm.srchin.length; i++) {
9984: if ( callingForm.srchin.options[i].value == 'dom') {
9985: callingForm.srchin.selectedIndex = i;
9986: }
9987: }
9988: for (var i=0; i<callingForm.srchtype.length; i++) {
9989: if (callingForm.srchtype.options[i].value == 'exact') {
9990: callingForm.srchtype.selectedIndex = i;
9991: }
9992: }
9993: for (var i=0; i<callingForm.srchdomain.length; i++) {
9994: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9995: callingForm.srchdomain.selectedIndex = i;
9996: }
9997: }
9998: }
9999: }
10000: ENDSCRIPT
10001:
10002: }
10003:
10004: my $output = <<"END_BLOCK";
10005: <script type="text/javascript">
10006: // <![CDATA[
10007: function validateEntry(callingForm) {
10008:
10009: var checkok = 1;
10010: var srchin;
10011: for (var i=0; i<callingForm.srchin.length; i++) {
10012: if ( callingForm.srchin[i].checked ) {
10013: srchin = callingForm.srchin[i].value;
10014: }
10015: }
10016:
10017: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10018: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10019: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10020: var srchterm = callingForm.srchterm.value;
10021: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10022: var msg = "";
10023:
10024: if (srchterm == "") {
10025: checkok = 0;
10026: msg += "$js_lt{'youm'}\\n";
10027: }
10028:
10029: if (srchtype== 'begins') {
10030: if (srchterm.length < 2) {
10031: checkok = 0;
10032: msg += "$js_lt{'thte'}\\n";
10033: }
10034: }
10035:
10036: if (srchtype== 'contains') {
10037: if (srchterm.length < 3) {
10038: checkok = 0;
10039: msg += "$js_lt{'thet'}\\n";
10040: }
10041: }
10042: if (srchin == 'instd') {
10043: if (srchdomain == '') {
10044: checkok = 0;
10045: msg += "$js_lt{'yomc'}\\n";
10046: }
10047: }
10048: if (srchin == 'dom') {
10049: if (srchdomain == '') {
10050: checkok = 0;
10051: msg += "$js_lt{'ymcd'}\\n";
10052: }
10053: }
10054: if (srchby == 'lastfirst') {
10055: if (srchterm.indexOf(",") == -1) {
10056: checkok = 0;
10057: msg += "$js_lt{'whus'}\\n";
10058: }
10059: if (srchterm.indexOf(",") == srchterm.length -1) {
10060: checkok = 0;
10061: msg += "$js_lt{'whse'}\\n";
10062: }
10063: }
10064: if (checkok == 0) {
10065: alert("$js_lt{'thfo'}\\n"+msg);
10066: return;
10067: }
10068: if (checkok == 1) {
10069: callingForm.submit();
10070: }
10071: }
10072:
10073: $newuserscript
10074:
10075: // ]]>
10076: </script>
10077:
10078: $new_user_create
10079:
10080: END_BLOCK
10081:
10082: $output .= &Apache::lonhtmlcommon::start_pick_box().
10083: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10084: $domform.
10085: &Apache::lonhtmlcommon::row_closure().
10086: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10087: $srchbysel.
10088: $srchtypesel.
10089: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10090: $srchinsel.
10091: &Apache::lonhtmlcommon::row_closure(1).
10092: &Apache::lonhtmlcommon::end_pick_box().
10093: '<br />';
10094: return ($output,1);
10095: }
10096:
10097: sub user_rule_check {
10098: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10099: my ($response,%inst_response);
10100: if (ref($usershash) eq 'HASH') {
10101: if (keys(%{$usershash}) > 1) {
10102: my (%by_username,%by_id,%userdoms);
10103: my $checkid;
10104: if (ref($checks) eq 'HASH') {
10105: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10106: $checkid = 1;
10107: }
10108: }
10109: foreach my $user (keys(%{$usershash})) {
10110: my ($uname,$udom) = split(/:/,$user);
10111: if ($checkid) {
10112: if (ref($usershash->{$user}) eq 'HASH') {
10113: if ($usershash->{$user}->{'id'} ne '') {
10114: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10115: $userdoms{$udom} = 1;
10116: if (ref($inst_results) eq 'HASH') {
10117: $inst_results->{$uname.':'.$udom} = {};
10118: }
10119: }
10120: }
10121: } else {
10122: $by_username{$udom}{$uname} = 1;
10123: $userdoms{$udom} = 1;
10124: if (ref($inst_results) eq 'HASH') {
10125: $inst_results->{$uname.':'.$udom} = {};
10126: }
10127: }
10128: }
10129: foreach my $udom (keys(%userdoms)) {
10130: if (!$got_rules->{$udom}) {
10131: my %domconfig = &Apache::lonnet::get_dom('configuration',
10132: ['usercreation'],$udom);
10133: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10134: foreach my $item ('username','id') {
10135: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10136: $$curr_rules{$udom}{$item} =
10137: $domconfig{'usercreation'}{$item.'_rule'};
10138: }
10139: }
10140: }
10141: $got_rules->{$udom} = 1;
10142: }
10143: }
10144: if ($checkid) {
10145: foreach my $udom (keys(%by_id)) {
10146: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10147: if ($outcome eq 'ok') {
10148: foreach my $id (keys(%{$by_id{$udom}})) {
10149: my $uname = $by_id{$udom}{$id};
10150: $inst_response{$uname.':'.$udom} = $outcome;
10151: }
10152: if (ref($results) eq 'HASH') {
10153: foreach my $uname (keys(%{$results})) {
10154: if (exists($inst_response{$uname.':'.$udom})) {
10155: $inst_response{$uname.':'.$udom} = $outcome;
10156: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10157: }
10158: }
10159: }
10160: }
10161: }
10162: } else {
10163: foreach my $udom (keys(%by_username)) {
10164: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10165: if ($outcome eq 'ok') {
10166: foreach my $uname (keys(%{$by_username{$udom}})) {
10167: $inst_response{$uname.':'.$udom} = $outcome;
10168: }
10169: if (ref($results) eq 'HASH') {
10170: foreach my $uname (keys(%{$results})) {
10171: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10172: }
10173: }
10174: }
10175: }
10176: }
10177: } elsif (keys(%{$usershash}) == 1) {
10178: my $user = (keys(%{$usershash}))[0];
10179: my ($uname,$udom) = split(/:/,$user);
10180: if (($udom ne '') && ($uname ne '')) {
10181: if (ref($usershash->{$user}) eq 'HASH') {
10182: if (ref($checks) eq 'HASH') {
10183: if (defined($checks->{'username'})) {
10184: ($inst_response{$user},%{$inst_results->{$user}}) =
10185: &Apache::lonnet::get_instuser($udom,$uname);
10186: } elsif (defined($checks->{'id'})) {
10187: if ($usershash->{$user}->{'id'} ne '') {
10188: ($inst_response{$user},%{$inst_results->{$user}}) =
10189: &Apache::lonnet::get_instuser($udom,undef,
10190: $usershash->{$user}->{'id'});
10191: } else {
10192: ($inst_response{$user},%{$inst_results->{$user}}) =
10193: &Apache::lonnet::get_instuser($udom,$uname);
10194: }
10195: }
10196: } else {
10197: ($inst_response{$user},%{$inst_results->{$user}}) =
10198: &Apache::lonnet::get_instuser($udom,$uname);
10199: return;
10200: }
10201: if (!$got_rules->{$udom}) {
10202: my %domconfig = &Apache::lonnet::get_dom('configuration',
10203: ['usercreation'],$udom);
10204: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10205: foreach my $item ('username','id') {
10206: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10207: $$curr_rules{$udom}{$item} =
10208: $domconfig{'usercreation'}{$item.'_rule'};
10209: }
10210: }
10211: }
10212: $got_rules->{$udom} = 1;
10213: }
10214: }
10215: } else {
10216: return;
10217: }
10218: } else {
10219: return;
10220: }
10221: foreach my $user (keys(%{$usershash})) {
10222: my ($uname,$udom) = split(/:/,$user);
10223: next if (($udom eq '') || ($uname eq ''));
10224: my $id;
10225: if (ref($inst_results) eq 'HASH') {
10226: if (ref($inst_results->{$user}) eq 'HASH') {
10227: $id = $inst_results->{$user}->{'id'};
10228: }
10229: }
10230: if ($id eq '') {
10231: if (ref($usershash->{$user})) {
10232: $id = $usershash->{$user}->{'id'};
10233: }
10234: }
10235: foreach my $item (keys(%{$checks})) {
10236: if (ref($$curr_rules{$udom}) eq 'HASH') {
10237: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10238: if (@{$$curr_rules{$udom}{$item}} > 0) {
10239: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10240: $$curr_rules{$udom}{$item});
10241: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10242: if ($rule_check{$rule}) {
10243: $$rulematch{$user}{$item} = $rule;
10244: if ($inst_response{$user} eq 'ok') {
10245: if (ref($inst_results) eq 'HASH') {
10246: if (ref($inst_results->{$user}) eq 'HASH') {
10247: if (keys(%{$inst_results->{$user}}) == 0) {
10248: $$alerts{$item}{$udom}{$uname} = 1;
10249: } elsif ($item eq 'id') {
10250: if ($inst_results->{$user}->{'id'} eq '') {
10251: $$alerts{$item}{$udom}{$uname} = 1;
10252: }
10253: }
10254: }
10255: }
10256: }
10257: last;
10258: }
10259: }
10260: }
10261: }
10262: }
10263: }
10264: }
10265: }
10266: return;
10267: }
10268:
10269: sub user_rule_formats {
10270: my ($domain,$domdesc,$curr_rules,$check) = @_;
10271: my %text = (
10272: 'username' => 'Usernames',
10273: 'id' => 'IDs',
10274: );
10275: my $output;
10276: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10277: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10278: if (@{$ruleorder} > 0) {
10279: $output = '<br />'.
10280: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10281: '<span class="LC_cusr_emph">','</span>',$domdesc).
10282: ' <ul>';
10283: foreach my $rule (@{$ruleorder}) {
10284: if (ref($curr_rules) eq 'ARRAY') {
10285: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10286: if (ref($rules->{$rule}) eq 'HASH') {
10287: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10288: $rules->{$rule}{'desc'}.'</li>';
10289: }
10290: }
10291: }
10292: }
10293: $output .= '</ul>';
10294: }
10295: }
10296: return $output;
10297: }
10298:
10299: sub instrule_disallow_msg {
10300: my ($checkitem,$domdesc,$count,$mode) = @_;
10301: my $response;
10302: my %text = (
10303: item => 'username',
10304: items => 'usernames',
10305: match => 'matches',
10306: do => 'does',
10307: action => 'a username',
10308: one => 'one',
10309: );
10310: if ($count > 1) {
10311: $text{'item'} = 'usernames';
10312: $text{'match'} ='match';
10313: $text{'do'} = 'do';
10314: $text{'action'} = 'usernames',
10315: $text{'one'} = 'ones';
10316: }
10317: if ($checkitem eq 'id') {
10318: $text{'items'} = 'IDs';
10319: $text{'item'} = 'ID';
10320: $text{'action'} = 'an ID';
10321: if ($count > 1) {
10322: $text{'item'} = 'IDs';
10323: $text{'action'} = 'IDs';
10324: }
10325: }
10326: $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 />';
10327: if ($mode eq 'upload') {
10328: if ($checkitem eq 'username') {
10329: $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'}.");
10330: } elsif ($checkitem eq 'id') {
10331: $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.");
10332: }
10333: } elsif ($mode eq 'selfcreate') {
10334: if ($checkitem eq 'id') {
10335: $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.");
10336: }
10337: } else {
10338: if ($checkitem eq 'username') {
10339: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10340: } elsif ($checkitem eq 'id') {
10341: $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.");
10342: }
10343: }
10344: return $response;
10345: }
10346:
10347: sub personal_data_fieldtitles {
10348: my %fieldtitles = &Apache::lonlocal::texthash (
10349: id => 'Student/Employee ID',
10350: permanentemail => 'E-mail address',
10351: lastname => 'Last Name',
10352: firstname => 'First Name',
10353: middlename => 'Middle Name',
10354: generation => 'Generation',
10355: gen => 'Generation',
10356: inststatus => 'Affiliation',
10357: );
10358: return %fieldtitles;
10359: }
10360:
10361: sub sorted_inst_types {
10362: my ($dom) = @_;
10363: my ($usertypes,$order);
10364: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10365: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10366: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10367: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10368: } else {
10369: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10370: }
10371: my $othertitle = &mt('All users');
10372: if ($env{'request.course.id'}) {
10373: $othertitle = &mt('Any users');
10374: }
10375: my @types;
10376: if (ref($order) eq 'ARRAY') {
10377: @types = @{$order};
10378: }
10379: if (@types == 0) {
10380: if (ref($usertypes) eq 'HASH') {
10381: @types = sort(keys(%{$usertypes}));
10382: }
10383: }
10384: if (keys(%{$usertypes}) > 0) {
10385: $othertitle = &mt('Other users');
10386: }
10387: return ($othertitle,$usertypes,\@types);
10388: }
10389:
10390: sub get_institutional_codes {
10391: my ($settings,$allcourses,$LC_code) = @_;
10392: # Get complete list of course sections to update
10393: my @currsections = ();
10394: my @currxlists = ();
10395: my $coursecode = $$settings{'internal.coursecode'};
10396:
10397: if ($$settings{'internal.sectionnums'} ne '') {
10398: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10399: }
10400:
10401: if ($$settings{'internal.crosslistings'} ne '') {
10402: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10403: }
10404:
10405: if (@currxlists > 0) {
10406: foreach (@currxlists) {
10407: if (m/^([^:]+):(\w*)$/) {
10408: unless (grep/^$1$/,@{$allcourses}) {
10409: push(@{$allcourses},$1);
10410: $$LC_code{$1} = $2;
10411: }
10412: }
10413: }
10414: }
10415:
10416: if (@currsections > 0) {
10417: foreach (@currsections) {
10418: if (m/^(\w+):(\w*)$/) {
10419: my $sec = $coursecode.$1;
10420: my $lc_sec = $2;
10421: unless (grep/^$sec$/,@{$allcourses}) {
10422: push(@{$allcourses},$sec);
10423: $$LC_code{$sec} = $lc_sec;
10424: }
10425: }
10426: }
10427: }
10428: return;
10429: }
10430:
10431: sub get_standard_codeitems {
10432: return ('Year','Semester','Department','Number','Section');
10433: }
10434:
10435: =pod
10436:
10437: =head1 Slot Helpers
10438:
10439: =over 4
10440:
10441: =item * sorted_slots()
10442:
10443: Sorts an array of slot names in order of an optional sort key,
10444: default sort is by slot start time (earliest first).
10445:
10446: Inputs:
10447:
10448: =over 4
10449:
10450: slotsarr - Reference to array of unsorted slot names.
10451:
10452: slots - Reference to hash of hash, where outer hash keys are slot names.
10453:
10454: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10455:
10456: =back
10457:
10458: Returns:
10459:
10460: =over 4
10461:
10462: sorted - An array of slot names sorted by a specified sort key
10463: (default sort key is start time of the slot).
10464:
10465: =back
10466:
10467: =cut
10468:
10469:
10470: sub sorted_slots {
10471: my ($slotsarr,$slots,$sortkey) = @_;
10472: if ($sortkey eq '') {
10473: $sortkey = 'starttime';
10474: }
10475: my @sorted;
10476: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10477: @sorted =
10478: sort {
10479: if (ref($slots->{$a}) && ref($slots->{$b})) {
10480: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10481: }
10482: if (ref($slots->{$a})) { return -1;}
10483: if (ref($slots->{$b})) { return 1;}
10484: return 0;
10485: } @{$slotsarr};
10486: }
10487: return @sorted;
10488: }
10489:
10490: =pod
10491:
10492: =item * get_future_slots()
10493:
10494: Inputs:
10495:
10496: =over 4
10497:
10498: cnum - course number
10499:
10500: cdom - course domain
10501:
10502: now - current UNIX time
10503:
10504: symb - optional symb
10505:
10506: =back
10507:
10508: Returns:
10509:
10510: =over 4
10511:
10512: sorted_reservable - ref to array of student_schedulable slots currently
10513: reservable, ordered by end date of reservation period.
10514:
10515: reservable_now - ref to hash of student_schedulable slots currently
10516: reservable.
10517:
10518: Keys in inner hash are:
10519: (a) symb: either blank or symb to which slot use is restricted.
10520: (b) endreserve: end date of reservation period.
10521: (c) uniqueperiod: start,end dates when slot is to be uniquely
10522: selected.
10523:
10524: sorted_future - ref to array of student_schedulable slots reservable in
10525: the future, ordered by start date of reservation period.
10526:
10527: future_reservable - ref to hash of student_schedulable slots reservable
10528: in the future.
10529:
10530: Keys in inner hash are:
10531: (a) symb: either blank or symb to which slot use is restricted.
10532: (b) startreserve: start date of reservation period.
10533: (c) uniqueperiod: start,end dates when slot is to be uniquely
10534: selected.
10535:
10536: =back
10537:
10538: =cut
10539:
10540: sub get_future_slots {
10541: my ($cnum,$cdom,$now,$symb) = @_;
10542: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10543: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10544: foreach my $slot (keys(%slots)) {
10545: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10546: if ($symb) {
10547: next if (($slots{$slot}->{'symb'} ne '') &&
10548: ($slots{$slot}->{'symb'} ne $symb));
10549: }
10550: if (($slots{$slot}->{'starttime'} > $now) &&
10551: ($slots{$slot}->{'endtime'} > $now)) {
10552: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10553: my $userallowed = 0;
10554: if ($slots{$slot}->{'allowedsections'}) {
10555: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10556: if (!defined($env{'request.role.sec'})
10557: && grep(/^No section assigned$/,@allowed_sec)) {
10558: $userallowed=1;
10559: } else {
10560: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10561: $userallowed=1;
10562: }
10563: }
10564: unless ($userallowed) {
10565: if (defined($env{'request.course.groups'})) {
10566: my @groups = split(/:/,$env{'request.course.groups'});
10567: foreach my $group (@groups) {
10568: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10569: $userallowed=1;
10570: last;
10571: }
10572: }
10573: }
10574: }
10575: }
10576: if ($slots{$slot}->{'allowedusers'}) {
10577: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10578: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10579: if (grep(/^\Q$user\E$/,@allowed_users)) {
10580: $userallowed = 1;
10581: }
10582: }
10583: next unless($userallowed);
10584: }
10585: my $startreserve = $slots{$slot}->{'startreserve'};
10586: my $endreserve = $slots{$slot}->{'endreserve'};
10587: my $symb = $slots{$slot}->{'symb'};
10588: my $uniqueperiod;
10589: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10590: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10591: }
10592: if (($startreserve < $now) &&
10593: (!$endreserve || $endreserve > $now)) {
10594: my $lastres = $endreserve;
10595: if (!$lastres) {
10596: $lastres = $slots{$slot}->{'starttime'};
10597: }
10598: $reservable_now{$slot} = {
10599: symb => $symb,
10600: endreserve => $lastres,
10601: uniqueperiod => $uniqueperiod,
10602: };
10603: } elsif (($startreserve > $now) &&
10604: (!$endreserve || $endreserve > $startreserve)) {
10605: $future_reservable{$slot} = {
10606: symb => $symb,
10607: startreserve => $startreserve,
10608: uniqueperiod => $uniqueperiod,
10609: };
10610: }
10611: }
10612: }
10613: my @unsorted_reservable = keys(%reservable_now);
10614: if (@unsorted_reservable > 0) {
10615: @sorted_reservable =
10616: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10617: }
10618: my @unsorted_future = keys(%future_reservable);
10619: if (@unsorted_future > 0) {
10620: @sorted_future =
10621: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10622: }
10623: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10624: }
10625:
10626: =pod
10627:
10628: =back
10629:
10630: =head1 HTTP Helpers
10631:
10632: =over 4
10633:
10634: =item * &get_unprocessed_cgi($query,$possible_names)
10635:
10636: Modify the %env hash to contain unprocessed CGI form parameters held in
10637: $query. The parameters listed in $possible_names (an array reference),
10638: will be set in $env{'form.name'} if they do not already exist.
10639:
10640: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
10641: $possible_names is an ref to an array of form element names. As an example:
10642: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10643: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10644:
10645: =cut
10646:
10647: sub get_unprocessed_cgi {
10648: my ($query,$possible_names)= @_;
10649: # $Apache::lonxml::debug=1;
10650: foreach my $pair (split(/&/,$query)) {
10651: my ($name, $value) = split(/=/,$pair);
10652: $name = &unescape($name);
10653: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10654: $value =~ tr/+/ /;
10655: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10656: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10657: }
10658: }
10659: }
10660:
10661: =pod
10662:
10663: =item * &cacheheader()
10664:
10665: returns cache-controlling header code
10666:
10667: =cut
10668:
10669: sub cacheheader {
10670: unless ($env{'request.method'} eq 'GET') { return ''; }
10671: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10672: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10673: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10674: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10675: return $output;
10676: }
10677:
10678: =pod
10679:
10680: =item * &no_cache($r)
10681:
10682: specifies header code to not have cache
10683:
10684: =cut
10685:
10686: sub no_cache {
10687: my ($r) = @_;
10688: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10689: $env{'request.method'} ne 'GET') { return ''; }
10690: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10691: $r->no_cache(1);
10692: $r->header_out("Expires" => $date);
10693: $r->header_out("Pragma" => "no-cache");
10694: }
10695:
10696: sub content_type {
10697: my ($r,$type,$charset) = @_;
10698: if ($r) {
10699: # Note that printout.pl calls this with undef for $r.
10700: &no_cache($r);
10701: }
10702: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10703: unless ($charset) {
10704: $charset=&Apache::lonlocal::current_encoding;
10705: }
10706: if ($charset) { $type.='; charset='.$charset; }
10707: if ($r) {
10708: $r->content_type($type);
10709: } else {
10710: print("Content-type: $type\n\n");
10711: }
10712: }
10713:
10714: =pod
10715:
10716: =item * &add_to_env($name,$value)
10717:
10718: adds $name to the %env hash with value
10719: $value, if $name already exists, the entry is converted to an array
10720: reference and $value is added to the array.
10721:
10722: =cut
10723:
10724: sub add_to_env {
10725: my ($name,$value)=@_;
10726: if (defined($env{$name})) {
10727: if (ref($env{$name})) {
10728: #already have multiple values
10729: push(@{ $env{$name} },$value);
10730: } else {
10731: #first time seeing multiple values, convert hash entry to an arrayref
10732: my $first=$env{$name};
10733: undef($env{$name});
10734: push(@{ $env{$name} },$first,$value);
10735: }
10736: } else {
10737: $env{$name}=$value;
10738: }
10739: }
10740:
10741: =pod
10742:
10743: =item * &get_env_multiple($name)
10744:
10745: gets $name from the %env hash, it seemlessly handles the cases where multiple
10746: values may be defined and end up as an array ref.
10747:
10748: returns an array of values
10749:
10750: =cut
10751:
10752: sub get_env_multiple {
10753: my ($name) = @_;
10754: my @values;
10755: if (defined($env{$name})) {
10756: # exists is it an array
10757: if (ref($env{$name})) {
10758: @values=@{ $env{$name} };
10759: } else {
10760: $values[0]=$env{$name};
10761: }
10762: }
10763: return(@values);
10764: }
10765:
10766: sub ask_for_embedded_content {
10767: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10768: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10769: %currsubfile,%unused,$rem);
10770: my $counter = 0;
10771: my $numnew = 0;
10772: my $numremref = 0;
10773: my $numinvalid = 0;
10774: my $numpathchg = 0;
10775: my $numexisting = 0;
10776: my $numunused = 0;
10777: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10778: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10779: my $heading = &mt('Upload embedded files');
10780: my $buttontext = &mt('Upload');
10781:
10782: if ($env{'request.course.id'}) {
10783: if ($actionurl eq '/adm/dependencies') {
10784: $navmap = Apache::lonnavmaps::navmap->new();
10785: }
10786: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10787: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10788: }
10789: if (($actionurl eq '/adm/portfolio') ||
10790: ($actionurl eq '/adm/coursegrp_portfolio')) {
10791: my $current_path='/';
10792: if ($env{'form.currentpath'}) {
10793: $current_path = $env{'form.currentpath'};
10794: }
10795: if ($actionurl eq '/adm/coursegrp_portfolio') {
10796: $udom = $cdom;
10797: $uname = $cnum;
10798: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10799: } else {
10800: $udom = $env{'user.domain'};
10801: $uname = $env{'user.name'};
10802: $url = '/userfiles/portfolio';
10803: }
10804: $toplevel = $url.'/';
10805: $url .= $current_path;
10806: $getpropath = 1;
10807: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10808: ($actionurl eq '/adm/imsimport')) {
10809: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10810: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10811: $toplevel = $url;
10812: if ($rest ne '') {
10813: $url .= $rest;
10814: }
10815: } elsif ($actionurl eq '/adm/coursedocs') {
10816: if (ref($args) eq 'HASH') {
10817: $url = $args->{'docs_url'};
10818: $toplevel = $url;
10819: if ($args->{'context'} eq 'paste') {
10820: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10821: ($path) =
10822: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10823: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10824: $fileloc =~ s{^/}{};
10825: }
10826: }
10827: } elsif ($actionurl eq '/adm/dependencies') {
10828: if ($env{'request.course.id'} ne '') {
10829: if (ref($args) eq 'HASH') {
10830: $url = $args->{'docs_url'};
10831: $title = $args->{'docs_title'};
10832: $toplevel = $url;
10833: unless ($toplevel =~ m{^/}) {
10834: $toplevel = "/$url";
10835: }
10836: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10837: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10838: $path = $1;
10839: } else {
10840: ($path) =
10841: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10842: }
10843: if ($toplevel=~/^\/*(uploaded|editupload)/) {
10844: $fileloc = $toplevel;
10845: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10846: my ($udom,$uname,$fname) =
10847: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10848: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10849: } else {
10850: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10851: }
10852: $fileloc =~ s{^/}{};
10853: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10854: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10855: }
10856: }
10857: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10858: $udom = $cdom;
10859: $uname = $cnum;
10860: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10861: $toplevel = $url;
10862: $path = $url;
10863: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10864: $fileloc =~ s{^/}{};
10865: }
10866: foreach my $file (keys(%{$allfiles})) {
10867: my $embed_file;
10868: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10869: $embed_file = $1;
10870: } else {
10871: $embed_file = $file;
10872: }
10873: my ($absolutepath,$cleaned_file);
10874: if ($embed_file =~ m{^\w+://}) {
10875: $cleaned_file = $embed_file;
10876: $newfiles{$cleaned_file} = 1;
10877: $mapping{$cleaned_file} = $embed_file;
10878: } else {
10879: $cleaned_file = &clean_path($embed_file);
10880: if ($embed_file =~ m{^/}) {
10881: $absolutepath = $embed_file;
10882: }
10883: if ($cleaned_file =~ m{/}) {
10884: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10885: $path = &check_for_traversal($path,$url,$toplevel);
10886: my $item = $fname;
10887: if ($path ne '') {
10888: $item = $path.'/'.$fname;
10889: $subdependencies{$path}{$fname} = 1;
10890: } else {
10891: $dependencies{$item} = 1;
10892: }
10893: if ($absolutepath) {
10894: $mapping{$item} = $absolutepath;
10895: } else {
10896: $mapping{$item} = $embed_file;
10897: }
10898: } else {
10899: $dependencies{$embed_file} = 1;
10900: if ($absolutepath) {
10901: $mapping{$cleaned_file} = $absolutepath;
10902: } else {
10903: $mapping{$cleaned_file} = $embed_file;
10904: }
10905: }
10906: }
10907: }
10908: my $dirptr = 16384;
10909: foreach my $path (keys(%subdependencies)) {
10910: $currsubfile{$path} = {};
10911: if (($actionurl eq '/adm/portfolio') ||
10912: ($actionurl eq '/adm/coursegrp_portfolio')) {
10913: my ($sublistref,$listerror) =
10914: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10915: if (ref($sublistref) eq 'ARRAY') {
10916: foreach my $line (@{$sublistref}) {
10917: my ($file_name,$rest) = split(/\&/,$line,2);
10918: $currsubfile{$path}{$file_name} = 1;
10919: }
10920: }
10921: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10922: if (opendir(my $dir,$url.'/'.$path)) {
10923: my @subdir_list = grep(!/^\./,readdir($dir));
10924: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10925: }
10926: } elsif (($actionurl eq '/adm/dependencies') ||
10927: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10928: ($args->{'context'} eq 'paste')) ||
10929: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10930: if ($env{'request.course.id'} ne '') {
10931: my $dir;
10932: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10933: $dir = $fileloc;
10934: } else {
10935: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10936: }
10937: if ($dir ne '') {
10938: my ($sublistref,$listerror) =
10939: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10940: if (ref($sublistref) eq 'ARRAY') {
10941: foreach my $line (@{$sublistref}) {
10942: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10943: undef,$mtime)=split(/\&/,$line,12);
10944: unless (($testdir&$dirptr) ||
10945: ($file_name =~ /^\.\.?$/)) {
10946: $currsubfile{$path}{$file_name} = [$size,$mtime];
10947: }
10948: }
10949: }
10950: }
10951: }
10952: }
10953: foreach my $file (keys(%{$subdependencies{$path}})) {
10954: if (exists($currsubfile{$path}{$file})) {
10955: my $item = $path.'/'.$file;
10956: unless ($mapping{$item} eq $item) {
10957: $pathchanges{$item} = 1;
10958: }
10959: $existing{$item} = 1;
10960: $numexisting ++;
10961: } else {
10962: $newfiles{$path.'/'.$file} = 1;
10963: }
10964: }
10965: if ($actionurl eq '/adm/dependencies') {
10966: foreach my $path (keys(%currsubfile)) {
10967: if (ref($currsubfile{$path}) eq 'HASH') {
10968: foreach my $file (keys(%{$currsubfile{$path}})) {
10969: unless ($subdependencies{$path}{$file}) {
10970: next if (($rem ne '') &&
10971: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10972: (ref($navmap) &&
10973: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10974: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10975: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10976: $unused{$path.'/'.$file} = 1;
10977: }
10978: }
10979: }
10980: }
10981: }
10982: }
10983: my %currfile;
10984: if (($actionurl eq '/adm/portfolio') ||
10985: ($actionurl eq '/adm/coursegrp_portfolio')) {
10986: my ($dirlistref,$listerror) =
10987: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10988: if (ref($dirlistref) eq 'ARRAY') {
10989: foreach my $line (@{$dirlistref}) {
10990: my ($file_name,$rest) = split(/\&/,$line,2);
10991: $currfile{$file_name} = 1;
10992: }
10993: }
10994: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10995: if (opendir(my $dir,$url)) {
10996: my @dir_list = grep(!/^\./,readdir($dir));
10997: map {$currfile{$_} = 1;} @dir_list;
10998: }
10999: } elsif (($actionurl eq '/adm/dependencies') ||
11000: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11001: ($args->{'context'} eq 'paste')) ||
11002: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11003: if ($env{'request.course.id'} ne '') {
11004: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11005: if ($dir ne '') {
11006: my ($dirlistref,$listerror) =
11007: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11008: if (ref($dirlistref) eq 'ARRAY') {
11009: foreach my $line (@{$dirlistref}) {
11010: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11011: $size,undef,$mtime)=split(/\&/,$line,12);
11012: unless (($testdir&$dirptr) ||
11013: ($file_name =~ /^\.\.?$/)) {
11014: $currfile{$file_name} = [$size,$mtime];
11015: }
11016: }
11017: }
11018: }
11019: }
11020: }
11021: foreach my $file (keys(%dependencies)) {
11022: if (exists($currfile{$file})) {
11023: unless ($mapping{$file} eq $file) {
11024: $pathchanges{$file} = 1;
11025: }
11026: $existing{$file} = 1;
11027: $numexisting ++;
11028: } else {
11029: $newfiles{$file} = 1;
11030: }
11031: }
11032: foreach my $file (keys(%currfile)) {
11033: unless (($file eq $filename) ||
11034: ($file eq $filename.'.bak') ||
11035: ($dependencies{$file})) {
11036: if ($actionurl eq '/adm/dependencies') {
11037: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11038: next if (($rem ne '') &&
11039: (($env{"httpref.$rem".$file} ne '') ||
11040: (ref($navmap) &&
11041: (($navmap->getResourceByUrl($rem.$file) ne '') ||
11042: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11043: ($navmap->getResourceByUrl($rem.$1)))))));
11044: }
11045: }
11046: $unused{$file} = 1;
11047: }
11048: }
11049: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11050: ($args->{'context'} eq 'paste')) {
11051: $counter = scalar(keys(%existing));
11052: $numpathchg = scalar(keys(%pathchanges));
11053: return ($output,$counter,$numpathchg,\%existing);
11054: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11055: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11056: $counter = scalar(keys(%existing));
11057: $numpathchg = scalar(keys(%pathchanges));
11058: return ($output,$counter,$numpathchg,\%existing,\%mapping);
11059: }
11060: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11061: if ($actionurl eq '/adm/dependencies') {
11062: next if ($embed_file =~ m{^\w+://});
11063: }
11064: $upload_output .= &start_data_table_row().
11065: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11066: '<span class="LC_filename">'.$embed_file.'</span>';
11067: unless ($mapping{$embed_file} eq $embed_file) {
11068: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11069: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11070: }
11071: $upload_output .= '</td>';
11072: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
11073: $upload_output.='<td align="right">'.
11074: '<span class="LC_info LC_fontsize_medium">'.
11075: &mt("URL points to web address").'</span>';
11076: $numremref++;
11077: } elsif ($args->{'error_on_invalid_names'}
11078: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11079: $upload_output.='<td align="right"><span class="LC_warning">'.
11080: &mt('Invalid characters').'</span>';
11081: $numinvalid++;
11082: } else {
11083: $upload_output .= '<td>'.
11084: &embedded_file_element('upload_embedded',$counter,
11085: $embed_file,\%mapping,
11086: $allfiles,$codebase,'upload');
11087: $counter ++;
11088: $numnew ++;
11089: }
11090: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11091: }
11092: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11093: if ($actionurl eq '/adm/dependencies') {
11094: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11095: $modify_output .= &start_data_table_row().
11096: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11097: '<img src="'.&icon($embed_file).'" border="0" />'.
11098: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
11099: '<td>'.$size.'</td>'.
11100: '<td>'.$mtime.'</td>'.
11101: '<td><label><input type="checkbox" name="mod_upload_dep" '.
11102: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11103: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11104: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11105: &embedded_file_element('upload_embedded',$counter,
11106: $embed_file,\%mapping,
11107: $allfiles,$codebase,'modify').
11108: '</div></td>'.
11109: &end_data_table_row()."\n";
11110: $counter ++;
11111: } else {
11112: $upload_output .= &start_data_table_row().
11113: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11114: '<span class="LC_filename">'.$embed_file.'</span></td>'.
11115: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11116: &Apache::loncommon::end_data_table_row()."\n";
11117: }
11118: }
11119: my $delidx = $counter;
11120: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11121: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11122: $delete_output .= &start_data_table_row().
11123: '<td><img src="'.&icon($oldfile).'" />'.
11124: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
11125: '<td>'.$size.'</td>'.
11126: '<td>'.$mtime.'</td>'.
11127: '<td><label><input type="checkbox" name="del_upload_dep" '.
11128: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11129: &embedded_file_element('upload_embedded',$delidx,
11130: $oldfile,\%mapping,$allfiles,
11131: $codebase,'delete').'</td>'.
11132: &end_data_table_row()."\n";
11133: $numunused ++;
11134: $delidx ++;
11135: }
11136: if ($upload_output) {
11137: $upload_output = &start_data_table().
11138: $upload_output.
11139: &end_data_table()."\n";
11140: }
11141: if ($modify_output) {
11142: $modify_output = &start_data_table().
11143: &start_data_table_header_row().
11144: '<th>'.&mt('File').'</th>'.
11145: '<th>'.&mt('Size (KB)').'</th>'.
11146: '<th>'.&mt('Modified').'</th>'.
11147: '<th>'.&mt('Upload replacement?').'</th>'.
11148: &end_data_table_header_row().
11149: $modify_output.
11150: &end_data_table()."\n";
11151: }
11152: if ($delete_output) {
11153: $delete_output = &start_data_table().
11154: &start_data_table_header_row().
11155: '<th>'.&mt('File').'</th>'.
11156: '<th>'.&mt('Size (KB)').'</th>'.
11157: '<th>'.&mt('Modified').'</th>'.
11158: '<th>'.&mt('Delete?').'</th>'.
11159: &end_data_table_header_row().
11160: $delete_output.
11161: &end_data_table()."\n";
11162: }
11163: my $applies = 0;
11164: if ($numremref) {
11165: $applies ++;
11166: }
11167: if ($numinvalid) {
11168: $applies ++;
11169: }
11170: if ($numexisting) {
11171: $applies ++;
11172: }
11173: if ($counter || $numunused) {
11174: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11175: ' method="post" enctype="multipart/form-data">'."\n".
11176: $state.'<h3>'.$heading.'</h3>';
11177: if ($actionurl eq '/adm/dependencies') {
11178: if ($numnew) {
11179: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11180: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11181: $upload_output.'<br />'."\n";
11182: }
11183: if ($numexisting) {
11184: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11185: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11186: $modify_output.'<br />'."\n";
11187: $buttontext = &mt('Save changes');
11188: }
11189: if ($numunused) {
11190: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11191: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11192: $delete_output.'<br />'."\n";
11193: $buttontext = &mt('Save changes');
11194: }
11195: } else {
11196: $output .= $upload_output.'<br />'."\n";
11197: }
11198: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11199: $counter.'" />'."\n";
11200: if ($actionurl eq '/adm/dependencies') {
11201: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11202: $numnew.'" />'."\n";
11203: } elsif ($actionurl eq '') {
11204: $output .= '<input type="hidden" name="phase" value="three" />';
11205: }
11206: } elsif ($applies) {
11207: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11208: if ($applies > 1) {
11209: $output .=
11210: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11211: if ($numremref) {
11212: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11213: }
11214: if ($numinvalid) {
11215: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11216: }
11217: if ($numexisting) {
11218: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11219: }
11220: $output .= '</ul><br />';
11221: } elsif ($numremref) {
11222: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11223: } elsif ($numinvalid) {
11224: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11225: } elsif ($numexisting) {
11226: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11227: }
11228: $output .= $upload_output.'<br />';
11229: }
11230: my ($pathchange_output,$chgcount);
11231: $chgcount = $counter;
11232: if (keys(%pathchanges) > 0) {
11233: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11234: if ($counter) {
11235: $output .= &embedded_file_element('pathchange',$chgcount,
11236: $embed_file,\%mapping,
11237: $allfiles,$codebase,'change');
11238: } else {
11239: $pathchange_output .=
11240: &start_data_table_row().
11241: '<td><input type ="checkbox" name="namechange" value="'.
11242: $chgcount.'" checked="checked" /></td>'.
11243: '<td>'.$mapping{$embed_file}.'</td>'.
11244: '<td>'.$embed_file.
11245: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11246: \%mapping,$allfiles,$codebase,'change').
11247: '</td>'.&end_data_table_row();
11248: }
11249: $numpathchg ++;
11250: $chgcount ++;
11251: }
11252: }
11253: if (($counter) || ($numunused)) {
11254: if ($numpathchg) {
11255: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11256: $numpathchg.'" />'."\n";
11257: }
11258: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11259: ($actionurl eq '/adm/imsimport')) {
11260: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11261: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11262: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11263: } elsif ($actionurl eq '/adm/dependencies') {
11264: $output .= '<input type="hidden" name="action" value="process_changes" />';
11265: }
11266: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11267: } elsif ($numpathchg) {
11268: my %pathchange = ();
11269: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11270: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11271: $output .= '<p>'.&mt('or').'</p>';
11272: }
11273: }
11274: return ($output,$counter,$numpathchg);
11275: }
11276:
11277: =pod
11278:
11279: =item * clean_path($name)
11280:
11281: Performs clean-up of directories, subdirectories and filename in an
11282: embedded object, referenced in an HTML file which is being uploaded
11283: to a course or portfolio, where
11284: "Upload embedded images/multimedia files if HTML file" checkbox was
11285: checked.
11286:
11287: Clean-up is similar to replacements in lonnet::clean_filename()
11288: except each / between sub-directory and next level is preserved.
11289:
11290: =cut
11291:
11292: sub clean_path {
11293: my ($embed_file) = @_;
11294: $embed_file =~s{^/+}{};
11295: my @contents;
11296: if ($embed_file =~ m{/}) {
11297: @contents = split(/\//,$embed_file);
11298: } else {
11299: @contents = ($embed_file);
11300: }
11301: my $lastidx = scalar(@contents)-1;
11302: for (my $i=0; $i<=$lastidx; $i++) {
11303: $contents[$i]=~s{\\}{/}g;
11304: $contents[$i]=~s/\s+/\_/g;
11305: $contents[$i]=~s{[^/\w\.\-]}{}g;
11306: if ($i == $lastidx) {
11307: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11308: }
11309: }
11310: if ($lastidx > 0) {
11311: return join('/',@contents);
11312: } else {
11313: return $contents[0];
11314: }
11315: }
11316:
11317: sub embedded_file_element {
11318: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11319: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11320: (ref($codebase) eq 'HASH'));
11321: my $output;
11322: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11323: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11324: }
11325: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11326: &escape($embed_file).'" />';
11327: unless (($context eq 'upload_embedded') &&
11328: ($mapping->{$embed_file} eq $embed_file)) {
11329: $output .='
11330: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11331: }
11332: my $attrib;
11333: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11334: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11335: }
11336: $output .=
11337: "\n\t\t".
11338: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11339: $attrib.'" />';
11340: if (exists($codebase->{$mapping->{$embed_file}})) {
11341: $output .=
11342: "\n\t\t".
11343: '<input name="codebase_'.$num.'" type="hidden" value="'.
11344: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11345: }
11346: return $output;
11347: }
11348:
11349: sub get_dependency_details {
11350: my ($currfile,$currsubfile,$embed_file) = @_;
11351: my ($size,$mtime,$showsize,$showmtime);
11352: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11353: if ($embed_file =~ m{/}) {
11354: my ($path,$fname) = split(/\//,$embed_file);
11355: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11356: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11357: }
11358: } else {
11359: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11360: ($size,$mtime) = @{$currfile->{$embed_file}};
11361: }
11362: }
11363: $showsize = $size/1024.0;
11364: $showsize = sprintf("%.1f",$showsize);
11365: if ($mtime > 0) {
11366: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11367: }
11368: }
11369: return ($showsize,$showmtime);
11370: }
11371:
11372: sub ask_embedded_js {
11373: return <<"END";
11374: <script type="text/javascript"">
11375: // <![CDATA[
11376: function toggleBrowse(counter) {
11377: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11378: var fileid = document.getElementById('embedded_item_'+counter);
11379: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11380: if (chkboxid.checked == true) {
11381: uploaddivid.style.display='block';
11382: } else {
11383: uploaddivid.style.display='none';
11384: fileid.value = '';
11385: }
11386: }
11387: // ]]>
11388: </script>
11389:
11390: END
11391: }
11392:
11393: sub upload_embedded {
11394: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11395: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11396: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11397: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11398: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11399: my $orig_uploaded_filename =
11400: $env{'form.embedded_item_'.$i.'.filename'};
11401: foreach my $type ('orig','ref','attrib','codebase') {
11402: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11403: $env{'form.embedded_'.$type.'_'.$i} =
11404: &unescape($env{'form.embedded_'.$type.'_'.$i});
11405: }
11406: }
11407: my ($path,$fname) =
11408: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11409: # no path, whole string is fname
11410: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11411: $fname = &Apache::lonnet::clean_filename($fname);
11412: # See if there is anything left
11413: next if ($fname eq '');
11414:
11415: # Check if file already exists as a file or directory.
11416: my ($state,$msg);
11417: if ($context eq 'portfolio') {
11418: my $port_path = $dirpath;
11419: if ($group ne '') {
11420: $port_path = "groups/$group/$port_path";
11421: }
11422: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11423: $fname,$group,'embedded_item_'.$i,
11424: $dir_root,$port_path,$disk_quota,
11425: $current_disk_usage,$uname,$udom);
11426: if ($state eq 'will_exceed_quota'
11427: || $state eq 'file_locked') {
11428: $output .= $msg;
11429: next;
11430: }
11431: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11432: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11433: if ($state eq 'exists') {
11434: $output .= $msg;
11435: next;
11436: }
11437: }
11438: # Check if extension is valid
11439: if (($fname =~ /\.(\w+)$/) &&
11440: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11441: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11442: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11443: next;
11444: } elsif (($fname =~ /\.(\w+)$/) &&
11445: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11446: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11447: next;
11448: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11449: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11450: next;
11451: }
11452: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11453: my $subdir = $path;
11454: $subdir =~ s{/+$}{};
11455: if ($context eq 'portfolio') {
11456: my $result;
11457: if ($state eq 'existingfile') {
11458: $result=
11459: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11460: $dirpath.$env{'form.currentpath'}.$subdir);
11461: } else {
11462: $result=
11463: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11464: $dirpath.
11465: $env{'form.currentpath'}.$subdir);
11466: if ($result !~ m|^/uploaded/|) {
11467: $output .= '<span class="LC_error">'
11468: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11469: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11470: .'</span><br />';
11471: next;
11472: } else {
11473: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11474: $path.$fname.'</span>').'<br />';
11475: }
11476: }
11477: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11478: my $extendedsubdir = $dirpath.'/'.$subdir;
11479: $extendedsubdir =~ s{/+$}{};
11480: my $result =
11481: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11482: if ($result !~ m|^/uploaded/|) {
11483: $output .= '<span class="LC_error">'
11484: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11485: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11486: .'</span><br />';
11487: next;
11488: } else {
11489: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11490: $path.$fname.'</span>').'<br />';
11491: if ($context eq 'syllabus') {
11492: &Apache::lonnet::make_public_indefinitely($result);
11493: }
11494: }
11495: } else {
11496: # Save the file
11497: my $target = $env{'form.embedded_item_'.$i};
11498: my $fullpath = $dir_root.$dirpath.'/'.$path;
11499: my $dest = $fullpath.$fname;
11500: my $url = $url_root.$dirpath.'/'.$path.$fname;
11501: my @parts=split(/\//,"$dirpath/$path");
11502: my $count;
11503: my $filepath = $dir_root;
11504: foreach my $subdir (@parts) {
11505: $filepath .= "/$subdir";
11506: if (!-e $filepath) {
11507: mkdir($filepath,0770);
11508: }
11509: }
11510: my $fh;
11511: if (!open($fh,'>'.$dest)) {
11512: &Apache::lonnet::logthis('Failed to create '.$dest);
11513: $output .= '<span class="LC_error">'.
11514: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11515: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11516: '</span><br />';
11517: } else {
11518: if (!print $fh $env{'form.embedded_item_'.$i}) {
11519: &Apache::lonnet::logthis('Failed to write to '.$dest);
11520: $output .= '<span class="LC_error">'.
11521: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11522: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11523: '</span><br />';
11524: } else {
11525: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11526: $url.'</span>').'<br />';
11527: unless ($context eq 'testbank') {
11528: $footer .= &mt('View embedded file: [_1]',
11529: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11530: }
11531: }
11532: close($fh);
11533: }
11534: }
11535: if ($env{'form.embedded_ref_'.$i}) {
11536: $pathchange{$i} = 1;
11537: }
11538: }
11539: if ($output) {
11540: $output = '<p>'.$output.'</p>';
11541: }
11542: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11543: $returnflag = 'ok';
11544: my $numpathchgs = scalar(keys(%pathchange));
11545: if ($numpathchgs > 0) {
11546: if ($context eq 'portfolio') {
11547: $output .= '<p>'.&mt('or').'</p>';
11548: } elsif ($context eq 'testbank') {
11549: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11550: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11551: $returnflag = 'modify_orightml';
11552: }
11553: }
11554: return ($output.$footer,$returnflag,$numpathchgs);
11555: }
11556:
11557: sub modify_html_form {
11558: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11559: my $end = 0;
11560: my $modifyform;
11561: if ($context eq 'upload_embedded') {
11562: return unless (ref($pathchange) eq 'HASH');
11563: if ($env{'form.number_embedded_items'}) {
11564: $end += $env{'form.number_embedded_items'};
11565: }
11566: if ($env{'form.number_pathchange_items'}) {
11567: $end += $env{'form.number_pathchange_items'};
11568: }
11569: if ($end) {
11570: for (my $i=0; $i<$end; $i++) {
11571: if ($i < $env{'form.number_embedded_items'}) {
11572: next unless($pathchange->{$i});
11573: }
11574: $modifyform .=
11575: &start_data_table_row().
11576: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11577: 'checked="checked" /></td>'.
11578: '<td>'.$env{'form.embedded_ref_'.$i}.
11579: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11580: &escape($env{'form.embedded_ref_'.$i}).'" />'.
11581: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11582: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11583: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11584: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11585: '<td>'.$env{'form.embedded_orig_'.$i}.
11586: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11587: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11588: &end_data_table_row();
11589: }
11590: }
11591: } else {
11592: $modifyform = $pathchgtable;
11593: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11594: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11595: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11596: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11597: }
11598: }
11599: if ($modifyform) {
11600: if ($actionurl eq '/adm/dependencies') {
11601: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11602: }
11603: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11604: '<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".
11605: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11606: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11607: '</ol></p>'."\n".'<p>'.
11608: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11609: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11610: &start_data_table()."\n".
11611: &start_data_table_header_row().
11612: '<th>'.&mt('Change?').'</th>'.
11613: '<th>'.&mt('Current reference').'</th>'.
11614: '<th>'.&mt('Required reference').'</th>'.
11615: &end_data_table_header_row()."\n".
11616: $modifyform.
11617: &end_data_table().'<br />'."\n".$hiddenstate.
11618: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11619: '</form>'."\n";
11620: }
11621: return;
11622: }
11623:
11624: sub modify_html_refs {
11625: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11626: my $container;
11627: if ($context eq 'portfolio') {
11628: $container = $env{'form.container'};
11629: } elsif ($context eq 'coursedoc') {
11630: $container = $env{'form.primaryurl'};
11631: } elsif ($context eq 'manage_dependencies') {
11632: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11633: $container = "/$container";
11634: } elsif ($context eq 'syllabus') {
11635: $container = $url;
11636: } else {
11637: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11638: }
11639: my (%allfiles,%codebase,$output,$content);
11640: my @changes = &get_env_multiple('form.namechange');
11641: unless ((@changes > 0) || ($context eq 'syllabus')) {
11642: if (wantarray) {
11643: return ('',0,0);
11644: } else {
11645: return;
11646: }
11647: }
11648: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11649: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11650: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11651: if (wantarray) {
11652: return ('',0,0);
11653: } else {
11654: return;
11655: }
11656: }
11657: $content = &Apache::lonnet::getfile($container);
11658: if ($content eq '-1') {
11659: if (wantarray) {
11660: return ('',0,0);
11661: } else {
11662: return;
11663: }
11664: }
11665: } else {
11666: unless ($container =~ /^\Q$dir_root\E/) {
11667: if (wantarray) {
11668: return ('',0,0);
11669: } else {
11670: return;
11671: }
11672: }
11673: if (open(my $fh,'<',$container)) {
11674: $content = join('', <$fh>);
11675: close($fh);
11676: } else {
11677: if (wantarray) {
11678: return ('',0,0);
11679: } else {
11680: return;
11681: }
11682: }
11683: }
11684: my ($count,$codebasecount) = (0,0);
11685: my $mm = new File::MMagic;
11686: my $mime_type = $mm->checktype_contents($content);
11687: if ($mime_type eq 'text/html') {
11688: my $parse_result =
11689: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11690: \%codebase,\$content);
11691: if ($parse_result eq 'ok') {
11692: foreach my $i (@changes) {
11693: my $orig = &unescape($env{'form.embedded_orig_'.$i});
11694: my $ref = &unescape($env{'form.embedded_ref_'.$i});
11695: if ($allfiles{$ref}) {
11696: my $newname = $orig;
11697: my ($attrib_regexp,$codebase);
11698: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11699: if ($attrib_regexp =~ /:/) {
11700: $attrib_regexp =~ s/\:/|/g;
11701: }
11702: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11703: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11704: $count += $numchg;
11705: $allfiles{$newname} = $allfiles{$ref};
11706: delete($allfiles{$ref});
11707: }
11708: if ($env{'form.embedded_codebase_'.$i} ne '') {
11709: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11710: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11711: $codebasecount ++;
11712: }
11713: }
11714: }
11715: my $skiprewrites;
11716: if ($count || $codebasecount) {
11717: my $saveresult;
11718: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11719: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11720: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11721: if ($url eq $container) {
11722: my ($fname) = ($container =~ m{/([^/]+)$});
11723: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11724: $count,'<span class="LC_filename">'.
11725: $fname.'</span>').'</p>';
11726: } else {
11727: $output = '<p class="LC_error">'.
11728: &mt('Error: update failed for: [_1].',
11729: '<span class="LC_filename">'.
11730: $container.'</span>').'</p>';
11731: }
11732: if ($context eq 'syllabus') {
11733: unless ($saveresult eq 'ok') {
11734: $skiprewrites = 1;
11735: }
11736: }
11737: } else {
11738: if (open(my $fh,'>',$container)) {
11739: print $fh $content;
11740: close($fh);
11741: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11742: $count,'<span class="LC_filename">'.
11743: $container.'</span>').'</p>';
11744: } else {
11745: $output = '<p class="LC_error">'.
11746: &mt('Error: could not update [_1].',
11747: '<span class="LC_filename">'.
11748: $container.'</span>').'</p>';
11749: }
11750: }
11751: }
11752: if (($context eq 'syllabus') && (!$skiprewrites)) {
11753: my ($actionurl,$state);
11754: $actionurl = "/public/$udom/$uname/syllabus";
11755: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11756: &ask_for_embedded_content($actionurl,$state,\%allfiles,
11757: \%codebase,
11758: {'context' => 'rewrites',
11759: 'ignore_remote_references' => 1,});
11760: if (ref($mapping) eq 'HASH') {
11761: my $rewrites = 0;
11762: foreach my $key (keys(%{$mapping})) {
11763: next if ($key =~ m{^https?://});
11764: my $ref = $mapping->{$key};
11765: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11766: my $attrib;
11767: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11768: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11769: }
11770: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11771: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11772: $rewrites += $numchg;
11773: }
11774: }
11775: if ($rewrites) {
11776: my $saveresult;
11777: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11778: if ($url eq $container) {
11779: my ($fname) = ($container =~ m{/([^/]+)$});
11780: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11781: $count,'<span class="LC_filename">'.
11782: $fname.'</span>').'</p>';
11783: } else {
11784: $output .= '<p class="LC_error">'.
11785: &mt('Error: could not update links in [_1].',
11786: '<span class="LC_filename">'.
11787: $container.'</span>').'</p>';
11788:
11789: }
11790: }
11791: }
11792: }
11793: } else {
11794: &logthis('Failed to parse '.$container.
11795: ' to modify references: '.$parse_result);
11796: }
11797: }
11798: if (wantarray) {
11799: return ($output,$count,$codebasecount);
11800: } else {
11801: return $output;
11802: }
11803: }
11804:
11805: sub check_for_existing {
11806: my ($path,$fname,$element) = @_;
11807: my ($state,$msg);
11808: if (-d $path.'/'.$fname) {
11809: $state = 'exists';
11810: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11811: } elsif (-e $path.'/'.$fname) {
11812: $state = 'exists';
11813: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11814: }
11815: if ($state eq 'exists') {
11816: $msg = '<span class="LC_error">'.$msg.'</span><br />';
11817: }
11818: return ($state,$msg);
11819: }
11820:
11821: sub check_for_upload {
11822: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11823: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11824: my $filesize = length($env{'form.'.$element});
11825: if (!$filesize) {
11826: my $msg = '<span class="LC_error">'.
11827: &mt('Unable to upload [_1]. (size = [_2] bytes)',
11828: '<span class="LC_filename">'.$fname.'</span>',
11829: $filesize).'<br />'.
11830: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11831: '</span>';
11832: return ('zero_bytes',$msg);
11833: }
11834: $filesize = $filesize/1000; #express in k (1024?)
11835: my $getpropath = 1;
11836: my ($dirlistref,$listerror) =
11837: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11838: my $found_file = 0;
11839: my $locked_file = 0;
11840: my @lockers;
11841: my $navmap;
11842: if ($env{'request.course.id'}) {
11843: $navmap = Apache::lonnavmaps::navmap->new();
11844: }
11845: if (ref($dirlistref) eq 'ARRAY') {
11846: foreach my $line (@{$dirlistref}) {
11847: my ($file_name,$rest)=split(/\&/,$line,2);
11848: if ($file_name eq $fname){
11849: $file_name = $path.$file_name;
11850: if ($group ne '') {
11851: $file_name = $group.$file_name;
11852: }
11853: $found_file = 1;
11854: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11855: foreach my $lock (@lockers) {
11856: if (ref($lock) eq 'ARRAY') {
11857: my ($symb,$crsid) = @{$lock};
11858: if ($crsid eq $env{'request.course.id'}) {
11859: if (ref($navmap)) {
11860: my $res = $navmap->getBySymb($symb);
11861: foreach my $part (@{$res->parts()}) {
11862: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11863: unless (($slot_status == $res->RESERVED) ||
11864: ($slot_status == $res->RESERVED_LOCATION)) {
11865: $locked_file = 1;
11866: }
11867: }
11868: } else {
11869: $locked_file = 1;
11870: }
11871: } else {
11872: $locked_file = 1;
11873: }
11874: }
11875: }
11876: } else {
11877: my @info = split(/\&/,$rest);
11878: my $currsize = $info[6]/1000;
11879: if ($currsize < $filesize) {
11880: my $extra = $filesize - $currsize;
11881: if (($current_disk_usage + $extra) > $disk_quota) {
11882: my $msg = '<p class="LC_warning">'.
11883: &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.',
11884: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11885: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11886: $disk_quota,$current_disk_usage).'</p>';
11887: return ('will_exceed_quota',$msg);
11888: }
11889: }
11890: }
11891: }
11892: }
11893: }
11894: if (($current_disk_usage + $filesize) > $disk_quota){
11895: my $msg = '<p class="LC_warning">'.
11896: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11897: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11898: return ('will_exceed_quota',$msg);
11899: } elsif ($found_file) {
11900: if ($locked_file) {
11901: my $msg = '<p class="LC_warning">';
11902: $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>');
11903: $msg .= '</p>';
11904: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11905: return ('file_locked',$msg);
11906: } else {
11907: my $msg = '<p class="LC_error">';
11908: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11909: $msg .= '</p>';
11910: return ('existingfile',$msg);
11911: }
11912: }
11913: }
11914:
11915: sub check_for_traversal {
11916: my ($path,$url,$toplevel) = @_;
11917: my @parts=split(/\//,$path);
11918: my $cleanpath;
11919: my $fullpath = $url;
11920: for (my $i=0;$i<@parts;$i++) {
11921: next if ($parts[$i] eq '.');
11922: if ($parts[$i] eq '..') {
11923: $fullpath =~ s{([^/]+/)$}{};
11924: } else {
11925: $fullpath .= $parts[$i].'/';
11926: }
11927: }
11928: if ($fullpath =~ /^\Q$url\E(.*)$/) {
11929: $cleanpath = $1;
11930: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11931: my $curr_toprel = $1;
11932: my @parts = split(/\//,$curr_toprel);
11933: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11934: my @urlparts = split(/\//,$url_toprel);
11935: my $doubledots;
11936: my $startdiff = -1;
11937: for (my $i=0; $i<@urlparts; $i++) {
11938: if ($startdiff == -1) {
11939: unless ($urlparts[$i] eq $parts[$i]) {
11940: $startdiff = $i;
11941: $doubledots .= '../';
11942: }
11943: } else {
11944: $doubledots .= '../';
11945: }
11946: }
11947: if ($startdiff > -1) {
11948: $cleanpath = $doubledots;
11949: for (my $i=$startdiff; $i<@parts; $i++) {
11950: $cleanpath .= $parts[$i].'/';
11951: }
11952: }
11953: }
11954: $cleanpath =~ s{(/)$}{};
11955: return $cleanpath;
11956: }
11957:
11958: sub is_archive_file {
11959: my ($mimetype) = @_;
11960: if (($mimetype eq 'application/octet-stream') ||
11961: ($mimetype eq 'application/x-stuffit') ||
11962: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11963: return 1;
11964: }
11965: return;
11966: }
11967:
11968: sub decompress_form {
11969: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11970: my %lt = &Apache::lonlocal::texthash (
11971: this => 'This file is an archive file.',
11972: camt => 'This file is a Camtasia archive file.',
11973: itsc => 'Its contents are as follows:',
11974: youm => 'You may wish to extract its contents.',
11975: extr => 'Extract contents',
11976: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11977: proa => 'Process automatically?',
11978: yes => 'Yes',
11979: no => 'No',
11980: fold => 'Title for folder containing movie',
11981: movi => 'Title for page containing embedded movie',
11982: );
11983: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11984: my ($is_camtasia,$topdir,%toplevel,@paths);
11985: my $info = &list_archive_contents($fileloc,\@paths);
11986: if (@paths) {
11987: foreach my $path (@paths) {
11988: $path =~ s{^/}{};
11989: if ($path =~ m{^([^/]+)/$}) {
11990: $topdir = $1;
11991: }
11992: if ($path =~ m{^([^/]+)/}) {
11993: $toplevel{$1} = $path;
11994: } else {
11995: $toplevel{$path} = $path;
11996: }
11997: }
11998: }
11999: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12000: my @camtasia6 = ("$topdir/","$topdir/index.html",
12001: "$topdir/media/",
12002: "$topdir/media/$topdir.mp4",
12003: "$topdir/media/FirstFrame.png",
12004: "$topdir/media/player.swf",
12005: "$topdir/media/swfobject.js",
12006: "$topdir/media/expressInstall.swf");
12007: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12008: "$topdir/$topdir.mp4",
12009: "$topdir/$topdir\_config.xml",
12010: "$topdir/$topdir\_controller.swf",
12011: "$topdir/$topdir\_embed.css",
12012: "$topdir/$topdir\_First_Frame.png",
12013: "$topdir/$topdir\_player.html",
12014: "$topdir/$topdir\_Thumbnails.png",
12015: "$topdir/playerProductInstall.swf",
12016: "$topdir/scripts/",
12017: "$topdir/scripts/config_xml.js",
12018: "$topdir/scripts/handlebars.js",
12019: "$topdir/scripts/jquery-1.7.1.min.js",
12020: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12021: "$topdir/scripts/modernizr.js",
12022: "$topdir/scripts/player-min.js",
12023: "$topdir/scripts/swfobject.js",
12024: "$topdir/skins/",
12025: "$topdir/skins/configuration_express.xml",
12026: "$topdir/skins/express_show/",
12027: "$topdir/skins/express_show/player-min.css",
12028: "$topdir/skins/express_show/spritesheet.png");
12029: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12030: "$topdir/$topdir.mp4",
12031: "$topdir/$topdir\_config.xml",
12032: "$topdir/$topdir\_controller.swf",
12033: "$topdir/$topdir\_embed.css",
12034: "$topdir/$topdir\_First_Frame.png",
12035: "$topdir/$topdir\_player.html",
12036: "$topdir/$topdir\_Thumbnails.png",
12037: "$topdir/playerProductInstall.swf",
12038: "$topdir/scripts/",
12039: "$topdir/scripts/config_xml.js",
12040: "$topdir/scripts/techsmith-smart-player.min.js",
12041: "$topdir/skins/",
12042: "$topdir/skins/configuration_express.xml",
12043: "$topdir/skins/express_show/",
12044: "$topdir/skins/express_show/spritesheet.min.css",
12045: "$topdir/skins/express_show/spritesheet.png",
12046: "$topdir/skins/express_show/techsmith-smart-player.min.css");
12047: my @diffs = &compare_arrays(\@paths,\@camtasia6);
12048: if (@diffs == 0) {
12049: $is_camtasia = 6;
12050: } else {
12051: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12052: if (@diffs == 0) {
12053: $is_camtasia = 8;
12054: } else {
12055: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12056: if (@diffs == 0) {
12057: $is_camtasia = 8;
12058: }
12059: }
12060: }
12061: }
12062: my $output;
12063: if ($is_camtasia) {
12064: $output = <<"ENDCAM";
12065: <script type="text/javascript" language="Javascript">
12066: // <![CDATA[
12067:
12068: function camtasiaToggle() {
12069: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12070: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12071: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12072: document.getElementById('camtasia_titles').style.display='block';
12073: } else {
12074: document.getElementById('camtasia_titles').style.display='none';
12075: }
12076: }
12077: }
12078: return;
12079: }
12080:
12081: // ]]>
12082: </script>
12083: <p>$lt{'camt'}</p>
12084: ENDCAM
12085: } else {
12086: $output = '<p>'.$lt{'this'};
12087: if ($info eq '') {
12088: $output .= ' '.$lt{'youm'}.'</p>'."\n";
12089: } else {
12090: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12091: '<div><pre>'.$info.'</pre></div>';
12092: }
12093: }
12094: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12095: my $duplicates;
12096: my $num = 0;
12097: if (ref($dirlist) eq 'ARRAY') {
12098: foreach my $item (@{$dirlist}) {
12099: if (ref($item) eq 'ARRAY') {
12100: if (exists($toplevel{$item->[0]})) {
12101: $duplicates .=
12102: &start_data_table_row().
12103: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12104: 'value="0" checked="checked" />'.&mt('No').'</label>'.
12105: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
12106: 'value="1" />'.&mt('Yes').'</label>'.
12107: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12108: '<td>'.$item->[0].'</td>';
12109: if ($item->[2]) {
12110: $duplicates .= '<td>'.&mt('Directory').'</td>';
12111: } else {
12112: $duplicates .= '<td>'.&mt('File').'</td>';
12113: }
12114: $duplicates .= '<td>'.$item->[3].'</td>'.
12115: '<td>'.
12116: &Apache::lonlocal::locallocaltime($item->[4]).
12117: '</td>'.
12118: &end_data_table_row();
12119: $num ++;
12120: }
12121: }
12122: }
12123: }
12124: my $itemcount;
12125: if (@paths > 0) {
12126: $itemcount = scalar(@paths);
12127: } else {
12128: $itemcount = 1;
12129: }
12130: if ($is_camtasia) {
12131: $output .= $lt{'auto'}.'<br />'.
12132: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12133: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12134: $lt{'yes'}.'</label> <label>'.
12135: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12136: $lt{'no'}.'</label></span><br />'.
12137: '<div id="camtasia_titles" style="display:block">'.
12138: &Apache::lonhtmlcommon::start_pick_box().
12139: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12140: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12141: &Apache::lonhtmlcommon::row_closure().
12142: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12143: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12144: &Apache::lonhtmlcommon::row_closure(1).
12145: &Apache::lonhtmlcommon::end_pick_box().
12146: '</div>';
12147: }
12148: $output .=
12149: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12150: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12151: "\n";
12152: if ($duplicates ne '') {
12153: $output .= '<p><span class="LC_warning">'.
12154: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
12155: &start_data_table().
12156: &start_data_table_header_row().
12157: '<th>'.&mt('Overwrite?').'</th>'.
12158: '<th>'.&mt('Name').'</th>'.
12159: '<th>'.&mt('Type').'</th>'.
12160: '<th>'.&mt('Size').'</th>'.
12161: '<th>'.&mt('Last modified').'</th>'.
12162: &end_data_table_header_row().
12163: $duplicates.
12164: &end_data_table().
12165: '</p>';
12166: }
12167: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12168: if (ref($hiddenelements) eq 'HASH') {
12169: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12170: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12171: }
12172: }
12173: $output .= <<"END";
12174: <br />
12175: <input type="submit" name="decompress" value="$lt{'extr'}" />
12176: </form>
12177: $noextract
12178: END
12179: return $output;
12180: }
12181:
12182: sub decompression_utility {
12183: my ($program) = @_;
12184: my @utilities = ('tar','gunzip','bunzip2','unzip');
12185: my $location;
12186: if (grep(/^\Q$program\E$/,@utilities)) {
12187: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12188: '/usr/sbin/') {
12189: if (-x $dir.$program) {
12190: $location = $dir.$program;
12191: last;
12192: }
12193: }
12194: }
12195: return $location;
12196: }
12197:
12198: sub list_archive_contents {
12199: my ($file,$pathsref) = @_;
12200: my (@cmd,$output);
12201: my $needsregexp;
12202: if ($file =~ /\.zip$/) {
12203: @cmd = (&decompression_utility('unzip'),"-l");
12204: $needsregexp = 1;
12205: } elsif (($file =~ m/\.tar\.gz$/) ||
12206: ($file =~ /\.tgz$/)) {
12207: @cmd = (&decompression_utility('tar'),"-ztf");
12208: } elsif ($file =~ /\.tar\.bz2$/) {
12209: @cmd = (&decompression_utility('tar'),"-jtf");
12210: } elsif ($file =~ m|\.tar$|) {
12211: @cmd = (&decompression_utility('tar'),"-tf");
12212: }
12213: if (@cmd) {
12214: undef($!);
12215: undef($@);
12216: if (open(my $fh,"-|", @cmd, $file)) {
12217: while (my $line = <$fh>) {
12218: $output .= $line;
12219: chomp($line);
12220: my $item;
12221: if ($needsregexp) {
12222: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12223: } else {
12224: $item = $line;
12225: }
12226: if ($item ne '') {
12227: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12228: push(@{$pathsref},$item);
12229: }
12230: }
12231: }
12232: close($fh);
12233: }
12234: }
12235: return $output;
12236: }
12237:
12238: sub decompress_uploaded_file {
12239: my ($file,$dir) = @_;
12240: &Apache::lonnet::appenv({'cgi.file' => $file});
12241: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12242: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12243: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12244: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12245: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12246: my $decompressed = $env{'cgi.decompressed'};
12247: &Apache::lonnet::delenv('cgi.file');
12248: &Apache::lonnet::delenv('cgi.dir');
12249: &Apache::lonnet::delenv('cgi.decompressed');
12250: return ($decompressed,$result);
12251: }
12252:
12253: sub process_decompression {
12254: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12255: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12256: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12257: &mt('Unexpected file path.').'</p>'."\n";
12258: }
12259: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12260: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12261: &mt('Unexpected course context.').'</p>'."\n";
12262: }
12263: unless ($file eq &Apache::lonnet::clean_filename($file)) {
12264: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12265: &mt('Filename contained unexpected characters.').'</p>'."\n";
12266: }
12267: my ($dir,$error,$warning,$output);
12268: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12269: $error = &mt('Filename not a supported archive file type.').
12270: '<br />'.&mt('Filename should end with one of: [_1].',
12271: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12272: } else {
12273: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12274: if ($docuhome eq 'no_host') {
12275: $error = &mt('Could not determine home server for course.');
12276: } else {
12277: my @ids=&Apache::lonnet::current_machine_ids();
12278: my $currdir = "$dir_root/$destination";
12279: if (grep(/^\Q$docuhome\E$/,@ids)) {
12280: $dir = &LONCAPA::propath($docudom,$docuname).
12281: "$dir_root/$destination";
12282: } else {
12283: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12284: "$dir_root/$docudom/$docuname/$destination";
12285: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12286: $error = &mt('Archive file not found.');
12287: }
12288: }
12289: my (@to_overwrite,@to_skip);
12290: if ($env{'form.archive_overwrite_total'} > 0) {
12291: my $total = $env{'form.archive_overwrite_total'};
12292: for (my $i=0; $i<$total; $i++) {
12293: if ($env{'form.archive_overwrite_'.$i} == 1) {
12294: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12295: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12296: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12297: }
12298: }
12299: }
12300: my $numskip = scalar(@to_skip);
12301: my $numoverwrite = scalar(@to_overwrite);
12302: if (($numskip) && (!$numoverwrite)) {
12303: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12304: } elsif ($dir eq '') {
12305: $error = &mt('Directory containing archive file unavailable.');
12306: } elsif (!$error) {
12307: my ($decompressed,$display);
12308: if (($numskip) || ($numoverwrite)) {
12309: my $tempdir = time.'_'.$$.int(rand(10000));
12310: mkdir("$dir/$tempdir",0755);
12311: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12312: ($decompressed,$display) =
12313: &decompress_uploaded_file($file,"$dir/$tempdir");
12314: foreach my $item (@to_skip) {
12315: if (($item ne '') && ($item !~ /\.\./)) {
12316: if (-f "$dir/$tempdir/$item") {
12317: unlink("$dir/$tempdir/$item");
12318: } elsif (-d "$dir/$tempdir/$item") {
12319: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12320: }
12321: }
12322: }
12323: foreach my $item (@to_overwrite) {
12324: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12325: if (($item ne '') && ($item !~ /\.\./)) {
12326: if (-f "$dir/$item") {
12327: unlink("$dir/$item");
12328: } elsif (-d "$dir/$item") {
12329: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12330: }
12331: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12332: }
12333: }
12334: }
12335: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12336: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12337: }
12338: }
12339: } else {
12340: ($decompressed,$display) =
12341: &decompress_uploaded_file($file,$dir);
12342: }
12343: if ($decompressed eq 'ok') {
12344: $output = '<p class="LC_info">'.
12345: &mt('Files extracted successfully from archive.').
12346: '</p>'."\n";
12347: my ($warning,$result,@contents);
12348: my ($newdirlistref,$newlisterror) =
12349: &Apache::lonnet::dirlist($currdir,$docudom,
12350: $docuname,1);
12351: my (%is_dir,%changes,@newitems);
12352: my $dirptr = 16384;
12353: if (ref($newdirlistref) eq 'ARRAY') {
12354: foreach my $dir_line (@{$newdirlistref}) {
12355: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12356: unless (($item =~ /^\.+$/) || ($item eq $file)) {
12357: push(@newitems,$item);
12358: if ($dirptr&$testdir) {
12359: $is_dir{$item} = 1;
12360: }
12361: $changes{$item} = 1;
12362: }
12363: }
12364: }
12365: if (keys(%changes) > 0) {
12366: foreach my $item (sort(@newitems)) {
12367: if ($changes{$item}) {
12368: push(@contents,$item);
12369: }
12370: }
12371: }
12372: if (@contents > 0) {
12373: my $wantform;
12374: unless ($env{'form.autoextract_camtasia'}) {
12375: $wantform = 1;
12376: }
12377: my (%children,%parent,%dirorder,%titles);
12378: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12379: $currdir,\%is_dir,
12380: \%children,\%parent,
12381: \@contents,\%dirorder,
12382: \%titles,$wantform);
12383: if ($datatable ne '') {
12384: $output .= &archive_options_form('decompressed',$datatable,
12385: $count,$hiddenelem);
12386: my $startcount = 6;
12387: $output .= &archive_javascript($startcount,$count,
12388: \%titles,\%children);
12389: }
12390: if ($env{'form.autoextract_camtasia'}) {
12391: my $version = $env{'form.autoextract_camtasia'};
12392: my %displayed;
12393: my $total = 1;
12394: $env{'form.archive_directory'} = [];
12395: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12396: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12397: $path =~ s{/$}{};
12398: my $item;
12399: if ($path ne '') {
12400: $item = "$path/$titles{$i}";
12401: } else {
12402: $item = $titles{$i};
12403: }
12404: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12405: if ($item eq $contents[0]) {
12406: push(@{$env{'form.archive_directory'}},$i);
12407: $env{'form.archive_'.$i} = 'display';
12408: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12409: $displayed{'folder'} = $i;
12410: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12411: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12412: $env{'form.archive_'.$i} = 'display';
12413: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12414: $displayed{'web'} = $i;
12415: } else {
12416: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12417: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12418: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12419: push(@{$env{'form.archive_directory'}},$i);
12420: }
12421: $env{'form.archive_'.$i} = 'dependency';
12422: }
12423: $total ++;
12424: }
12425: for (my $i=1; $i<$total; $i++) {
12426: next if ($i == $displayed{'web'});
12427: next if ($i == $displayed{'folder'});
12428: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12429: }
12430: $env{'form.phase'} = 'decompress_cleanup';
12431: $env{'form.archivedelete'} = 1;
12432: $env{'form.archive_count'} = $total-1;
12433: $output .=
12434: &process_extracted_files('coursedocs',$docudom,
12435: $docuname,$destination,
12436: $dir_root,$hiddenelem);
12437: }
12438: } else {
12439: $warning = &mt('No new items extracted from archive file.');
12440: }
12441: } else {
12442: $output = $display;
12443: $error = &mt('An error occurred during extraction from the archive file.');
12444: }
12445: }
12446: }
12447: }
12448: if ($error) {
12449: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12450: $error.'</p>'."\n";
12451: }
12452: if ($warning) {
12453: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12454: }
12455: return $output;
12456: }
12457:
12458: sub get_extracted {
12459: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12460: $titles,$wantform) = @_;
12461: my $count = 0;
12462: my $depth = 0;
12463: my $datatable;
12464: my @hierarchy;
12465: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12466: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12467: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12468: foreach my $item (@{$contents}) {
12469: $count ++;
12470: @{$dirorder->{$count}} = @hierarchy;
12471: $titles->{$count} = $item;
12472: &archive_hierarchy($depth,$count,$parent,$children);
12473: if ($wantform) {
12474: $datatable .= &archive_row($is_dir->{$item},$item,
12475: $currdir,$depth,$count);
12476: }
12477: if ($is_dir->{$item}) {
12478: $depth ++;
12479: push(@hierarchy,$count);
12480: $parent->{$depth} = $count;
12481: $datatable .=
12482: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12483: \$depth,\$count,\@hierarchy,$dirorder,
12484: $children,$parent,$titles,$wantform);
12485: $depth --;
12486: pop(@hierarchy);
12487: }
12488: }
12489: return ($count,$datatable);
12490: }
12491:
12492: sub recurse_extracted_archive {
12493: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12494: $children,$parent,$titles,$wantform) = @_;
12495: my $result='';
12496: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12497: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12498: (ref($dirorder) eq 'HASH')) {
12499: return $result;
12500: }
12501: my $dirptr = 16384;
12502: my ($newdirlistref,$newlisterror) =
12503: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12504: if (ref($newdirlistref) eq 'ARRAY') {
12505: foreach my $dir_line (@{$newdirlistref}) {
12506: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12507: unless ($item =~ /^\.+$/) {
12508: $$count ++;
12509: @{$dirorder->{$$count}} = @{$hierarchy};
12510: $titles->{$$count} = $item;
12511: &archive_hierarchy($$depth,$$count,$parent,$children);
12512:
12513: my $is_dir;
12514: if ($dirptr&$testdir) {
12515: $is_dir = 1;
12516: }
12517: if ($wantform) {
12518: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12519: }
12520: if ($is_dir) {
12521: $$depth ++;
12522: push(@{$hierarchy},$$count);
12523: $parent->{$$depth} = $$count;
12524: $result .=
12525: &recurse_extracted_archive("$currdir/$item",$docudom,
12526: $docuname,$depth,$count,
12527: $hierarchy,$dirorder,$children,
12528: $parent,$titles,$wantform);
12529: $$depth --;
12530: pop(@{$hierarchy});
12531: }
12532: }
12533: }
12534: }
12535: return $result;
12536: }
12537:
12538: sub archive_hierarchy {
12539: my ($depth,$count,$parent,$children) =@_;
12540: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12541: if (exists($parent->{$depth})) {
12542: $children->{$parent->{$depth}} .= $count.':';
12543: }
12544: }
12545: return;
12546: }
12547:
12548: sub archive_row {
12549: my ($is_dir,$item,$currdir,$depth,$count) = @_;
12550: my ($name) = ($item =~ m{([^/]+)$});
12551: my %choices = &Apache::lonlocal::texthash (
12552: 'display' => 'Add as file',
12553: 'dependency' => 'Include as dependency',
12554: 'discard' => 'Discard',
12555: );
12556: if ($is_dir) {
12557: $choices{'display'} = &mt('Add as folder');
12558: }
12559: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12560: my $offset = 0;
12561: foreach my $action ('display','dependency','discard') {
12562: $offset ++;
12563: if ($action ne 'display') {
12564: $offset ++;
12565: }
12566: $output .= '<td><span class="LC_nobreak">'.
12567: '<label><input type="radio" name="archive_'.$count.
12568: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12569: my $text = $choices{$action};
12570: if ($is_dir) {
12571: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12572: if ($action eq 'display') {
12573: $text = &mt('Add as folder');
12574: }
12575: } else {
12576: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12577:
12578: }
12579: $output .= ' /> '.$choices{$action}.'</label></span>';
12580: if ($action eq 'dependency') {
12581: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12582: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
12583: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12584: '<option value=""></option>'."\n".
12585: '</select>'."\n".
12586: '</div>';
12587: } elsif ($action eq 'display') {
12588: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12589: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12590: '</div>';
12591: }
12592: $output .= '</td>';
12593: }
12594: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12595: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
12596: for (my $i=0; $i<$depth; $i++) {
12597: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12598: }
12599: if ($is_dir) {
12600: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
12601: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12602: } else {
12603: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12604: }
12605: $output .= ' '.$name.'</td>'."\n".
12606: &end_data_table_row();
12607: return $output;
12608: }
12609:
12610: sub archive_options_form {
12611: my ($form,$display,$count,$hiddenelem) = @_;
12612: my %lt = &Apache::lonlocal::texthash(
12613: perm => 'Permanently remove archive file?',
12614: hows => 'How should each extracted item be incorporated in the course?',
12615: cont => 'Content actions for all',
12616: addf => 'Add as folder/file',
12617: incd => 'Include as dependency for a displayed file',
12618: disc => 'Discard',
12619: no => 'No',
12620: yes => 'Yes',
12621: save => 'Save',
12622: );
12623: my $output = <<"END";
12624: <form name="$form" method="post" action="">
12625: <p><span class="LC_nobreak">$lt{'perm'}
12626: <label>
12627: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12628: </label>
12629:
12630: <label>
12631: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12632: </span>
12633: </p>
12634: <input type="hidden" name="phase" value="decompress_cleanup" />
12635: <br />$lt{'hows'}
12636: <div class="LC_columnSection">
12637: <fieldset>
12638: <legend>$lt{'cont'}</legend>
12639: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
12640: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12641: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12642: </fieldset>
12643: </div>
12644: END
12645: return $output.
12646: &start_data_table()."\n".
12647: $display."\n".
12648: &end_data_table()."\n".
12649: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12650: $hiddenelem.
12651: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12652: '</form>';
12653: }
12654:
12655: sub archive_javascript {
12656: my ($startcount,$numitems,$titles,$children) = @_;
12657: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12658: my $maintitle = $env{'form.comment'};
12659: my $scripttag = <<START;
12660: <script type="text/javascript">
12661: // <![CDATA[
12662:
12663: function checkAll(form,prefix) {
12664: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
12665: for (var i=0; i < form.elements.length; i++) {
12666: var id = form.elements[i].id;
12667: if ((id != '') && (id != undefined)) {
12668: if (idstr.test(id)) {
12669: if (form.elements[i].type == 'radio') {
12670: form.elements[i].checked = true;
12671: var nostart = i-$startcount;
12672: var offset = nostart%7;
12673: var count = (nostart-offset)/7;
12674: dependencyCheck(form,count,offset);
12675: }
12676: }
12677: }
12678: }
12679: }
12680:
12681: function propagateCheck(form,count) {
12682: if (count > 0) {
12683: var startelement = $startcount + ((count-1) * 7);
12684: for (var j=1; j<6; j++) {
12685: if ((j != 2) && (j != 4)) {
12686: var item = startelement + j;
12687: if (form.elements[item].type == 'radio') {
12688: if (form.elements[item].checked) {
12689: containerCheck(form,count,j);
12690: break;
12691: }
12692: }
12693: }
12694: }
12695: }
12696: }
12697:
12698: numitems = $numitems
12699: var titles = new Array(numitems);
12700: var parents = new Array(numitems);
12701: for (var i=0; i<numitems; i++) {
12702: parents[i] = new Array;
12703: }
12704: var maintitle = '$maintitle';
12705:
12706: START
12707:
12708: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12709: my @contents = split(/:/,$children->{$container});
12710: for (my $i=0; $i<@contents; $i ++) {
12711: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12712: }
12713: }
12714:
12715: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12716: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12717: }
12718:
12719: $scripttag .= <<END;
12720:
12721: function containerCheck(form,count,offset) {
12722: if (count > 0) {
12723: dependencyCheck(form,count,offset);
12724: var item = (offset+$startcount)+7*(count-1);
12725: form.elements[item].checked = true;
12726: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12727: if (parents[count].length > 0) {
12728: for (var j=0; j<parents[count].length; j++) {
12729: containerCheck(form,parents[count][j],offset);
12730: }
12731: }
12732: }
12733: }
12734: }
12735:
12736: function dependencyCheck(form,count,offset) {
12737: if (count > 0) {
12738: var chosen = (offset+$startcount)+7*(count-1);
12739: var depitem = $startcount + ((count-1) * 7) + 4;
12740: var currtype = form.elements[depitem].type;
12741: if (form.elements[chosen].value == 'dependency') {
12742: document.getElementById('arc_depon_'+count).style.display='block';
12743: form.elements[depitem].options.length = 0;
12744: form.elements[depitem].options[0] = new Option('Select','',true,true);
12745: for (var i=1; i<=numitems; i++) {
12746: if (i == count) {
12747: continue;
12748: }
12749: var startelement = $startcount + (i-1) * 7;
12750: for (var j=1; j<6; j++) {
12751: if ((j != 2) && (j!= 4)) {
12752: var item = startelement + j;
12753: if (form.elements[item].type == 'radio') {
12754: if (form.elements[item].checked) {
12755: if (form.elements[item].value == 'display') {
12756: var n = form.elements[depitem].options.length;
12757: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12758: }
12759: }
12760: }
12761: }
12762: }
12763: }
12764: } else {
12765: document.getElementById('arc_depon_'+count).style.display='none';
12766: form.elements[depitem].options.length = 0;
12767: form.elements[depitem].options[0] = new Option('Select','',true,true);
12768: }
12769: titleCheck(form,count,offset);
12770: }
12771: }
12772:
12773: function propagateSelect(form,count,offset) {
12774: if (count > 0) {
12775: var item = (1+offset+$startcount)+7*(count-1);
12776: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
12777: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12778: if (parents[count].length > 0) {
12779: for (var j=0; j<parents[count].length; j++) {
12780: containerSelect(form,parents[count][j],offset,picked);
12781: }
12782: }
12783: }
12784: }
12785: }
12786:
12787: function containerSelect(form,count,offset,picked) {
12788: if (count > 0) {
12789: var item = (offset+$startcount)+7*(count-1);
12790: if (form.elements[item].type == 'radio') {
12791: if (form.elements[item].value == 'dependency') {
12792: if (form.elements[item+1].type == 'select-one') {
12793: for (var i=0; i<form.elements[item+1].options.length; i++) {
12794: if (form.elements[item+1].options[i].value == picked) {
12795: form.elements[item+1].selectedIndex = i;
12796: break;
12797: }
12798: }
12799: }
12800: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12801: if (parents[count].length > 0) {
12802: for (var j=0; j<parents[count].length; j++) {
12803: containerSelect(form,parents[count][j],offset,picked);
12804: }
12805: }
12806: }
12807: }
12808: }
12809: }
12810: }
12811:
12812: function titleCheck(form,count,offset) {
12813: if (count > 0) {
12814: var chosen = (offset+$startcount)+7*(count-1);
12815: var depitem = $startcount + ((count-1) * 7) + 2;
12816: var currtype = form.elements[depitem].type;
12817: if (form.elements[chosen].value == 'display') {
12818: document.getElementById('arc_title_'+count).style.display='block';
12819: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12820: document.getElementById('archive_title_'+count).value=maintitle;
12821: }
12822: } else {
12823: document.getElementById('arc_title_'+count).style.display='none';
12824: if (currtype == 'text') {
12825: document.getElementById('archive_title_'+count).value='';
12826: }
12827: }
12828: }
12829: return;
12830: }
12831:
12832: // ]]>
12833: </script>
12834: END
12835: return $scripttag;
12836: }
12837:
12838: sub process_extracted_files {
12839: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12840: my $numitems = $env{'form.archive_count'};
12841: return if ((!$numitems) || ($numitems =~ /\D/));
12842: my @ids=&Apache::lonnet::current_machine_ids();
12843: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12844: %folders,%containers,%mapinner,%prompttofetch);
12845: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12846: if (grep(/^\Q$docuhome\E$/,@ids)) {
12847: $prefix = &LONCAPA::propath($docudom,$docuname);
12848: $pathtocheck = "$dir_root/$destination";
12849: $dir = $dir_root;
12850: $ishome = 1;
12851: } else {
12852: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12853: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12854: $dir = "$dir_root/$docudom/$docuname";
12855: }
12856: my $currdir = "$dir_root/$destination";
12857: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12858: if ($env{'form.folderpath'}) {
12859: my @items = split('&',$env{'form.folderpath'});
12860: $folders{'0'} = $items[-2];
12861: if ($env{'form.folderpath'} =~ /\:1$/) {
12862: $containers{'0'}='page';
12863: } else {
12864: $containers{'0'}='sequence';
12865: }
12866: }
12867: my @archdirs = &get_env_multiple('form.archive_directory');
12868: if ($numitems) {
12869: for (my $i=1; $i<=$numitems; $i++) {
12870: my $path = $env{'form.archive_content_'.$i};
12871: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12872: my $item = $1;
12873: $toplevelitems{$item} = $i;
12874: if (grep(/^\Q$i\E$/,@archdirs)) {
12875: $is_dir{$item} = 1;
12876: }
12877: }
12878: }
12879: }
12880: my ($output,%children,%parent,%titles,%dirorder,$result);
12881: if (keys(%toplevelitems) > 0) {
12882: my @contents = sort(keys(%toplevelitems));
12883: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12884: \%parent,\@contents,\%dirorder,\%titles);
12885: }
12886: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12887: if ($numitems) {
12888: for (my $i=1; $i<=$numitems; $i++) {
12889: next if ($env{'form.archive_'.$i} eq 'dependency');
12890: my $path = $env{'form.archive_content_'.$i};
12891: if ($path =~ /^\Q$pathtocheck\E/) {
12892: if ($env{'form.archive_'.$i} eq 'discard') {
12893: if ($prefix ne '' && $path ne '') {
12894: if (-e $prefix.$path) {
12895: if ((@archdirs > 0) &&
12896: (grep(/^\Q$i\E$/,@archdirs))) {
12897: $todeletedir{$prefix.$path} = 1;
12898: } else {
12899: $todelete{$prefix.$path} = 1;
12900: }
12901: }
12902: }
12903: } elsif ($env{'form.archive_'.$i} eq 'display') {
12904: my ($docstitle,$title,$url,$outer);
12905: ($title) = ($path =~ m{/([^/]+)$});
12906: $docstitle = $env{'form.archive_title_'.$i};
12907: if ($docstitle eq '') {
12908: $docstitle = $title;
12909: }
12910: $outer = 0;
12911: if (ref($dirorder{$i}) eq 'ARRAY') {
12912: if (@{$dirorder{$i}} > 0) {
12913: foreach my $item (reverse(@{$dirorder{$i}})) {
12914: if ($env{'form.archive_'.$item} eq 'display') {
12915: $outer = $item;
12916: last;
12917: }
12918: }
12919: }
12920: }
12921: my ($errtext,$fatal) =
12922: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12923: '/'.$folders{$outer}.'.'.
12924: $containers{$outer});
12925: next if ($fatal);
12926: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12927: if ($context eq 'coursedocs') {
12928: $mapinner{$i} = time;
12929: $folders{$i} = 'default_'.$mapinner{$i};
12930: $containers{$i} = 'sequence';
12931: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12932: $folders{$i}.'.'.$containers{$i};
12933: my $newidx = &LONCAPA::map::getresidx();
12934: $LONCAPA::map::resources[$newidx]=
12935: $docstitle.':'.$url.':false:normal:res';
12936: push(@LONCAPA::map::order,$newidx);
12937: my ($outtext,$errtext) =
12938: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12939: $docuname.'/'.$folders{$outer}.
12940: '.'.$containers{$outer},1,1);
12941: $newseqid{$i} = $newidx;
12942: unless ($errtext) {
12943: $result .= '<li>'.&mt('Folder: [_1] added to course',
12944: &HTML::Entities::encode($docstitle,'<>&"'))..
12945: '</li>'."\n";
12946: }
12947: }
12948: } else {
12949: if ($context eq 'coursedocs') {
12950: my $newidx=&LONCAPA::map::getresidx();
12951: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12952: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12953: $title;
12954: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12955: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12956: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12957: }
12958: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12959: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12960: }
12961: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12962: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12963: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12964: unless ($ishome) {
12965: my $fetch = "$newdest{$i}/$title";
12966: $fetch =~ s/^\Q$prefix$dir\E//;
12967: $prompttofetch{$fetch} = 1;
12968: }
12969: }
12970: }
12971: $LONCAPA::map::resources[$newidx]=
12972: $docstitle.':'.$url.':false:normal:res';
12973: push(@LONCAPA::map::order, $newidx);
12974: my ($outtext,$errtext)=
12975: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12976: $docuname.'/'.$folders{$outer}.
12977: '.'.$containers{$outer},1,1);
12978: unless ($errtext) {
12979: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12980: $result .= '<li>'.&mt('File: [_1] added to course',
12981: &HTML::Entities::encode($docstitle,'<>&"')).
12982: '</li>'."\n";
12983: }
12984: }
12985: } else {
12986: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12987: &HTML::Entities::encode($path,'<>&"')).'<br />';
12988: }
12989: }
12990: }
12991: }
12992: } else {
12993: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12994: &HTML::Entities::encode($path,'<>&"')).'<br />';
12995: }
12996: }
12997: for (my $i=1; $i<=$numitems; $i++) {
12998: next unless ($env{'form.archive_'.$i} eq 'dependency');
12999: my $path = $env{'form.archive_content_'.$i};
13000: if ($path =~ /^\Q$pathtocheck\E/) {
13001: my ($title) = ($path =~ m{/([^/]+)$});
13002: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13003: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13004: if (ref($dirorder{$i}) eq 'ARRAY') {
13005: my ($itemidx,$fullpath,$relpath);
13006: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13007: my $container = $dirorder{$referrer{$i}}->[-1];
13008: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13009: if ($dirorder{$i}->[$j] eq $container) {
13010: $itemidx = $j;
13011: }
13012: }
13013: }
13014: if ($itemidx eq '') {
13015: $itemidx = 0;
13016: }
13017: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13018: if ($mapinner{$referrer{$i}}) {
13019: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13020: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13021: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13022: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13023: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13024: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13025: if (!-e $fullpath) {
13026: mkdir($fullpath,0755);
13027: }
13028: }
13029: } else {
13030: last;
13031: }
13032: }
13033: }
13034: } elsif ($newdest{$referrer{$i}}) {
13035: $fullpath = $newdest{$referrer{$i}};
13036: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13037: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13038: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13039: last;
13040: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13041: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13042: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13043: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13044: if (!-e $fullpath) {
13045: mkdir($fullpath,0755);
13046: }
13047: }
13048: } else {
13049: last;
13050: }
13051: }
13052: }
13053: if ($fullpath ne '') {
13054: if (-e "$prefix$path") {
13055: unless (rename("$prefix$path","$fullpath/$title")) {
13056: $warning .= &mt('Failed to rename dependency').'<br />';
13057: }
13058: }
13059: if (-e "$fullpath/$title") {
13060: my $showpath;
13061: if ($relpath ne '') {
13062: $showpath = "$relpath/$title";
13063: } else {
13064: $showpath = "/$title";
13065: }
13066: $result .= '<li>'.&mt('[_1] included as a dependency',
13067: &HTML::Entities::encode($showpath,'<>&"')).
13068: '</li>'."\n";
13069: unless ($ishome) {
13070: my $fetch = "$fullpath/$title";
13071: $fetch =~ s/^\Q$prefix$dir\E//;
13072: $prompttofetch{$fetch} = 1;
13073: }
13074: }
13075: }
13076: }
13077: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13078: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13079: &HTML::Entities::encode($path,'<>&"'),
13080: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13081: '<br />';
13082: }
13083: } else {
13084: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13085: &HTML::Entities::encode($path)).'<br />';
13086: }
13087: }
13088: if (keys(%todelete)) {
13089: foreach my $key (keys(%todelete)) {
13090: unlink($key);
13091: }
13092: }
13093: if (keys(%todeletedir)) {
13094: foreach my $key (keys(%todeletedir)) {
13095: rmdir($key);
13096: }
13097: }
13098: foreach my $dir (sort(keys(%is_dir))) {
13099: if (($pathtocheck ne '') && ($dir ne '')) {
13100: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13101: }
13102: }
13103: if ($result ne '') {
13104: $output .= '<ul>'."\n".
13105: $result."\n".
13106: '</ul>';
13107: }
13108: unless ($ishome) {
13109: my $replicationfail;
13110: foreach my $item (keys(%prompttofetch)) {
13111: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13112: unless ($fetchresult eq 'ok') {
13113: $replicationfail .= '<li>'.$item.'</li>'."\n";
13114: }
13115: }
13116: if ($replicationfail) {
13117: $output .= '<p class="LC_error">'.
13118: &mt('Course home server failed to retrieve:').'<ul>'.
13119: $replicationfail.
13120: '</ul></p>';
13121: }
13122: }
13123: } else {
13124: $warning = &mt('No items found in archive.');
13125: }
13126: if ($error) {
13127: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13128: $error.'</p>'."\n";
13129: }
13130: if ($warning) {
13131: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13132: }
13133: return $output;
13134: }
13135:
13136: sub cleanup_empty_dirs {
13137: my ($path) = @_;
13138: if (($path ne '') && (-d $path)) {
13139: if (opendir(my $dirh,$path)) {
13140: my @dircontents = grep(!/^\./,readdir($dirh));
13141: my $numitems = 0;
13142: foreach my $item (@dircontents) {
13143: if (-d "$path/$item") {
13144: &cleanup_empty_dirs("$path/$item");
13145: if (-e "$path/$item") {
13146: $numitems ++;
13147: }
13148: } else {
13149: $numitems ++;
13150: }
13151: }
13152: if ($numitems == 0) {
13153: rmdir($path);
13154: }
13155: closedir($dirh);
13156: }
13157: }
13158: return;
13159: }
13160:
13161: =pod
13162:
13163: =item * &get_folder_hierarchy()
13164:
13165: Provides hierarchy of names of folders/sub-folders containing the current
13166: item,
13167:
13168: Inputs: 3
13169: - $navmap - navmaps object
13170:
13171: - $map - url for map (either the trigger itself, or map containing
13172: the resource, which is the trigger).
13173:
13174: - $showitem - 1 => show title for map itself; 0 => do not show.
13175:
13176: Outputs: 1 @pathitems - array of folder/subfolder names.
13177:
13178: =cut
13179:
13180: sub get_folder_hierarchy {
13181: my ($navmap,$map,$showitem) = @_;
13182: my @pathitems;
13183: if (ref($navmap)) {
13184: my $mapres = $navmap->getResourceByUrl($map);
13185: if (ref($mapres)) {
13186: my $pcslist = $mapres->map_hierarchy();
13187: if ($pcslist ne '') {
13188: my @pcs = split(/,/,$pcslist);
13189: foreach my $pc (@pcs) {
13190: if ($pc == 1) {
13191: push(@pathitems,&mt('Main Content'));
13192: } else {
13193: my $res = $navmap->getByMapPc($pc);
13194: if (ref($res)) {
13195: my $title = $res->compTitle();
13196: $title =~ s/\W+/_/g;
13197: if ($title ne '') {
13198: push(@pathitems,$title);
13199: }
13200: }
13201: }
13202: }
13203: }
13204: if ($showitem) {
13205: if ($mapres->{ID} eq '0.0') {
13206: push(@pathitems,&mt('Main Content'));
13207: } else {
13208: my $maptitle = $mapres->compTitle();
13209: $maptitle =~ s/\W+/_/g;
13210: if ($maptitle ne '') {
13211: push(@pathitems,$maptitle);
13212: }
13213: }
13214: }
13215: }
13216: }
13217: return @pathitems;
13218: }
13219:
13220: =pod
13221:
13222: =item * &get_turnedin_filepath()
13223:
13224: Determines path in a user's portfolio file for storage of files uploaded
13225: to a specific essayresponse or dropbox item.
13226:
13227: Inputs: 3 required + 1 optional.
13228: $symb is symb for resource, $uname and $udom are for current user (required).
13229: $caller is optional (can be "submission", if routine is called when storing
13230: an upoaded file when "Submit Answer" button was pressed).
13231:
13232: Returns array containing $path and $multiresp.
13233: $path is path in portfolio. $multiresp is 1 if this resource contains more
13234: than one file upload item. Callers of routine should append partid as a
13235: subdirectory to $path in cases where $multiresp is 1.
13236:
13237: Called by: homework/essayresponse.pm and homework/structuretags.pm
13238:
13239: =cut
13240:
13241: sub get_turnedin_filepath {
13242: my ($symb,$uname,$udom,$caller) = @_;
13243: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13244: my $turnindir;
13245: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13246: $turnindir = $userhash{'turnindir'};
13247: my ($path,$multiresp);
13248: if ($turnindir eq '') {
13249: if ($caller eq 'submission') {
13250: $turnindir = &mt('turned in');
13251: $turnindir =~ s/\W+/_/g;
13252: my %newhash = (
13253: 'turnindir' => $turnindir,
13254: );
13255: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13256: }
13257: }
13258: if ($turnindir ne '') {
13259: $path = '/'.$turnindir.'/';
13260: my ($multipart,$turnin,@pathitems);
13261: my $navmap = Apache::lonnavmaps::navmap->new();
13262: if (defined($navmap)) {
13263: my $mapres = $navmap->getResourceByUrl($map);
13264: if (ref($mapres)) {
13265: my $pcslist = $mapres->map_hierarchy();
13266: if ($pcslist ne '') {
13267: foreach my $pc (split(/,/,$pcslist)) {
13268: my $res = $navmap->getByMapPc($pc);
13269: if (ref($res)) {
13270: my $title = $res->compTitle();
13271: $title =~ s/\W+/_/g;
13272: if ($title ne '') {
13273: if (($pc > 1) && (length($title) > 12)) {
13274: $title = substr($title,0,12);
13275: }
13276: push(@pathitems,$title);
13277: }
13278: }
13279: }
13280: }
13281: my $maptitle = $mapres->compTitle();
13282: $maptitle =~ s/\W+/_/g;
13283: if ($maptitle ne '') {
13284: if (length($maptitle) > 12) {
13285: $maptitle = substr($maptitle,0,12);
13286: }
13287: push(@pathitems,$maptitle);
13288: }
13289: unless ($env{'request.state'} eq 'construct') {
13290: my $res = $navmap->getBySymb($symb);
13291: if (ref($res)) {
13292: my $partlist = $res->parts();
13293: my $totaluploads = 0;
13294: if (ref($partlist) eq 'ARRAY') {
13295: foreach my $part (@{$partlist}) {
13296: my @types = $res->responseType($part);
13297: my @ids = $res->responseIds($part);
13298: for (my $i=0; $i < scalar(@ids); $i++) {
13299: if ($types[$i] eq 'essay') {
13300: my $partid = $part.'_'.$ids[$i];
13301: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13302: $totaluploads ++;
13303: }
13304: }
13305: }
13306: }
13307: if ($totaluploads > 1) {
13308: $multiresp = 1;
13309: }
13310: }
13311: }
13312: }
13313: } else {
13314: return;
13315: }
13316: } else {
13317: return;
13318: }
13319: my $restitle=&Apache::lonnet::gettitle($symb);
13320: $restitle =~ s/\W+/_/g;
13321: if ($restitle eq '') {
13322: $restitle = ($resurl =~ m{/[^/]+$});
13323: if ($restitle eq '') {
13324: $restitle = time;
13325: }
13326: }
13327: if (length($restitle) > 12) {
13328: $restitle = substr($restitle,0,12);
13329: }
13330: push(@pathitems,$restitle);
13331: $path .= join('/',@pathitems);
13332: }
13333: return ($path,$multiresp);
13334: }
13335:
13336: =pod
13337:
13338: =back
13339:
13340: =head1 CSV Upload/Handling functions
13341:
13342: =over 4
13343:
13344: =item * &upfile_store($r)
13345:
13346: Store uploaded file, $r should be the HTTP Request object,
13347: needs $env{'form.upfile'}
13348: returns $datatoken to be put into hidden field
13349:
13350: =cut
13351:
13352: sub upfile_store {
13353: my $r=shift;
13354: $env{'form.upfile'}=~s/\r/\n/gs;
13355: $env{'form.upfile'}=~s/\f/\n/gs;
13356: $env{'form.upfile'}=~s/\n+/\n/gs;
13357: $env{'form.upfile'}=~s/\n+$//gs;
13358:
13359: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13360: '_enroll_'.$env{'request.course.id'}.'_'.
13361: time.'_'.$$);
13362: return if ($datatoken eq '');
13363:
13364: {
13365: my $datafile = $r->dir_config('lonDaemons').
13366: '/tmp/'.$datatoken.'.tmp';
13367: if ( open(my $fh,'>',$datafile) ) {
13368: print $fh $env{'form.upfile'};
13369: close($fh);
13370: }
13371: }
13372: return $datatoken;
13373: }
13374:
13375: =pod
13376:
13377: =item * &load_tmp_file($r,$datatoken)
13378:
13379: Load uploaded file from tmp, $r should be the HTTP Request object,
13380: $datatoken is the name to assign to the temporary file.
13381: sets $env{'form.upfile'} to the contents of the file
13382:
13383: =cut
13384:
13385: sub load_tmp_file {
13386: my ($r,$datatoken) = @_;
13387: return if ($datatoken eq '');
13388: my @studentdata=();
13389: {
13390: my $studentfile = $r->dir_config('lonDaemons').
13391: '/tmp/'.$datatoken.'.tmp';
13392: if ( open(my $fh,'<',$studentfile) ) {
13393: @studentdata=<$fh>;
13394: close($fh);
13395: }
13396: }
13397: $env{'form.upfile'}=join('',@studentdata);
13398: }
13399:
13400: sub valid_datatoken {
13401: my ($datatoken) = @_;
13402: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13403: return $datatoken;
13404: }
13405: return;
13406: }
13407:
13408: =pod
13409:
13410: =item * &upfile_record_sep()
13411:
13412: Separate uploaded file into records
13413: returns array of records,
13414: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13415:
13416: =cut
13417:
13418: sub upfile_record_sep {
13419: if ($env{'form.upfiletype'} eq 'xml') {
13420: } else {
13421: my @records;
13422: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13423: if ($line=~/^\s*$/) { next; }
13424: push(@records,$line);
13425: }
13426: return @records;
13427: }
13428: }
13429:
13430: =pod
13431:
13432: =item * &record_sep($record)
13433:
13434: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13435:
13436: =cut
13437:
13438: sub takeleft {
13439: my $index=shift;
13440: return substr('0000'.$index,-4,4);
13441: }
13442:
13443: sub record_sep {
13444: my $record=shift;
13445: my %components=();
13446: if ($env{'form.upfiletype'} eq 'xml') {
13447: } elsif ($env{'form.upfiletype'} eq 'space') {
13448: my $i=0;
13449: foreach my $field (split(/\s+/,$record)) {
13450: $field=~s/^(\"|\')//;
13451: $field=~s/(\"|\')$//;
13452: $components{&takeleft($i)}=$field;
13453: $i++;
13454: }
13455: } elsif ($env{'form.upfiletype'} eq 'tab') {
13456: my $i=0;
13457: foreach my $field (split(/\t/,$record)) {
13458: $field=~s/^(\"|\')//;
13459: $field=~s/(\"|\')$//;
13460: $components{&takeleft($i)}=$field;
13461: $i++;
13462: }
13463: } else {
13464: my $separator=',';
13465: if ($env{'form.upfiletype'} eq 'semisv') {
13466: $separator=';';
13467: }
13468: my $i=0;
13469: # the character we are looking for to indicate the end of a quote or a record
13470: my $looking_for=$separator;
13471: # do not add the characters to the fields
13472: my $ignore=0;
13473: # we just encountered a separator (or the beginning of the record)
13474: my $just_found_separator=1;
13475: # store the field we are working on here
13476: my $field='';
13477: # work our way through all characters in record
13478: foreach my $character ($record=~/(.)/g) {
13479: if ($character eq $looking_for) {
13480: if ($character ne $separator) {
13481: # Found the end of a quote, again looking for separator
13482: $looking_for=$separator;
13483: $ignore=1;
13484: } else {
13485: # Found a separator, store away what we got
13486: $components{&takeleft($i)}=$field;
13487: $i++;
13488: $just_found_separator=1;
13489: $ignore=0;
13490: $field='';
13491: }
13492: next;
13493: }
13494: # single or double quotation marks after a separator indicate beginning of a quote
13495: # we are now looking for the end of the quote and need to ignore separators
13496: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13497: $looking_for=$character;
13498: next;
13499: }
13500: # ignore would be true after we reached the end of a quote
13501: if ($ignore) { next; }
13502: if (($just_found_separator) && ($character=~/\s/)) { next; }
13503: $field.=$character;
13504: $just_found_separator=0;
13505: }
13506: # catch the very last entry, since we never encountered the separator
13507: $components{&takeleft($i)}=$field;
13508: }
13509: return %components;
13510: }
13511:
13512: ######################################################
13513: ######################################################
13514:
13515: =pod
13516:
13517: =item * &upfile_select_html()
13518:
13519: Return HTML code to select a file from the users machine and specify
13520: the file type.
13521:
13522: =cut
13523:
13524: ######################################################
13525: ######################################################
13526: sub upfile_select_html {
13527: my %Types = (
13528: csv => &mt('CSV (comma separated values, spreadsheet)'),
13529: semisv => &mt('Semicolon separated values'),
13530: space => &mt('Space separated'),
13531: tab => &mt('Tabulator separated'),
13532: # xml => &mt('HTML/XML'),
13533: );
13534: my $Str = '<input type="file" name="upfile" size="50" />'.
13535: '<br />'.&mt('Type').': <select name="upfiletype">';
13536: foreach my $type (sort(keys(%Types))) {
13537: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13538: }
13539: $Str .= "</select>\n";
13540: return $Str;
13541: }
13542:
13543: sub get_samples {
13544: my ($records,$toget) = @_;
13545: my @samples=({});
13546: my $got=0;
13547: foreach my $rec (@$records) {
13548: my %temp = &record_sep($rec);
13549: if (! grep(/\S/, values(%temp))) { next; }
13550: if (%temp) {
13551: $samples[$got]=\%temp;
13552: $got++;
13553: if ($got == $toget) { last; }
13554: }
13555: }
13556: return \@samples;
13557: }
13558:
13559: ######################################################
13560: ######################################################
13561:
13562: =pod
13563:
13564: =item * &csv_print_samples($r,$records)
13565:
13566: Prints a table of sample values from each column uploaded $r is an
13567: Apache Request ref, $records is an arrayref from
13568: &Apache::loncommon::upfile_record_sep
13569:
13570: =cut
13571:
13572: ######################################################
13573: ######################################################
13574: sub csv_print_samples {
13575: my ($r,$records) = @_;
13576: my $samples = &get_samples($records,5);
13577:
13578: $r->print(&mt('Samples').'<br />'.&start_data_table().
13579: &start_data_table_header_row());
13580: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13581: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13582: $r->print(&end_data_table_header_row());
13583: foreach my $hash (@$samples) {
13584: $r->print(&start_data_table_row());
13585: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13586: $r->print('<td>');
13587: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13588: $r->print('</td>');
13589: }
13590: $r->print(&end_data_table_row());
13591: }
13592: $r->print(&end_data_table().'<br />'."\n");
13593: }
13594:
13595: ######################################################
13596: ######################################################
13597:
13598: =pod
13599:
13600: =item * &csv_print_select_table($r,$records,$d)
13601:
13602: Prints a table to create associations between values and table columns.
13603:
13604: $r is an Apache Request ref,
13605: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13606: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13607:
13608: =cut
13609:
13610: ######################################################
13611: ######################################################
13612: sub csv_print_select_table {
13613: my ($r,$records,$d) = @_;
13614: my $i=0;
13615: my $samples = &get_samples($records,1);
13616: $r->print(&mt('Associate columns with student attributes.')."\n".
13617: &start_data_table().&start_data_table_header_row().
13618: '<th>'.&mt('Attribute').'</th>'.
13619: '<th>'.&mt('Column').'</th>'.
13620: &end_data_table_header_row()."\n");
13621: foreach my $array_ref (@$d) {
13622: my ($value,$display,$defaultcol)=@{ $array_ref };
13623: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
13624:
13625: $r->print('<td><select name="f'.$i.'"'.
13626: ' onchange="javascript:flip(this.form,'.$i.');">');
13627: $r->print('<option value="none"></option>');
13628: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13629: $r->print('<option value="'.$sample.'"'.
13630: ($sample eq $defaultcol ? ' selected="selected" ' : '').
13631: '>'.&mt('Column [_1]',($sample+1)).'</option>');
13632: }
13633: $r->print('</select></td>'.&end_data_table_row()."\n");
13634: $i++;
13635: }
13636: $r->print(&end_data_table());
13637: $i--;
13638: return $i;
13639: }
13640:
13641: ######################################################
13642: ######################################################
13643:
13644: =pod
13645:
13646: =item * &csv_samples_select_table($r,$records,$d)
13647:
13648: Prints a table of sample values from the upload and can make associate samples to internal names.
13649:
13650: $r is an Apache Request ref,
13651: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13652: $d is an array of 2 element arrays (internal name, displayed name)
13653:
13654: =cut
13655:
13656: ######################################################
13657: ######################################################
13658: sub csv_samples_select_table {
13659: my ($r,$records,$d) = @_;
13660: my $i=0;
13661: #
13662: my $max_samples = 5;
13663: my $samples = &get_samples($records,$max_samples);
13664: $r->print(&start_data_table().
13665: &start_data_table_header_row().'<th>'.
13666: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13667: &end_data_table_header_row());
13668:
13669: foreach my $key (sort(keys(%{ $samples->[0] }))) {
13670: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13671: ' onchange="javascript:flip(this.form,'.$i.');">');
13672: foreach my $option (@$d) {
13673: my ($value,$display,$defaultcol)=@{ $option };
13674: $r->print('<option value="'.$value.'"'.
13675: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13676: $display.'</option>');
13677: }
13678: $r->print('</select></td><td>');
13679: foreach my $line (0..($max_samples-1)) {
13680: if (defined($samples->[$line]{$key})) {
13681: $r->print($samples->[$line]{$key}."<br />\n");
13682: }
13683: }
13684: $r->print('</td>'.&end_data_table_row());
13685: $i++;
13686: }
13687: $r->print(&end_data_table());
13688: $i--;
13689: return($i);
13690: }
13691:
13692: ######################################################
13693: ######################################################
13694:
13695: =pod
13696:
13697: =item * &clean_excel_name($name)
13698:
13699: Returns a replacement for $name which does not contain any illegal characters.
13700:
13701: =cut
13702:
13703: ######################################################
13704: ######################################################
13705: sub clean_excel_name {
13706: my ($name) = @_;
13707: $name =~ s/[:\*\?\/\\]//g;
13708: if (length($name) > 31) {
13709: $name = substr($name,0,31);
13710: }
13711: return $name;
13712: }
13713:
13714: =pod
13715:
13716: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13717:
13718: Returns either 1 or undef
13719:
13720: 1 if the part is to be hidden, undef if it is to be shown
13721:
13722: Arguments are:
13723:
13724: $id the id of the part to be checked
13725: $symb, optional the symb of the resource to check
13726: $udom, optional the domain of the user to check for
13727: $uname, optional the username of the user to check for
13728:
13729: =cut
13730:
13731: sub check_if_partid_hidden {
13732: my ($id,$symb,$udom,$uname) = @_;
13733: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13734: $symb,$udom,$uname);
13735: my $truth=1;
13736: #if the string starts with !, then the list is the list to show not hide
13737: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13738: my @hiddenlist=split(/,/,$hiddenparts);
13739: foreach my $checkid (@hiddenlist) {
13740: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13741: }
13742: return !$truth;
13743: }
13744:
13745:
13746: ############################################################
13747: ############################################################
13748:
13749: =pod
13750:
13751: =back
13752:
13753: =head1 cgi-bin script and graphing routines
13754:
13755: =over 4
13756:
13757: =item * &get_cgi_id()
13758:
13759: Inputs: none
13760:
13761: Returns an id which can be used to pass environment variables
13762: to various cgi-bin scripts. These environment variables will
13763: be removed from the users environment after a given time by
13764: the routine &Apache::lonnet::transfer_profile_to_env.
13765:
13766: =cut
13767:
13768: ############################################################
13769: ############################################################
13770: my $uniq=0;
13771: sub get_cgi_id {
13772: $uniq=($uniq+1)%100000;
13773: return (time.'_'.$$.'_'.$uniq);
13774: }
13775:
13776: ############################################################
13777: ############################################################
13778:
13779: =pod
13780:
13781: =item * &DrawBarGraph()
13782:
13783: Facilitates the plotting of data in a (stacked) bar graph.
13784: Puts plot definition data into the users environment in order for
13785: graph.png to plot it. Returns an <img> tag for the plot.
13786: The bars on the plot are labeled '1','2',...,'n'.
13787:
13788: Inputs:
13789:
13790: =over 4
13791:
13792: =item $Title: string, the title of the plot
13793:
13794: =item $xlabel: string, text describing the X-axis of the plot
13795:
13796: =item $ylabel: string, text describing the Y-axis of the plot
13797:
13798: =item $Max: scalar, the maximum Y value to use in the plot
13799: If $Max is < any data point, the graph will not be rendered.
13800:
13801: =item $colors: array ref holding the colors to be used for the data sets when
13802: they are plotted. If undefined, default values will be used.
13803:
13804: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13805:
13806: =item @Values: An array of array references. Each array reference holds data
13807: to be plotted in a stacked bar chart.
13808:
13809: =item If the final element of @Values is a hash reference the key/value
13810: pairs will be added to the graph definition.
13811:
13812: =back
13813:
13814: Returns:
13815:
13816: An <img> tag which references graph.png and the appropriate identifying
13817: information for the plot.
13818:
13819: =cut
13820:
13821: ############################################################
13822: ############################################################
13823: sub DrawBarGraph {
13824: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13825: #
13826: if (! defined($colors)) {
13827: $colors = ['#33ff00',
13828: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13829: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13830: ];
13831: }
13832: my $extra_settings = {};
13833: if (ref($Values[-1]) eq 'HASH') {
13834: $extra_settings = pop(@Values);
13835: }
13836: #
13837: my $identifier = &get_cgi_id();
13838: my $id = 'cgi.'.$identifier;
13839: if (! @Values || ref($Values[0]) ne 'ARRAY') {
13840: return '';
13841: }
13842: #
13843: my @Labels;
13844: if (defined($labels)) {
13845: @Labels = @$labels;
13846: } else {
13847: for (my $i=0;$i<@{$Values[0]};$i++) {
13848: push(@Labels,$i+1);
13849: }
13850: }
13851: #
13852: my $NumBars = scalar(@{$Values[0]});
13853: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13854: my %ValuesHash;
13855: my $NumSets=1;
13856: foreach my $array (@Values) {
13857: next if (! ref($array));
13858: $ValuesHash{$id.'.data.'.$NumSets++} =
13859: join(',',@$array);
13860: }
13861: #
13862: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13863: if ($NumBars < 3) {
13864: $width = 120+$NumBars*32;
13865: $xskip = 1;
13866: $bar_width = 30;
13867: } elsif ($NumBars < 5) {
13868: $width = 120+$NumBars*20;
13869: $xskip = 1;
13870: $bar_width = 20;
13871: } elsif ($NumBars < 10) {
13872: $width = 120+$NumBars*15;
13873: $xskip = 1;
13874: $bar_width = 15;
13875: } elsif ($NumBars <= 25) {
13876: $width = 120+$NumBars*11;
13877: $xskip = 5;
13878: $bar_width = 8;
13879: } elsif ($NumBars <= 50) {
13880: $width = 120+$NumBars*8;
13881: $xskip = 5;
13882: $bar_width = 4;
13883: } else {
13884: $width = 120+$NumBars*8;
13885: $xskip = 5;
13886: $bar_width = 4;
13887: }
13888: #
13889: $Max = 1 if ($Max < 1);
13890: if ( int($Max) < $Max ) {
13891: $Max++;
13892: $Max = int($Max);
13893: }
13894: $Title = '' if (! defined($Title));
13895: $xlabel = '' if (! defined($xlabel));
13896: $ylabel = '' if (! defined($ylabel));
13897: $ValuesHash{$id.'.title'} = &escape($Title);
13898: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
13899: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
13900: $ValuesHash{$id.'.y_max_value'} = $Max;
13901: $ValuesHash{$id.'.NumBars'} = $NumBars;
13902: $ValuesHash{$id.'.NumSets'} = $NumSets;
13903: $ValuesHash{$id.'.PlotType'} = 'bar';
13904: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13905: $ValuesHash{$id.'.height'} = $height;
13906: $ValuesHash{$id.'.width'} = $width;
13907: $ValuesHash{$id.'.xskip'} = $xskip;
13908: $ValuesHash{$id.'.bar_width'} = $bar_width;
13909: $ValuesHash{$id.'.labels'} = join(',',@Labels);
13910: #
13911: # Deal with other parameters
13912: while (my ($key,$value) = each(%$extra_settings)) {
13913: $ValuesHash{$id.'.'.$key} = $value;
13914: }
13915: #
13916: &Apache::lonnet::appenv(\%ValuesHash);
13917: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13918: }
13919:
13920: ############################################################
13921: ############################################################
13922:
13923: =pod
13924:
13925: =item * &DrawXYGraph()
13926:
13927: Facilitates the plotting of data in an XY graph.
13928: Puts plot definition data into the users environment in order for
13929: graph.png to plot it. Returns an <img> tag for the plot.
13930:
13931: Inputs:
13932:
13933: =over 4
13934:
13935: =item $Title: string, the title of the plot
13936:
13937: =item $xlabel: string, text describing the X-axis of the plot
13938:
13939: =item $ylabel: string, text describing the Y-axis of the plot
13940:
13941: =item $Max: scalar, the maximum Y value to use in the plot
13942: If $Max is < any data point, the graph will not be rendered.
13943:
13944: =item $colors: Array ref containing the hex color codes for the data to be
13945: plotted in. If undefined, default values will be used.
13946:
13947: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13948:
13949: =item $Ydata: Array ref containing Array refs.
13950: Each of the contained arrays will be plotted as a separate curve.
13951:
13952: =item %Values: hash indicating or overriding any default values which are
13953: passed to graph.png.
13954: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13955:
13956: =back
13957:
13958: Returns:
13959:
13960: An <img> tag which references graph.png and the appropriate identifying
13961: information for the plot.
13962:
13963: =cut
13964:
13965: ############################################################
13966: ############################################################
13967: sub DrawXYGraph {
13968: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13969: #
13970: # Create the identifier for the graph
13971: my $identifier = &get_cgi_id();
13972: my $id = 'cgi.'.$identifier;
13973: #
13974: $Title = '' if (! defined($Title));
13975: $xlabel = '' if (! defined($xlabel));
13976: $ylabel = '' if (! defined($ylabel));
13977: my %ValuesHash =
13978: (
13979: $id.'.title' => &escape($Title),
13980: $id.'.xlabel' => &escape($xlabel),
13981: $id.'.ylabel' => &escape($ylabel),
13982: $id.'.y_max_value'=> $Max,
13983: $id.'.labels' => join(',',@$Xlabels),
13984: $id.'.PlotType' => 'XY',
13985: );
13986: #
13987: if (defined($colors) && ref($colors) eq 'ARRAY') {
13988: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13989: }
13990: #
13991: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13992: return '';
13993: }
13994: my $NumSets=1;
13995: foreach my $array (@{$Ydata}){
13996: next if (! ref($array));
13997: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13998: }
13999: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14000: #
14001: # Deal with other parameters
14002: while (my ($key,$value) = each(%Values)) {
14003: $ValuesHash{$id.'.'.$key} = $value;
14004: }
14005: #
14006: &Apache::lonnet::appenv(\%ValuesHash);
14007: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14008: }
14009:
14010: ############################################################
14011: ############################################################
14012:
14013: =pod
14014:
14015: =item * &DrawXYYGraph()
14016:
14017: Facilitates the plotting of data in an XY graph with two Y axes.
14018: Puts plot definition data into the users environment in order for
14019: graph.png to plot it. Returns an <img> tag for the plot.
14020:
14021: Inputs:
14022:
14023: =over 4
14024:
14025: =item $Title: string, the title of the plot
14026:
14027: =item $xlabel: string, text describing the X-axis of the plot
14028:
14029: =item $ylabel: string, text describing the Y-axis of the plot
14030:
14031: =item $colors: Array ref containing the hex color codes for the data to be
14032: plotted in. If undefined, default values will be used.
14033:
14034: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14035:
14036: =item $Ydata1: The first data set
14037:
14038: =item $Min1: The minimum value of the left Y-axis
14039:
14040: =item $Max1: The maximum value of the left Y-axis
14041:
14042: =item $Ydata2: The second data set
14043:
14044: =item $Min2: The minimum value of the right Y-axis
14045:
14046: =item $Max2: The maximum value of the left Y-axis
14047:
14048: =item %Values: hash indicating or overriding any default values which are
14049: passed to graph.png.
14050: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14051:
14052: =back
14053:
14054: Returns:
14055:
14056: An <img> tag which references graph.png and the appropriate identifying
14057: information for the plot.
14058:
14059: =cut
14060:
14061: ############################################################
14062: ############################################################
14063: sub DrawXYYGraph {
14064: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14065: $Ydata2,$Min2,$Max2,%Values)=@_;
14066: #
14067: # Create the identifier for the graph
14068: my $identifier = &get_cgi_id();
14069: my $id = 'cgi.'.$identifier;
14070: #
14071: $Title = '' if (! defined($Title));
14072: $xlabel = '' if (! defined($xlabel));
14073: $ylabel = '' if (! defined($ylabel));
14074: my %ValuesHash =
14075: (
14076: $id.'.title' => &escape($Title),
14077: $id.'.xlabel' => &escape($xlabel),
14078: $id.'.ylabel' => &escape($ylabel),
14079: $id.'.labels' => join(',',@$Xlabels),
14080: $id.'.PlotType' => 'XY',
14081: $id.'.NumSets' => 2,
14082: $id.'.two_axes' => 1,
14083: $id.'.y1_max_value' => $Max1,
14084: $id.'.y1_min_value' => $Min1,
14085: $id.'.y2_max_value' => $Max2,
14086: $id.'.y2_min_value' => $Min2,
14087: );
14088: #
14089: if (defined($colors) && ref($colors) eq 'ARRAY') {
14090: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14091: }
14092: #
14093: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14094: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14095: return '';
14096: }
14097: my $NumSets=1;
14098: foreach my $array ($Ydata1,$Ydata2){
14099: next if (! ref($array));
14100: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14101: }
14102: #
14103: # Deal with other parameters
14104: while (my ($key,$value) = each(%Values)) {
14105: $ValuesHash{$id.'.'.$key} = $value;
14106: }
14107: #
14108: &Apache::lonnet::appenv(\%ValuesHash);
14109: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14110: }
14111:
14112: ############################################################
14113: ############################################################
14114:
14115: =pod
14116:
14117: =back
14118:
14119: =head1 Statistics helper routines?
14120:
14121: Bad place for them but what the hell.
14122:
14123: =over 4
14124:
14125: =item * &chartlink()
14126:
14127: Returns a link to the chart for a specific student.
14128:
14129: Inputs:
14130:
14131: =over 4
14132:
14133: =item $linktext: The text of the link
14134:
14135: =item $sname: The students username
14136:
14137: =item $sdomain: The students domain
14138:
14139: =back
14140:
14141: =back
14142:
14143: =cut
14144:
14145: ############################################################
14146: ############################################################
14147: sub chartlink {
14148: my ($linktext, $sname, $sdomain) = @_;
14149: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14150: '&SelectedStudent='.&escape($sname.':'.$sdomain).
14151: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
14152: '">'.$linktext.'</a>';
14153: }
14154:
14155: #######################################################
14156: #######################################################
14157:
14158: =pod
14159:
14160: =head1 Course Environment Routines
14161:
14162: =over 4
14163:
14164: =item * &restore_course_settings()
14165:
14166: =item * &store_course_settings()
14167:
14168: Restores/Store indicated form parameters from the course environment.
14169: Will not overwrite existing values of the form parameters.
14170:
14171: Inputs:
14172: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14173:
14174: a hash ref describing the data to be stored. For example:
14175:
14176: %Save_Parameters = ('Status' => 'scalar',
14177: 'chartoutputmode' => 'scalar',
14178: 'chartoutputdata' => 'scalar',
14179: 'Section' => 'array',
14180: 'Group' => 'array',
14181: 'StudentData' => 'array',
14182: 'Maps' => 'array');
14183:
14184: Returns: both routines return nothing
14185:
14186: =back
14187:
14188: =cut
14189:
14190: #######################################################
14191: #######################################################
14192: sub store_course_settings {
14193: return &store_settings($env{'request.course.id'},@_);
14194: }
14195:
14196: sub store_settings {
14197: # save to the environment
14198: # appenv the same items, just to be safe
14199: my $udom = $env{'user.domain'};
14200: my $uname = $env{'user.name'};
14201: my ($context,$prefix,$Settings) = @_;
14202: my %SaveHash;
14203: my %AppHash;
14204: while (my ($setting,$type) = each(%$Settings)) {
14205: my $basename = join('.','internal',$context,$prefix,$setting);
14206: my $envname = 'environment.'.$basename;
14207: if (exists($env{'form.'.$setting})) {
14208: # Save this value away
14209: if ($type eq 'scalar' &&
14210: (! exists($env{$envname}) ||
14211: $env{$envname} ne $env{'form.'.$setting})) {
14212: $SaveHash{$basename} = $env{'form.'.$setting};
14213: $AppHash{$envname} = $env{'form.'.$setting};
14214: } elsif ($type eq 'array') {
14215: my $stored_form;
14216: if (ref($env{'form.'.$setting})) {
14217: $stored_form = join(',',
14218: map {
14219: &escape($_);
14220: } sort(@{$env{'form.'.$setting}}));
14221: } else {
14222: $stored_form =
14223: &escape($env{'form.'.$setting});
14224: }
14225: # Determine if the array contents are the same.
14226: if ($stored_form ne $env{$envname}) {
14227: $SaveHash{$basename} = $stored_form;
14228: $AppHash{$envname} = $stored_form;
14229: }
14230: }
14231: }
14232: }
14233: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14234: $udom,$uname);
14235: if ($put_result !~ /^(ok|delayed)/) {
14236: &Apache::lonnet::logthis('unable to save form parameters, '.
14237: 'got error:'.$put_result);
14238: }
14239: # Make sure these settings stick around in this session, too
14240: &Apache::lonnet::appenv(\%AppHash);
14241: return;
14242: }
14243:
14244: sub restore_course_settings {
14245: return &restore_settings($env{'request.course.id'},@_);
14246: }
14247:
14248: sub restore_settings {
14249: my ($context,$prefix,$Settings) = @_;
14250: while (my ($setting,$type) = each(%$Settings)) {
14251: next if (exists($env{'form.'.$setting}));
14252: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14253: '.'.$setting;
14254: if (exists($env{$envname})) {
14255: if ($type eq 'scalar') {
14256: $env{'form.'.$setting} = $env{$envname};
14257: } elsif ($type eq 'array') {
14258: $env{'form.'.$setting} = [
14259: map {
14260: &unescape($_);
14261: } split(',',$env{$envname})
14262: ];
14263: }
14264: }
14265: }
14266: }
14267:
14268: #######################################################
14269: #######################################################
14270:
14271: =pod
14272:
14273: =head1 Domain E-mail Routines
14274:
14275: =over 4
14276:
14277: =item * &build_recipient_list()
14278:
14279: Build recipient lists for following types of e-mail:
14280: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14281: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14282: module change checking, student/employee ID conflict checks, as
14283: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14284: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14285:
14286: Inputs:
14287: defmail (scalar - email address of default recipient),
14288: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14289: requestsmail, updatesmail, or idconflictsmail).
14290:
14291: defdom (domain for which to retrieve configuration settings),
14292:
14293: origmail (scalar - email address of recipient from loncapa.conf,
14294: i.e., predates configuration by DC via domainprefs.pm
14295:
14296: $requname username of requester (if mailing type is helpdeskmail)
14297:
14298: $requdom domain of requester (if mailing type is helpdeskmail)
14299:
14300: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14301:
14302: Returns: comma separated list of addresses to which to send e-mail.
14303:
14304: =back
14305:
14306: =cut
14307:
14308: ############################################################
14309: ############################################################
14310: sub build_recipient_list {
14311: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14312: my @recipients;
14313: my ($otheremails,$lastresort,$allbcc,$addtext);
14314: my %domconfig =
14315: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14316: if (ref($domconfig{'contacts'}) eq 'HASH') {
14317: if (exists($domconfig{'contacts'}{$mailing})) {
14318: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14319: my @contacts = ('adminemail','supportemail');
14320: foreach my $item (@contacts) {
14321: if ($domconfig{'contacts'}{$mailing}{$item}) {
14322: my $addr = $domconfig{'contacts'}{$item};
14323: if (!grep(/^\Q$addr\E$/,@recipients)) {
14324: push(@recipients,$addr);
14325: }
14326: }
14327: }
14328: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14329: if ($mailing eq 'helpdeskmail') {
14330: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14331: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14332: my @ok_bccs;
14333: foreach my $bcc (@bccs) {
14334: $bcc =~ s/^\s+//g;
14335: $bcc =~ s/\s+$//g;
14336: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14337: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14338: push(@ok_bccs,$bcc);
14339: }
14340: }
14341: }
14342: if (@ok_bccs > 0) {
14343: $allbcc = join(', ',@ok_bccs);
14344: }
14345: }
14346: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14347: }
14348: }
14349: } elsif ($origmail ne '') {
14350: $lastresort = $origmail;
14351: }
14352: if ($mailing eq 'helpdeskmail') {
14353: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14354: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14355: my ($inststatus,$inststatus_checked);
14356: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14357: ($env{'user.domain'} ne 'public')) {
14358: $inststatus_checked = 1;
14359: $inststatus = $env{'environment.inststatus'};
14360: }
14361: unless ($inststatus_checked) {
14362: if (($requname ne '') && ($requdom ne '')) {
14363: if (($requname =~ /^$match_username$/) &&
14364: ($requdom =~ /^$match_domain$/) &&
14365: (&Apache::lonnet::domain($requdom))) {
14366: my $requhome = &Apache::lonnet::homeserver($requname,
14367: $requdom);
14368: unless ($requhome eq 'no_host') {
14369: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14370: $inststatus = $userenv{'inststatus'};
14371: $inststatus_checked = 1;
14372: }
14373: }
14374: }
14375: }
14376: unless ($inststatus_checked) {
14377: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14378: my %srch = (srchby => 'email',
14379: srchdomain => $defdom,
14380: srchterm => $reqemail,
14381: srchtype => 'exact');
14382: my %srch_results = &Apache::lonnet::usersearch(\%srch);
14383: foreach my $uname (keys(%srch_results)) {
14384: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14385: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14386: $inststatus_checked = 1;
14387: last;
14388: }
14389: }
14390: unless ($inststatus_checked) {
14391: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14392: if ($dirsrchres eq 'ok') {
14393: foreach my $uname (keys(%srch_results)) {
14394: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14395: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14396: $inststatus_checked = 1;
14397: last;
14398: }
14399: }
14400: }
14401: }
14402: }
14403: }
14404: if ($inststatus ne '') {
14405: foreach my $status (split(/\:/,$inststatus)) {
14406: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14407: my @contacts = ('adminemail','supportemail');
14408: foreach my $item (@contacts) {
14409: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14410: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14411: if (!grep(/^\Q$addr\E$/,@recipients)) {
14412: push(@recipients,$addr);
14413: }
14414: }
14415: }
14416: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14417: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14418: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14419: my @ok_bccs;
14420: foreach my $bcc (@bccs) {
14421: $bcc =~ s/^\s+//g;
14422: $bcc =~ s/\s+$//g;
14423: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14424: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14425: push(@ok_bccs,$bcc);
14426: }
14427: }
14428: }
14429: if (@ok_bccs > 0) {
14430: $allbcc = join(', ',@ok_bccs);
14431: }
14432: }
14433: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14434: last;
14435: }
14436: }
14437: }
14438: }
14439: }
14440: } elsif ($origmail ne '') {
14441: $lastresort = $origmail;
14442: }
14443: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14444: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14445: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14446: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14447: my %what = (
14448: perlvar => 1,
14449: );
14450: my $primary = &Apache::lonnet::domain($defdom,'primary');
14451: if ($primary) {
14452: my $gotaddr;
14453: my ($result,$returnhash) =
14454: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14455: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14456: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14457: $lastresort = $returnhash->{'lonSupportEMail'};
14458: $gotaddr = 1;
14459: }
14460: }
14461: unless ($gotaddr) {
14462: my $uintdom = &Apache::lonnet::internet_dom($primary);
14463: my $intdom = &Apache::lonnet::internet_dom($lonhost);
14464: unless ($uintdom eq $intdom) {
14465: my %domconfig =
14466: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14467: if (ref($domconfig{'contacts'}) eq 'HASH') {
14468: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14469: my @contacts = ('adminemail','supportemail');
14470: foreach my $item (@contacts) {
14471: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14472: my $addr = $domconfig{'contacts'}{$item};
14473: if (!grep(/^\Q$addr\E$/,@recipients)) {
14474: push(@recipients,$addr);
14475: }
14476: }
14477: }
14478: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14479: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14480: }
14481: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14482: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14483: my @ok_bccs;
14484: foreach my $bcc (@bccs) {
14485: $bcc =~ s/^\s+//g;
14486: $bcc =~ s/\s+$//g;
14487: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14488: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14489: push(@ok_bccs,$bcc);
14490: }
14491: }
14492: }
14493: if (@ok_bccs > 0) {
14494: $allbcc = join(', ',@ok_bccs);
14495: }
14496: }
14497: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14498: }
14499: }
14500: }
14501: }
14502: }
14503: }
14504: }
14505: if (defined($defmail)) {
14506: if ($defmail ne '') {
14507: push(@recipients,$defmail);
14508: }
14509: }
14510: if ($otheremails) {
14511: my @others;
14512: if ($otheremails =~ /,/) {
14513: @others = split(/,/,$otheremails);
14514: } else {
14515: push(@others,$otheremails);
14516: }
14517: foreach my $addr (@others) {
14518: if (!grep(/^\Q$addr\E$/,@recipients)) {
14519: push(@recipients,$addr);
14520: }
14521: }
14522: }
14523: if ($mailing eq 'helpdeskmail') {
14524: if ((!@recipients) && ($lastresort ne '')) {
14525: push(@recipients,$lastresort);
14526: }
14527: } elsif ($lastresort ne '') {
14528: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14529: push(@recipients,$lastresort);
14530: }
14531: }
14532: my $recipientlist = join(',',@recipients);
14533: if (wantarray) {
14534: return ($recipientlist,$allbcc,$addtext);
14535: } else {
14536: return $recipientlist;
14537: }
14538: }
14539:
14540: ############################################################
14541: ############################################################
14542:
14543: =pod
14544:
14545: =head1 Course Catalog Routines
14546:
14547: =over 4
14548:
14549: =item * &gather_categories()
14550:
14551: Converts category definitions - keys of categories hash stored in
14552: coursecategories in configuration.db on the primary library server in a
14553: domain - to an array. Also generates javascript and idx hash used to
14554: generate Domain Coordinator interface for editing Course Categories.
14555:
14556: Inputs:
14557:
14558: categories (reference to hash of category definitions).
14559:
14560: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14561: categories and subcategories).
14562:
14563: idx (reference to hash of counters used in Domain Coordinator interface for
14564: editing Course Categories).
14565:
14566: jsarray (reference to array of categories used to create Javascript arrays for
14567: Domain Coordinator interface for editing Course Categories).
14568:
14569: Returns: nothing
14570:
14571: Side effects: populates cats, idx and jsarray.
14572:
14573: =cut
14574:
14575: sub gather_categories {
14576: my ($categories,$cats,$idx,$jsarray) = @_;
14577: my %counters;
14578: my $num = 0;
14579: foreach my $item (keys(%{$categories})) {
14580: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14581: if ($container eq '' && $depth == 0) {
14582: $cats->[$depth][$categories->{$item}] = $cat;
14583: } else {
14584: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14585: }
14586: my ($escitem,$tail) = split(/:/,$item,2);
14587: if ($counters{$tail} eq '') {
14588: $counters{$tail} = $num;
14589: $num ++;
14590: }
14591: if (ref($idx) eq 'HASH') {
14592: $idx->{$item} = $counters{$tail};
14593: }
14594: if (ref($jsarray) eq 'ARRAY') {
14595: push(@{$jsarray->[$counters{$tail}]},$item);
14596: }
14597: }
14598: return;
14599: }
14600:
14601: =pod
14602:
14603: =item * &extract_categories()
14604:
14605: Used to generate breadcrumb trails for course categories.
14606:
14607: Inputs:
14608:
14609: categories (reference to hash of category definitions).
14610:
14611: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14612: categories and subcategories).
14613:
14614: trails (reference to array of breacrumb trails for each category).
14615:
14616: allitems (reference to hash - key is category key
14617: (format: escaped(name):escaped(parent category):depth in hierarchy).
14618:
14619: idx (reference to hash of counters used in Domain Coordinator interface for
14620: editing Course Categories).
14621:
14622: jsarray (reference to array of categories used to create Javascript arrays for
14623: Domain Coordinator interface for editing Course Categories).
14624:
14625: subcats (reference to hash of arrays containing all subcategories within each
14626: category, -recursive)
14627:
14628: maxd (reference to hash used to hold max depth for all top-level categories).
14629:
14630: Returns: nothing
14631:
14632: Side effects: populates trails and allitems hash references.
14633:
14634: =cut
14635:
14636: sub extract_categories {
14637: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14638: if (ref($categories) eq 'HASH') {
14639: &gather_categories($categories,$cats,$idx,$jsarray);
14640: if (ref($cats->[0]) eq 'ARRAY') {
14641: for (my $i=0; $i<@{$cats->[0]}; $i++) {
14642: my $name = $cats->[0][$i];
14643: my $item = &escape($name).'::0';
14644: my $trailstr;
14645: if ($name eq 'instcode') {
14646: $trailstr = &mt('Official courses (with institutional codes)');
14647: } elsif ($name eq 'communities') {
14648: $trailstr = &mt('Communities');
14649: } else {
14650: $trailstr = $name;
14651: }
14652: if ($allitems->{$item} eq '') {
14653: push(@{$trails},$trailstr);
14654: $allitems->{$item} = scalar(@{$trails})-1;
14655: }
14656: my @parents = ($name);
14657: if (ref($cats->[1]{$name}) eq 'ARRAY') {
14658: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14659: my $category = $cats->[1]{$name}[$j];
14660: if (ref($subcats) eq 'HASH') {
14661: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14662: }
14663: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14664: }
14665: } else {
14666: if (ref($subcats) eq 'HASH') {
14667: $subcats->{$item} = [];
14668: }
14669: if (ref($maxd) eq 'HASH') {
14670: $maxd->{$name} = 1;
14671: }
14672: }
14673: }
14674: }
14675: }
14676: return;
14677: }
14678:
14679: =pod
14680:
14681: =item * &recurse_categories()
14682:
14683: Recursively used to generate breadcrumb trails for course categories.
14684:
14685: Inputs:
14686:
14687: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14688: categories and subcategories).
14689:
14690: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14691:
14692: category (current course category, for which breadcrumb trail is being generated).
14693:
14694: trails (reference to array of breadcrumb trails for each category).
14695:
14696: allitems (reference to hash - key is category key
14697: (format: escaped(name):escaped(parent category):depth in hierarchy).
14698:
14699: parents (array containing containers directories for current category,
14700: back to top level).
14701:
14702: Returns: nothing
14703:
14704: Side effects: populates trails and allitems hash references
14705:
14706: =cut
14707:
14708: sub recurse_categories {
14709: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14710: my $shallower = $depth - 1;
14711: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14712: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14713: my $name = $cats->[$depth]{$category}[$k];
14714: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14715: my $trailstr = join(' -> ',(@{$parents},$category));
14716: if ($allitems->{$item} eq '') {
14717: push(@{$trails},$trailstr);
14718: $allitems->{$item} = scalar(@{$trails})-1;
14719: }
14720: my $deeper = $depth+1;
14721: push(@{$parents},$category);
14722: if (ref($subcats) eq 'HASH') {
14723: my $subcat = &escape($name).':'.$category.':'.$depth;
14724: for (my $j=@{$parents}; $j>=0; $j--) {
14725: my $higher;
14726: if ($j > 0) {
14727: $higher = &escape($parents->[$j]).':'.
14728: &escape($parents->[$j-1]).':'.$j;
14729: } else {
14730: $higher = &escape($parents->[$j]).'::'.$j;
14731: }
14732: push(@{$subcats->{$higher}},$subcat);
14733: }
14734: }
14735: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14736: $subcats,$maxd);
14737: pop(@{$parents});
14738: }
14739: } else {
14740: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14741: my $trailstr = join(' » ',(@{$parents},$category));
14742: if ($allitems->{$item} eq '') {
14743: push(@{$trails},$trailstr);
14744: $allitems->{$item} = scalar(@{$trails})-1;
14745: }
14746: if (ref($maxd) eq 'HASH') {
14747: if ($depth > $maxd->{$parents->[0]}) {
14748: $maxd->{$parents->[0]} = $depth;
14749: }
14750: }
14751: }
14752: return;
14753: }
14754:
14755: =pod
14756:
14757: =item * &assign_categories_table()
14758:
14759: Create a datatable for display of hierarchical categories in a domain,
14760: with checkboxes to allow a course to be categorized.
14761:
14762: Inputs:
14763:
14764: cathash - reference to hash of categories defined for the domain (from
14765: configuration.db)
14766:
14767: currcat - scalar with an & separated list of categories assigned to a course.
14768:
14769: type - scalar contains course type (Course or Community).
14770:
14771: disabled - scalar (optional) contains disabled="disabled" if input elements are
14772: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14773:
14774: Returns: $output (markup to be displayed)
14775:
14776: =cut
14777:
14778: sub assign_categories_table {
14779: my ($cathash,$currcat,$type,$disabled) = @_;
14780: my $output;
14781: if (ref($cathash) eq 'HASH') {
14782: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14783: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14784: $maxdepth = scalar(@cats);
14785: if (@cats > 0) {
14786: my $itemcount = 0;
14787: if (ref($cats[0]) eq 'ARRAY') {
14788: my @currcategories;
14789: if ($currcat ne '') {
14790: @currcategories = split('&',$currcat);
14791: }
14792: my $table;
14793: for (my $i=0; $i<@{$cats[0]}; $i++) {
14794: my $parent = $cats[0][$i];
14795: next if ($parent eq 'instcode');
14796: if ($type eq 'Community') {
14797: next unless ($parent eq 'communities');
14798: } else {
14799: next if ($parent eq 'communities');
14800: }
14801: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14802: my $item = &escape($parent).'::0';
14803: my $checked = '';
14804: if (@currcategories > 0) {
14805: if (grep(/^\Q$item\E$/,@currcategories)) {
14806: $checked = ' checked="checked"';
14807: }
14808: }
14809: my $parent_title = $parent;
14810: if ($parent eq 'communities') {
14811: $parent_title = &mt('Communities');
14812: }
14813: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14814: '<input type="checkbox" name="usecategory" value="'.
14815: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14816: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14817: my $depth = 1;
14818: push(@path,$parent);
14819: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14820: pop(@path);
14821: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14822: $itemcount ++;
14823: }
14824: if ($itemcount) {
14825: $output = &Apache::loncommon::start_data_table().
14826: $table.
14827: &Apache::loncommon::end_data_table();
14828: }
14829: }
14830: }
14831: }
14832: return $output;
14833: }
14834:
14835: =pod
14836:
14837: =item * &assign_category_rows()
14838:
14839: Create a datatable row for display of nested categories in a domain,
14840: with checkboxes to allow a course to be categorized,called recursively.
14841:
14842: Inputs:
14843:
14844: itemcount - track row number for alternating colors
14845:
14846: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14847: categories and subcategories.
14848:
14849: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14850:
14851: parent - parent of current category item
14852:
14853: path - Array containing all categories back up through the hierarchy from the
14854: current category to the top level.
14855:
14856: currcategories - reference to array of current categories assigned to the course
14857:
14858: disabled - scalar (optional) contains disabled="disabled" if input elements are
14859: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14860:
14861: Returns: $output (markup to be displayed).
14862:
14863: =cut
14864:
14865: sub assign_category_rows {
14866: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14867: my ($text,$name,$item,$chgstr);
14868: if (ref($cats) eq 'ARRAY') {
14869: my $maxdepth = scalar(@{$cats});
14870: if (ref($cats->[$depth]) eq 'HASH') {
14871: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14872: my $numchildren = @{$cats->[$depth]{$parent}};
14873: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14874: $text .= '<td><table class="LC_data_table">';
14875: for (my $j=0; $j<$numchildren; $j++) {
14876: $name = $cats->[$depth]{$parent}[$j];
14877: $item = &escape($name).':'.&escape($parent).':'.$depth;
14878: my $deeper = $depth+1;
14879: my $checked = '';
14880: if (ref($currcategories) eq 'ARRAY') {
14881: if (@{$currcategories} > 0) {
14882: if (grep(/^\Q$item\E$/,@{$currcategories})) {
14883: $checked = ' checked="checked"';
14884: }
14885: }
14886: }
14887: $text .= '<tr><td><span class="LC_nobreak"><label>'.
14888: '<input type="checkbox" name="usecategory" value="'.
14889: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14890: '<input type="hidden" name="catname" value="'.$name.'" />'.
14891: '</td><td>';
14892: if (ref($path) eq 'ARRAY') {
14893: push(@{$path},$name);
14894: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14895: pop(@{$path});
14896: }
14897: $text .= '</td></tr>';
14898: }
14899: $text .= '</table></td>';
14900: }
14901: }
14902: }
14903: return $text;
14904: }
14905:
14906: =pod
14907:
14908: =back
14909:
14910: =cut
14911:
14912: ############################################################
14913: ############################################################
14914:
14915:
14916: sub commit_customrole {
14917: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14918: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14919: ($start?', '.&mt('starting').' '.localtime($start):'').
14920: ($end?', ending '.localtime($end):'').': <b>'.
14921: &Apache::lonnet::assigncustomrole(
14922: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14923: '</b><br />';
14924: return $output;
14925: }
14926:
14927: sub commit_standardrole {
14928: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14929: my ($output,$logmsg,$linefeed);
14930: if ($context eq 'auto') {
14931: $linefeed = "\n";
14932: } else {
14933: $linefeed = "<br />\n";
14934: }
14935: if ($three eq 'st') {
14936: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14937: $one,$two,$sec,$context,$credits);
14938: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
14939: ($result eq 'unknown_course') || ($result eq 'refused')) {
14940: $output = $logmsg.' '.&mt('Error: ').$result."\n";
14941: } else {
14942: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14943: ($start?', '.&mt('starting').' '.localtime($start):'').
14944: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14945: if ($context eq 'auto') {
14946: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14947: } else {
14948: $output .= '<b>'.$result.'</b>'.$linefeed.
14949: &mt('Add to classlist').': <b>ok</b>';
14950: }
14951: $output .= $linefeed;
14952: }
14953: } else {
14954: $output = &mt('Assigning').' '.$three.' in '.$url.
14955: ($start?', '.&mt('starting').' '.localtime($start):'').
14956: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14957: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14958: if ($context eq 'auto') {
14959: $output .= $result.$linefeed;
14960: } else {
14961: $output .= '<b>'.$result.'</b>'.$linefeed;
14962: }
14963: }
14964: return $output;
14965: }
14966:
14967: sub commit_studentrole {
14968: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14969: $credits) = @_;
14970: my ($result,$linefeed,$oldsecurl,$newsecurl);
14971: if ($context eq 'auto') {
14972: $linefeed = "\n";
14973: } else {
14974: $linefeed = '<br />'."\n";
14975: }
14976: if (defined($one) && defined($two)) {
14977: my $cid=$one.'_'.$two;
14978: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14979: my $secchange = 0;
14980: my $expire_role_result;
14981: my $modify_section_result;
14982: if ($oldsec ne '-1') {
14983: if ($oldsec ne $sec) {
14984: $secchange = 1;
14985: my $now = time;
14986: my $uurl='/'.$cid;
14987: $uurl=~s/\_/\//g;
14988: if ($oldsec) {
14989: $uurl.='/'.$oldsec;
14990: }
14991: $oldsecurl = $uurl;
14992: $expire_role_result =
14993: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14994: if ($env{'request.course.sec'} ne '') {
14995: if ($expire_role_result eq 'refused') {
14996: my @roles = ('st');
14997: my @statuses = ('previous');
14998: my @roledoms = ($one);
14999: my $withsec = 1;
15000: my %roleshash =
15001: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15002: \@statuses,\@roles,\@roledoms,$withsec);
15003: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15004: my ($oldstart,$oldend) =
15005: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15006: if ($oldend > 0 && $oldend <= $now) {
15007: $expire_role_result = 'ok';
15008: }
15009: }
15010: }
15011: }
15012: $result = $expire_role_result;
15013: }
15014: }
15015: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15016: $modify_section_result =
15017: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15018: undef,undef,undef,$sec,
15019: $end,$start,'','',$cid,
15020: '',$context,$credits);
15021: if ($modify_section_result =~ /^ok/) {
15022: if ($secchange == 1) {
15023: if ($sec eq '') {
15024: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15025: } else {
15026: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15027: }
15028: } elsif ($oldsec eq '-1') {
15029: if ($sec eq '') {
15030: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15031: } else {
15032: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15033: }
15034: } else {
15035: if ($sec eq '') {
15036: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15037: } else {
15038: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15039: }
15040: }
15041: } else {
15042: if ($secchange) {
15043: $$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;
15044: } else {
15045: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15046: }
15047: }
15048: $result = $modify_section_result;
15049: } elsif ($secchange == 1) {
15050: if ($oldsec eq '') {
15051: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15052: } else {
15053: $$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;
15054: }
15055: if ($expire_role_result eq 'refused') {
15056: my $newsecurl = '/'.$cid;
15057: $newsecurl =~ s/\_/\//g;
15058: if ($sec ne '') {
15059: $newsecurl.='/'.$sec;
15060: }
15061: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15062: if ($sec eq '') {
15063: $$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;
15064: } else {
15065: $$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;
15066: }
15067: }
15068: }
15069: }
15070: } else {
15071: $$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;
15072: $result = "error: incomplete course id\n";
15073: }
15074: return $result;
15075: }
15076:
15077: sub show_role_extent {
15078: my ($scope,$context,$role) = @_;
15079: $scope =~ s{^/}{};
15080: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15081: push(@courseroles,'co');
15082: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15083: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15084: $scope =~ s{/}{_};
15085: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15086: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15087: my ($audom,$auname) = split(/\//,$scope);
15088: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15089: &Apache::loncommon::plainname($auname,$audom).'</span>');
15090: } else {
15091: $scope =~ s{/$}{};
15092: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15093: &Apache::lonnet::domain($scope,'description').'</span>');
15094: }
15095: }
15096:
15097: ############################################################
15098: ############################################################
15099:
15100: sub check_clone {
15101: my ($args,$linefeed) = @_;
15102: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15103: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15104: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15105: my $clonetitle;
15106: my @clonemsg;
15107: my $can_clone = 0;
15108: my $lctype = lc($args->{'crstype'});
15109: if ($lctype ne 'community') {
15110: $lctype = 'course';
15111: }
15112: if ($clonehome eq 'no_host') {
15113: if ($args->{'crstype'} eq 'Community') {
15114: push(@clonemsg,({
15115: mt => 'No new community created.',
15116: args => [],
15117: },
15118: {
15119: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15120: args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15121: }));
15122: } else {
15123: push(@clonemsg,({
15124: mt => 'No new course created.',
15125: args => [],
15126: },
15127: {
15128: mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15129: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15130: }));
15131: }
15132: } else {
15133: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15134: $clonetitle = $clonedesc{'description'};
15135: if ($args->{'crstype'} eq 'Community') {
15136: if ($clonedesc{'type'} ne 'Community') {
15137: push(@clonemsg,({
15138: mt => 'No new community created.',
15139: args => [],
15140: },
15141: {
15142: mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15143: args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15144: }));
15145: return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15146: }
15147: }
15148: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15149: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15150: $can_clone = 1;
15151: } else {
15152: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15153: $args->{'clonedomain'},$args->{'clonecourse'});
15154: if ($clonehash{'cloners'} eq '') {
15155: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15156: if ($domdefs{'canclone'}) {
15157: unless ($domdefs{'canclone'} eq 'none') {
15158: if ($domdefs{'canclone'} eq 'domain') {
15159: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15160: $can_clone = 1;
15161: }
15162: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15163: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15164: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15165: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15166: $can_clone = 1;
15167: }
15168: }
15169: }
15170: }
15171: } else {
15172: my @cloners = split(/,/,$clonehash{'cloners'});
15173: if (grep(/^\*$/,@cloners)) {
15174: $can_clone = 1;
15175: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15176: $can_clone = 1;
15177: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15178: $can_clone = 1;
15179: }
15180: unless ($can_clone) {
15181: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15182: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15183: my (%gotdomdefaults,%gotcodedefaults);
15184: foreach my $cloner (@cloners) {
15185: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15186: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15187: my (%codedefaults,@code_order);
15188: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15189: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15190: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15191: }
15192: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15193: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15194: }
15195: } else {
15196: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15197: \%codedefaults,
15198: \@code_order);
15199: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15200: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15201: }
15202: if (@code_order > 0) {
15203: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15204: $cloner,$clonehash{'internal.coursecode'},
15205: $args->{'crscode'})) {
15206: $can_clone = 1;
15207: last;
15208: }
15209: }
15210: }
15211: }
15212: }
15213: }
15214: }
15215: unless ($can_clone) {
15216: my $ccrole = 'cc';
15217: if ($args->{'crstype'} eq 'Community') {
15218: $ccrole = 'co';
15219: }
15220: my %roleshash =
15221: &Apache::lonnet::get_my_roles($args->{'ccuname'},
15222: $args->{'ccdomain'},
15223: 'userroles',['active'],[$ccrole],
15224: [$args->{'clonedomain'}]);
15225: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15226: $can_clone = 1;
15227: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15228: $args->{'ccuname'},$args->{'ccdomain'})) {
15229: $can_clone = 1;
15230: }
15231: }
15232: unless ($can_clone) {
15233: if ($args->{'crstype'} eq 'Community') {
15234: push(@clonemsg,({
15235: mt => 'No new community created.',
15236: args => [],
15237: },
15238: {
15239: 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]).',
15240: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15241: }));
15242: } else {
15243: push(@clonemsg,({
15244: mt => 'No new course created.',
15245: args => [],
15246: },
15247: {
15248: 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]).',
15249: args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15250: }));
15251: }
15252: }
15253: }
15254: }
15255: return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
15256: }
15257:
15258: sub construct_course {
15259: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15260: $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
15261: my ($outcome,$msgref,$clonemsgref);
15262: my $linefeed = '<br />'."\n";
15263: if ($context eq 'auto') {
15264: $linefeed = "\n";
15265: }
15266:
15267: #
15268: # Are we cloning?
15269: #
15270: my ($can_clone,$cloneid,$clonehome,$clonetitle);
15271: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15272: ($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
15273: if (!$can_clone) {
15274: return (0,$outcome,$clonemsgref);
15275: }
15276: }
15277:
15278: #
15279: # Open course
15280: #
15281: my $crstype = lc($args->{'crstype'});
15282: my %cenv=();
15283: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15284: $args->{'cdescr'},
15285: $args->{'curl'},
15286: $args->{'course_home'},
15287: $args->{'nonstandard'},
15288: $args->{'crscode'},
15289: $args->{'ccuname'}.':'.
15290: $args->{'ccdomain'},
15291: $args->{'crstype'},
15292: $cnum,$context,$category,
15293: $callercontext);
15294:
15295: # Note: The testing routines depend on this being output; see
15296: # Utils::Course. This needs to at least be output as a comment
15297: # if anyone ever decides to not show this, and Utils::Course::new
15298: # will need to be suitably modified.
15299: if (($callercontext eq 'auto') && ($user_lh ne '')) {
15300: $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15301: } else {
15302: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15303: }
15304: if ($$courseid =~ /^error:/) {
15305: return (0,$outcome,$clonemsgref);
15306: }
15307:
15308: #
15309: # Check if created correctly
15310: #
15311: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15312: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15313: if ($crsuhome eq 'no_host') {
15314: if (($callercontext eq 'auto') && ($user_lh ne '')) {
15315: $outcome .= &mt_user($user_lh,
15316: 'Course creation failed, unrecognized course home server.');
15317: } else {
15318: $outcome .= &mt('Course creation failed, unrecognized course home server.');
15319: }
15320: $outcome .= $linefeed;
15321: return (0,$outcome,$clonemsgref);
15322: }
15323: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15324:
15325: #
15326: # Do the cloning
15327: #
15328: my @clonemsg;
15329: if ($can_clone && $cloneid) {
15330: push(@clonemsg,
15331: {
15332: mt => 'Created [_1] by cloning from [_2]',
15333: args => [$crstype,$clonetitle],
15334: });
15335: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15336: # Copy all files
15337: my @info =
15338: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
15339: $args->{'dateshift'},$args->{'crscode'},
15340: $args->{'ccuname'}.':'.$args->{'ccdomain'},
15341: $args->{'tinyurls'});
15342: if (@info) {
15343: push(@clonemsg,@info);
15344: }
15345: # Restore URL
15346: $cenv{'url'}=$oldcenv{'url'};
15347: # Restore title
15348: $cenv{'description'}=$oldcenv{'description'};
15349: # Restore creation date, creator and creation context.
15350: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15351: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15352: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15353: # Mark as cloned
15354: $cenv{'clonedfrom'}=$cloneid;
15355: # Need to clone grading mode
15356: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15357: $cenv{'grading'}=$newenv{'grading'};
15358: # Do not clone these environment entries
15359: &Apache::lonnet::del('environment',
15360: ['default_enrollment_start_date',
15361: 'default_enrollment_end_date',
15362: 'question.email',
15363: 'policy.email',
15364: 'comment.email',
15365: 'pch.users.denied',
15366: 'plc.users.denied',
15367: 'hidefromcat',
15368: 'checkforpriv',
15369: 'categories',
15370: 'internal.uniquecode'],
15371: $$crsudom,$$crsunum);
15372: if ($args->{'textbook'}) {
15373: $cenv{'internal.textbook'} = $args->{'textbook'};
15374: }
15375: }
15376:
15377: #
15378: # Set environment (will override cloned, if existing)
15379: #
15380: my @sections = ();
15381: my @xlists = ();
15382: if ($args->{'crstype'}) {
15383: $cenv{'type'}=$args->{'crstype'};
15384: }
15385: if ($args->{'crsid'}) {
15386: $cenv{'courseid'}=$args->{'crsid'};
15387: }
15388: if ($args->{'crscode'}) {
15389: $cenv{'internal.coursecode'}=$args->{'crscode'};
15390: }
15391: if ($args->{'crsquota'} ne '') {
15392: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15393: } else {
15394: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15395: }
15396: if ($args->{'ccuname'}) {
15397: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15398: ':'.$args->{'ccdomain'};
15399: } else {
15400: $cenv{'internal.courseowner'} = $args->{'curruser'};
15401: }
15402: if ($args->{'defaultcredits'}) {
15403: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15404: }
15405: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15406: if ($args->{'crssections'}) {
15407: $cenv{'internal.sectionnums'} = '';
15408: if ($args->{'crssections'} =~ m/,/) {
15409: @sections = split/,/,$args->{'crssections'};
15410: } else {
15411: $sections[0] = $args->{'crssections'};
15412: }
15413: if (@sections > 0) {
15414: foreach my $item (@sections) {
15415: my ($sec,$gp) = split/:/,$item;
15416: my $class = $args->{'crscode'}.$sec;
15417: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15418: $cenv{'internal.sectionnums'} .= $item.',';
15419: unless ($addcheck eq 'ok') {
15420: push(@badclasses,$class);
15421: }
15422: }
15423: $cenv{'internal.sectionnums'} =~ s/,$//;
15424: }
15425: }
15426: # do not hide course coordinator from staff listing,
15427: # even if privileged
15428: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15429: # add course coordinator's domain to domains to check for privileged users
15430: # if different to course domain
15431: if ($$crsudom ne $args->{'ccdomain'}) {
15432: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15433: }
15434: # add crosslistings
15435: if ($args->{'crsxlist'}) {
15436: $cenv{'internal.crosslistings'}='';
15437: if ($args->{'crsxlist'} =~ m/,/) {
15438: @xlists = split/,/,$args->{'crsxlist'};
15439: } else {
15440: $xlists[0] = $args->{'crsxlist'};
15441: }
15442: if (@xlists > 0) {
15443: foreach my $item (@xlists) {
15444: my ($xl,$gp) = split/:/,$item;
15445: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15446: $cenv{'internal.crosslistings'} .= $item.',';
15447: unless ($addcheck eq 'ok') {
15448: push(@badclasses,$xl);
15449: }
15450: }
15451: $cenv{'internal.crosslistings'} =~ s/,$//;
15452: }
15453: }
15454: if ($args->{'autoadds'}) {
15455: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15456: }
15457: if ($args->{'autodrops'}) {
15458: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15459: }
15460: # check for notification of enrollment changes
15461: my @notified = ();
15462: if ($args->{'notify_owner'}) {
15463: if ($args->{'ccuname'} ne '') {
15464: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15465: }
15466: }
15467: if ($args->{'notify_dc'}) {
15468: if ($uname ne '') {
15469: push(@notified,$uname.':'.$udom);
15470: }
15471: }
15472: if (@notified > 0) {
15473: my $notifylist;
15474: if (@notified > 1) {
15475: $notifylist = join(',',@notified);
15476: } else {
15477: $notifylist = $notified[0];
15478: }
15479: $cenv{'internal.notifylist'} = $notifylist;
15480: }
15481: if (@badclasses > 0) {
15482: my %lt=&Apache::lonlocal::texthash(
15483: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15484: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15485: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15486: );
15487: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15488: &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'};
15489: if ($context eq 'auto') {
15490: $outcome .= $badclass_msg.$linefeed;
15491: } else {
15492: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15493: }
15494: foreach my $item (@badclasses) {
15495: if ($context eq 'auto') {
15496: $outcome .= " - $item\n";
15497: } else {
15498: $outcome .= "<li>$item</li>\n";
15499: }
15500: }
15501: if ($context eq 'auto') {
15502: $outcome .= $linefeed;
15503: } else {
15504: $outcome .= "</ul><br /><br /></div>\n";
15505: }
15506: }
15507: if ($args->{'no_end_date'}) {
15508: $args->{'endaccess'} = 0;
15509: }
15510: $cenv{'internal.autostart'}=$args->{'enrollstart'};
15511: $cenv{'internal.autoend'}=$args->{'enrollend'};
15512: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15513: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15514: if ($args->{'showphotos'}) {
15515: $cenv{'internal.showphotos'}=$args->{'showphotos'};
15516: }
15517: $cenv{'internal.authtype'} = $args->{'authtype'};
15518: $cenv{'internal.autharg'} = $args->{'autharg'};
15519: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15520: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
15521: 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');
15522: if ($context eq 'auto') {
15523: $outcome .= $krb_msg;
15524: } else {
15525: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15526: }
15527: $outcome .= $linefeed;
15528: }
15529: }
15530: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15531: if ($args->{'setpolicy'}) {
15532: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15533: }
15534: if ($args->{'setcontent'}) {
15535: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15536: }
15537: if ($args->{'setcomment'}) {
15538: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15539: }
15540: }
15541: if ($args->{'reshome'}) {
15542: $cenv{'reshome'}=$args->{'reshome'}.'/';
15543: $cenv{'reshome'}=~s/\/+$/\//;
15544: }
15545: #
15546: # course has keyed access
15547: #
15548: if ($args->{'setkeys'}) {
15549: $cenv{'keyaccess'}='yes';
15550: }
15551: # if specified, key authority is not course, but user
15552: # only active if keyaccess is yes
15553: if ($args->{'keyauth'}) {
15554: my ($user,$domain) = split(':',$args->{'keyauth'});
15555: $user = &LONCAPA::clean_username($user);
15556: $domain = &LONCAPA::clean_username($domain);
15557: if ($user ne '' && $domain ne '') {
15558: $cenv{'keyauth'}=$user.':'.$domain;
15559: }
15560: }
15561:
15562: #
15563: # generate and store uniquecode (available to course requester), if course should have one.
15564: #
15565: if ($args->{'uniquecode'}) {
15566: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15567: if ($code) {
15568: $cenv{'internal.uniquecode'} = $code;
15569: my %crsinfo =
15570: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15571: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15572: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15573: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15574: }
15575: if (ref($coderef)) {
15576: $$coderef = $code;
15577: }
15578: }
15579: }
15580:
15581: if ($args->{'disresdis'}) {
15582: $cenv{'pch.roles.denied'}='st';
15583: }
15584: if ($args->{'disablechat'}) {
15585: $cenv{'plc.roles.denied'}='st';
15586: }
15587:
15588: # Record we've not yet viewed the Course Initialization Helper for this
15589: # course
15590: $cenv{'course.helper.not.run'} = 1;
15591: #
15592: # Use new Randomseed
15593: #
15594: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15595: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15596: #
15597: # The encryption code and receipt prefix for this course
15598: #
15599: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15600: $cenv{'internal.encpref'}=100+int(9*rand(99));
15601: #
15602: # By default, use standard grading
15603: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15604:
15605: $outcome .= $linefeed.&mt('Setting environment').': '.
15606: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15607: #
15608: # Open all assignments
15609: #
15610: if ($args->{'openall'}) {
15611: my $opendate = time;
15612: if ($args->{'openallfrom'} =~ /^\d+$/) {
15613: $opendate = $args->{'openallfrom'};
15614: }
15615: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15616: my %storecontent = ($storeunder => $opendate,
15617: $storeunder.'.type' => 'date_start');
15618: $outcome .= &mt('All assignments open starting [_1]',
15619: &Apache::lonlocal::locallocaltime($opendate)).': '.
15620: &Apache::lonnet::cput
15621: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15622: }
15623: #
15624: # Set first page
15625: #
15626: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15627: || ($cloneid)) {
15628: use LONCAPA::map;
15629: $outcome .= &mt('Setting first resource').': ';
15630:
15631: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15632: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15633:
15634: $outcome .= ($fatal?$errtext:'read ok').' - ';
15635: my $title; my $url;
15636: if ($args->{'firstres'} eq 'syl') {
15637: $title=&mt('Syllabus');
15638: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15639: } else {
15640: $title=&mt('Table of Contents');
15641: $url='/adm/navmaps';
15642: }
15643:
15644: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15645: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15646:
15647: if ($errtext) { $fatal=2; }
15648: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15649: }
15650:
15651: return (1,$outcome,\@clonemsg);
15652: }
15653:
15654: sub make_unique_code {
15655: my ($cdom,$cnum) = @_;
15656: # get lock on uniquecodes db
15657: my $lockhash = {
15658: $cnum."\0".'uniquecodes' => $env{'user.name'}.
15659: ':'.$env{'user.domain'},
15660: };
15661: my $tries = 0;
15662: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15663: my ($code,$error);
15664:
15665: while (($gotlock ne 'ok') && ($tries<3)) {
15666: $tries ++;
15667: sleep 1;
15668: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15669: }
15670: if ($gotlock eq 'ok') {
15671: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15672: my $gotcode;
15673: my $attempts = 0;
15674: while ((!$gotcode) && ($attempts < 100)) {
15675: $code = &generate_code();
15676: if (!exists($currcodes{$code})) {
15677: $gotcode = 1;
15678: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15679: $error = 'nostore';
15680: }
15681: }
15682: $attempts ++;
15683: }
15684: my @del_lock = ($cnum."\0".'uniquecodes');
15685: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15686: } else {
15687: $error = 'nolock';
15688: }
15689: return ($code,$error);
15690: }
15691:
15692: sub generate_code {
15693: my $code;
15694: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15695: for (my $i=0; $i<6; $i++) {
15696: my $lettnum = int (rand 2);
15697: my $item = '';
15698: if ($lettnum) {
15699: $item = $letts[int( rand(18) )];
15700: } else {
15701: $item = 1+int( rand(8) );
15702: }
15703: $code .= $item;
15704: }
15705: return $code;
15706: }
15707:
15708: ############################################################
15709: ############################################################
15710:
15711: #SD
15712: # only Community and Course, or anything else?
15713: sub course_type {
15714: my ($cid) = @_;
15715: if (!defined($cid)) {
15716: $cid = $env{'request.course.id'};
15717: }
15718: if (defined($env{'course.'.$cid.'.type'})) {
15719: return $env{'course.'.$cid.'.type'};
15720: } else {
15721: return 'Course';
15722: }
15723: }
15724:
15725: sub group_term {
15726: my $crstype = &course_type();
15727: my %names = (
15728: 'Course' => 'group',
15729: 'Community' => 'group',
15730: );
15731: return $names{$crstype};
15732: }
15733:
15734: sub course_types {
15735: my @types = ('official','unofficial','community','textbook');
15736: my %typename = (
15737: official => 'Official course',
15738: unofficial => 'Unofficial course',
15739: community => 'Community',
15740: textbook => 'Textbook course',
15741: );
15742: return (\@types,\%typename);
15743: }
15744:
15745: sub icon {
15746: my ($file)=@_;
15747: my $curfext = lc((split(/\./,$file))[-1]);
15748: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15749: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15750: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15751: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15752: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15753: $curfext.".gif") {
15754: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15755: $curfext.".gif";
15756: }
15757: }
15758: return &lonhttpdurl($iconname);
15759: }
15760:
15761: sub lonhttpdurl {
15762: #
15763: # Had been used for "small fry" static images on separate port 8080.
15764: # Modify here if lightweight http functionality desired again.
15765: # Currently eliminated due to increasing firewall issues.
15766: #
15767: my ($url)=@_;
15768: return $url;
15769: }
15770:
15771: sub connection_aborted {
15772: my ($r)=@_;
15773: $r->print(" ");$r->rflush();
15774: my $c = $r->connection;
15775: return $c->aborted();
15776: }
15777:
15778: # Escapes strings that may have embedded 's that will be put into
15779: # strings as 'strings'.
15780: sub escape_single {
15781: my ($input) = @_;
15782: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
15783: $input =~ s/\'/\\\'/g; # Esacpe the 's....
15784: return $input;
15785: }
15786:
15787: # Same as escape_single, but escape's "'s This
15788: # can be used for "strings"
15789: sub escape_double {
15790: my ($input) = @_;
15791: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
15792: $input =~ s/\"/\\\"/g; # Esacpe the "s....
15793: return $input;
15794: }
15795:
15796: # Escapes the last element of a full URL.
15797: sub escape_url {
15798: my ($url) = @_;
15799: my @urlslices = split(/\//, $url,-1);
15800: my $lastitem = &escape(pop(@urlslices));
15801: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15802: }
15803:
15804: sub compare_arrays {
15805: my ($arrayref1,$arrayref2) = @_;
15806: my (@difference,%count);
15807: @difference = ();
15808: %count = ();
15809: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15810: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15811: foreach my $element (keys(%count)) {
15812: if ($count{$element} == 1) {
15813: push(@difference,$element);
15814: }
15815: }
15816: }
15817: return @difference;
15818: }
15819:
15820: # -------------------------------------------------------- Initialize user login
15821: sub init_user_environment {
15822: my ($r, $username, $domain, $authhost, $form, $args) = @_;
15823: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15824:
15825: my $public=($username eq 'public' && $domain eq 'public');
15826:
15827: # See if old ID present, if so, remove
15828:
15829: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15830: my $now=time;
15831:
15832: if ($public) {
15833: my $max_public=100;
15834: my $oldest;
15835: my $oldest_time=0;
15836: for(my $next=1;$next<=$max_public;$next++) {
15837: if (-e $lonids."/publicuser_$next.id") {
15838: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15839: if ($mtime<$oldest_time || !$oldest_time) {
15840: $oldest_time=$mtime;
15841: $oldest=$next;
15842: }
15843: } else {
15844: $cookie="publicuser_$next";
15845: last;
15846: }
15847: }
15848: if (!$cookie) { $cookie="publicuser_$oldest"; }
15849: } else {
15850: # if this isn't a robot, kill any existing non-robot sessions
15851: if (!$args->{'robot'}) {
15852: opendir(DIR,$lonids);
15853: while ($filename=readdir(DIR)) {
15854: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15855: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
15856: &GDBM_READER(),0640)) {
15857: my $linkedfile;
15858: if (exists($oldenv{'user.linkedenv'})) {
15859: $linkedfile = $oldenv{'user.linkedenv'};
15860: }
15861: untie(%oldenv);
15862: if (unlink("$lonids/$filename")) {
15863: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
15864: if (-l "$lonids/$linkedfile.id") {
15865: unlink("$lonids/$linkedfile.id");
15866: }
15867: }
15868: }
15869: } else {
15870: unlink($lonids.'/'.$filename);
15871: }
15872: }
15873: }
15874: closedir(DIR);
15875: # If there is a undeleted lockfile for the user's paste buffer remove it.
15876: my $namespace = 'nohist_courseeditor';
15877: my $lockingkey = 'paste'."\0".'locked_num';
15878: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15879: $domain,$username);
15880: if (exists($lockhash{$lockingkey})) {
15881: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15882: unless ($delresult eq 'ok') {
15883: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15884: }
15885: }
15886: }
15887: # Give them a new cookie
15888: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15889: : $now.$$.int(rand(10000)));
15890: $cookie="$username\_$id\_$domain\_$authhost";
15891:
15892: # Initialize roles
15893:
15894: ($userroles,$firstaccenv,$timerintenv) =
15895: &Apache::lonnet::rolesinit($domain,$username,$authhost);
15896: }
15897: # ------------------------------------ Check browser type and MathML capability
15898:
15899: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15900: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15901:
15902: # ------------------------------------------------------------- Get environment
15903:
15904: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15905: my ($tmp) = keys(%userenv);
15906: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15907: } else {
15908: undef(%userenv);
15909: }
15910: if (($userenv{'interface'}) && (!$form->{'interface'})) {
15911: $form->{'interface'}=$userenv{'interface'};
15912: }
15913: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15914:
15915: # --------------- Do not trust query string to be put directly into environment
15916: foreach my $option ('interface','localpath','localres') {
15917: $form->{$option}=~s/[\n\r\=]//gs;
15918: }
15919: # --------------------------------------------------------- Write first profile
15920:
15921: {
15922: my %initial_env =
15923: ("user.name" => $username,
15924: "user.domain" => $domain,
15925: "user.home" => $authhost,
15926: "browser.type" => $clientbrowser,
15927: "browser.version" => $clientversion,
15928: "browser.mathml" => $clientmathml,
15929: "browser.unicode" => $clientunicode,
15930: "browser.os" => $clientos,
15931: "browser.mobile" => $clientmobile,
15932: "browser.info" => $clientinfo,
15933: "browser.osversion" => $clientosversion,
15934: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
15935: "request.course.fn" => '',
15936: "request.course.uri" => '',
15937: "request.course.sec" => '',
15938: "request.role" => 'cm',
15939: "request.role.adv" => $env{'user.adv'},
15940: "request.host" => $ENV{'REMOTE_ADDR'},);
15941:
15942: if ($form->{'localpath'}) {
15943: $initial_env{"browser.localpath"} = $form->{'localpath'};
15944: $initial_env{"browser.localres"} = $form->{'localres'};
15945: }
15946:
15947: if ($form->{'interface'}) {
15948: $form->{'interface'}=~s/\W//gs;
15949: $initial_env{"browser.interface"} = $form->{'interface'};
15950: $env{'browser.interface'}=$form->{'interface'};
15951: }
15952:
15953: if ($form->{'iptoken'}) {
15954: my $lonhost = $r->dir_config('lonHostID');
15955: $initial_env{"user.noloadbalance"} = $lonhost;
15956: $env{'user.noloadbalance'} = $lonhost;
15957: }
15958:
15959: if ($form->{'noloadbalance'}) {
15960: my @hosts = &Apache::lonnet::current_machine_ids();
15961: my $hosthere = $form->{'noloadbalance'};
15962: if (grep(/^\Q$hosthere\E$/,@hosts)) {
15963: $initial_env{"user.noloadbalance"} = $hosthere;
15964: $env{'user.noloadbalance'} = $hosthere;
15965: }
15966: }
15967:
15968: unless ($domain eq 'public') {
15969: my %is_adv = ( is_adv => $env{'user.adv'} );
15970: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15971:
15972: foreach my $tool ('aboutme','blog','webdav','portfolio') {
15973: $userenv{'availabletools.'.$tool} =
15974: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15975: undef,\%userenv,\%domdef,\%is_adv);
15976: }
15977:
15978: foreach my $crstype ('official','unofficial','community','textbook') {
15979: $userenv{'canrequest.'.$crstype} =
15980: &Apache::lonnet::usertools_access($username,$domain,$crstype,
15981: 'reload','requestcourses',
15982: \%userenv,\%domdef,\%is_adv);
15983: }
15984:
15985: $userenv{'canrequest.author'} =
15986: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15987: 'reload','requestauthor',
15988: \%userenv,\%domdef,\%is_adv);
15989: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15990: $domain,$username);
15991: my $reqstatus = $reqauthor{'author_status'};
15992: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15993: if (ref($reqauthor{'author'}) eq 'HASH') {
15994: $userenv{'requestauthorqueued'} = $reqstatus.':'.
15995: $reqauthor{'author'}{'timestamp'};
15996: }
15997: }
15998: }
15999:
16000: $env{'user.environment'} = "$lonids/$cookie.id";
16001:
16002: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16003: &GDBM_WRCREAT(),0640)) {
16004: &_add_to_env(\%disk_env,\%initial_env);
16005: &_add_to_env(\%disk_env,\%userenv,'environment.');
16006: &_add_to_env(\%disk_env,$userroles);
16007: if (ref($firstaccenv) eq 'HASH') {
16008: &_add_to_env(\%disk_env,$firstaccenv);
16009: }
16010: if (ref($timerintenv) eq 'HASH') {
16011: &_add_to_env(\%disk_env,$timerintenv);
16012: }
16013: if (ref($args->{'extra_env'})) {
16014: &_add_to_env(\%disk_env,$args->{'extra_env'});
16015: }
16016: untie(%disk_env);
16017: } else {
16018: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16019: 'Could not create environment storage in lonauth: '.$!.'</span>');
16020: return 'error: '.$!;
16021: }
16022: }
16023: $env{'request.role'}='cm';
16024: $env{'request.role.adv'}=$env{'user.adv'};
16025: $env{'browser.type'}=$clientbrowser;
16026:
16027: return $cookie;
16028:
16029: }
16030:
16031: sub _add_to_env {
16032: my ($idf,$env_data,$prefix) = @_;
16033: if (ref($env_data) eq 'HASH') {
16034: while (my ($key,$value) = each(%$env_data)) {
16035: $idf->{$prefix.$key} = $value;
16036: $env{$prefix.$key} = $value;
16037: }
16038: }
16039: }
16040:
16041: # --- Get the symbolic name of a problem and the url
16042: sub get_symb {
16043: my ($request,$silent) = @_;
16044: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16045: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16046: if ($symb eq '') {
16047: if (!$silent) {
16048: if (ref($request)) {
16049: $request->print("Unable to handle ambiguous references:$url:.");
16050: }
16051: return ();
16052: }
16053: }
16054: &Apache::lonenc::check_decrypt(\$symb);
16055: return ($symb);
16056: }
16057:
16058: # --------------------------------------------------------------Get annotation
16059:
16060: sub get_annotation {
16061: my ($symb,$enc) = @_;
16062:
16063: my $key = $symb;
16064: if (!$enc) {
16065: $key =
16066: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16067: }
16068: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16069: return $annotation{$key};
16070: }
16071:
16072: sub clean_symb {
16073: my ($symb,$delete_enc) = @_;
16074:
16075: &Apache::lonenc::check_decrypt(\$symb);
16076: my $enc = $env{'request.enc'};
16077: if ($delete_enc) {
16078: delete($env{'request.enc'});
16079: }
16080:
16081: return ($symb,$enc);
16082: }
16083:
16084: ############################################################
16085: ############################################################
16086:
16087: =pod
16088:
16089: =head1 Routines for building display used to search for courses
16090:
16091:
16092: =over 4
16093:
16094: =item * &build_filters()
16095:
16096: Create markup for a table used to set filters to use when selecting
16097: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
16098: and quotacheck.pl
16099:
16100:
16101: Inputs:
16102:
16103: filterlist - anonymous array of fields to include as potential filters
16104:
16105: crstype - course type
16106:
16107: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16108: to pop-open a course selector (will contain "extra element").
16109:
16110: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16111:
16112: filter - anonymous hash of criteria and their values
16113:
16114: action - form action
16115:
16116: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16117:
16118: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16119:
16120: cloneruname - username of owner of new course who wants to clone
16121:
16122: clonerudom - domain of owner of new course who wants to clone
16123:
16124: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16125:
16126: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16127:
16128: codedom - domain
16129:
16130: formname - value of form element named "form".
16131:
16132: fixeddom - domain, if fixed.
16133:
16134: prevphase - value to assign to form element named "phase" when going back to the previous screen
16135:
16136: cnameelement - name of form element in form on opener page which will receive title of selected course
16137:
16138: cnumelement - name of form element in form on opener page which will receive courseID of selected course
16139:
16140: cdomelement - name of form element in form on opener page which will receive domain of selected course
16141:
16142: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16143:
16144: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16145:
16146: clonewarning - warning message about missing information for intended course owner when DC creates a course
16147:
16148:
16149: Returns: $output - HTML for display of search criteria, and hidden form elements.
16150:
16151:
16152: Side Effects: None
16153:
16154: =cut
16155:
16156: # ---------------------------------------------- search for courses based on last activity etc.
16157:
16158: sub build_filters {
16159: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16160: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16161: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16162: $cnameelement,$cnumelement,$cdomelement,$setroles,
16163: $clonetext,$clonewarning) = @_;
16164: my ($list,$jscript);
16165: my $onchange = 'javascript:updateFilters(this)';
16166: my ($domainselectform,$sincefilterform,$createdfilterform,
16167: $ownerdomselectform,$persondomselectform,$instcodeform,
16168: $typeselectform,$instcodetitle);
16169: if ($formname eq '') {
16170: $formname = $caller;
16171: }
16172: foreach my $item (@{$filterlist}) {
16173: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16174: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16175: if ($item eq 'domainfilter') {
16176: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16177: } elsif ($item eq 'coursefilter') {
16178: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16179: } elsif ($item eq 'ownerfilter') {
16180: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16181: } elsif ($item eq 'ownerdomfilter') {
16182: $filter->{'ownerdomfilter'} =
16183: &LONCAPA::clean_domain($filter->{$item});
16184: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16185: 'ownerdomfilter',1);
16186: } elsif ($item eq 'personfilter') {
16187: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16188: } elsif ($item eq 'persondomfilter') {
16189: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16190: 'persondomfilter',1);
16191: } else {
16192: $filter->{$item} =~ s/\W//g;
16193: }
16194: if (!$filter->{$item}) {
16195: $filter->{$item} = '';
16196: }
16197: }
16198: if ($item eq 'domainfilter') {
16199: my $allow_blank = 1;
16200: if ($formname eq 'portform') {
16201: $allow_blank=0;
16202: } elsif ($formname eq 'studentform') {
16203: $allow_blank=0;
16204: }
16205: if ($fixeddom) {
16206: $domainselectform = '<input type="hidden" name="domainfilter"'.
16207: ' value="'.$codedom.'" />'.
16208: &Apache::lonnet::domain($codedom,'description');
16209: } else {
16210: $domainselectform = &select_dom_form($filter->{$item},
16211: 'domainfilter',
16212: $allow_blank,'',$onchange);
16213: }
16214: } else {
16215: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16216: }
16217: }
16218:
16219: # last course activity filter and selection
16220: $sincefilterform = &timebased_select_form('sincefilter',$filter);
16221:
16222: # course created filter and selection
16223: if (exists($filter->{'createdfilter'})) {
16224: $createdfilterform = &timebased_select_form('createdfilter',$filter);
16225: }
16226:
16227: my %lt = &Apache::lonlocal::texthash(
16228: 'cac' => "$crstype Activity",
16229: 'ccr' => "$crstype Created",
16230: 'cde' => "$crstype Title",
16231: 'cdo' => "$crstype Domain",
16232: 'ins' => 'Institutional Code',
16233: 'inc' => 'Institutional Categorization',
16234: 'cow' => "$crstype Owner/Co-owner",
16235: 'cop' => "$crstype Personnel Includes",
16236: 'cog' => 'Type',
16237: );
16238:
16239: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16240: my $typeval = 'Course';
16241: if ($crstype eq 'Community') {
16242: $typeval = 'Community';
16243: }
16244: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16245: } else {
16246: $typeselectform = '<select name="type" size="1"';
16247: if ($onchange) {
16248: $typeselectform .= ' onchange="'.$onchange.'"';
16249: }
16250: $typeselectform .= '>'."\n";
16251: foreach my $posstype ('Course','Community') {
16252: $typeselectform.='<option value="'.$posstype.'"'.
16253: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16254: }
16255: $typeselectform.="</select>";
16256: }
16257:
16258: my ($cloneableonlyform,$cloneabletitle);
16259: if (exists($filter->{'cloneableonly'})) {
16260: my $cloneableon = '';
16261: my $cloneableoff = ' checked="checked"';
16262: if ($filter->{'cloneableonly'}) {
16263: $cloneableon = $cloneableoff;
16264: $cloneableoff = '';
16265: }
16266: $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>';
16267: if ($formname eq 'ccrs') {
16268: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16269: } else {
16270: $cloneabletitle = &mt('Cloneable by you');
16271: }
16272: }
16273: my $officialjs;
16274: if ($crstype eq 'Course') {
16275: if (exists($filter->{'instcodefilter'})) {
16276: # if (($fixeddom) || ($formname eq 'requestcrs') ||
16277: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16278: if ($codedom) {
16279: $officialjs = 1;
16280: ($instcodeform,$jscript,$$numtitlesref) =
16281: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16282: $officialjs,$codetitlesref);
16283: if ($jscript) {
16284: $jscript = '<script type="text/javascript">'."\n".
16285: '// <![CDATA['."\n".
16286: $jscript."\n".
16287: '// ]]>'."\n".
16288: '</script>'."\n";
16289: }
16290: }
16291: if ($instcodeform eq '') {
16292: $instcodeform =
16293: '<input type="text" name="instcodefilter" size="10" value="'.
16294: $list->{'instcodefilter'}.'" />';
16295: $instcodetitle = $lt{'ins'};
16296: } else {
16297: $instcodetitle = $lt{'inc'};
16298: }
16299: if ($fixeddom) {
16300: $instcodetitle .= '<br />('.$codedom.')';
16301: }
16302: }
16303: }
16304: my $output = qq|
16305: <form method="post" name="filterpicker" action="$action">
16306: <input type="hidden" name="form" value="$formname" />
16307: |;
16308: if ($formname eq 'modifycourse') {
16309: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16310: '<input type="hidden" name="prevphase" value="'.
16311: $prevphase.'" />'."\n";
16312: } elsif ($formname eq 'quotacheck') {
16313: $output .= qq|
16314: <input type="hidden" name="sortby" value="" />
16315: <input type="hidden" name="sortorder" value="" />
16316: |;
16317: } else {
16318: my $name_input;
16319: if ($cnameelement ne '') {
16320: $name_input = '<input type="hidden" name="cnameelement" value="'.
16321: $cnameelement.'" />';
16322: }
16323: $output .= qq|
16324: <input type="hidden" name="cnumelement" value="$cnumelement" />
16325: <input type="hidden" name="cdomelement" value="$cdomelement" />
16326: $name_input
16327: $roleelement
16328: $multelement
16329: $typeelement
16330: |;
16331: if ($formname eq 'portform') {
16332: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16333: }
16334: }
16335: if ($fixeddom) {
16336: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16337: }
16338: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16339: if ($sincefilterform) {
16340: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16341: .$sincefilterform
16342: .&Apache::lonhtmlcommon::row_closure();
16343: }
16344: if ($createdfilterform) {
16345: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16346: .$createdfilterform
16347: .&Apache::lonhtmlcommon::row_closure();
16348: }
16349: if ($domainselectform) {
16350: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16351: .$domainselectform
16352: .&Apache::lonhtmlcommon::row_closure();
16353: }
16354: if ($typeselectform) {
16355: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16356: $output .= $typeselectform;
16357: } else {
16358: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16359: .$typeselectform
16360: .&Apache::lonhtmlcommon::row_closure();
16361: }
16362: }
16363: if ($instcodeform) {
16364: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16365: .$instcodeform
16366: .&Apache::lonhtmlcommon::row_closure();
16367: }
16368: if (exists($filter->{'ownerfilter'})) {
16369: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16370: '<table><tr><td>'.&mt('Username').'<br />'.
16371: '<input type="text" name="ownerfilter" size="20" value="'.
16372: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16373: $ownerdomselectform.'</td></tr></table>'.
16374: &Apache::lonhtmlcommon::row_closure();
16375: }
16376: if (exists($filter->{'personfilter'})) {
16377: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16378: '<table><tr><td>'.&mt('Username').'<br />'.
16379: '<input type="text" name="personfilter" size="20" value="'.
16380: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16381: $persondomselectform.'</td></tr></table>'.
16382: &Apache::lonhtmlcommon::row_closure();
16383: }
16384: if (exists($filter->{'coursefilter'})) {
16385: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16386: .'<input type="text" name="coursefilter" size="25" value="'
16387: .$list->{'coursefilter'}.'" />'
16388: .&Apache::lonhtmlcommon::row_closure();
16389: }
16390: if ($cloneableonlyform) {
16391: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16392: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16393: }
16394: if (exists($filter->{'descriptfilter'})) {
16395: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16396: .'<input type="text" name="descriptfilter" size="40" value="'
16397: .$list->{'descriptfilter'}.'" />'
16398: .&Apache::lonhtmlcommon::row_closure(1);
16399: }
16400: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16401: '<input type="hidden" name="updater" value="" />'."\n".
16402: '<input type="submit" name="gosearch" value="'.
16403: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16404: return $jscript.$clonewarning.$output;
16405: }
16406:
16407: =pod
16408:
16409: =item * &timebased_select_form()
16410:
16411: Create markup for a dropdown list used to select a time-based
16412: filter e.g., Course Activity, Course Created, when searching for courses
16413: or communities
16414:
16415: Inputs:
16416:
16417: item - name of form element (sincefilter or createdfilter)
16418:
16419: filter - anonymous hash of criteria and their values
16420:
16421: Returns: HTML for a select box contained a blank, then six time selections,
16422: with value set in incoming form variables currently selected.
16423:
16424: Side Effects: None
16425:
16426: =cut
16427:
16428: sub timebased_select_form {
16429: my ($item,$filter) = @_;
16430: if (ref($filter) eq 'HASH') {
16431: $filter->{$item} =~ s/[^\d-]//g;
16432: if (!$filter->{$item}) { $filter->{$item}=-1; }
16433: return &select_form(
16434: $filter->{$item},
16435: $item,
16436: { '-1' => '',
16437: '86400' => &mt('today'),
16438: '604800' => &mt('last week'),
16439: '2592000' => &mt('last month'),
16440: '7776000' => &mt('last three months'),
16441: '15552000' => &mt('last six months'),
16442: '31104000' => &mt('last year'),
16443: 'select_form_order' =>
16444: ['-1','86400','604800','2592000','7776000',
16445: '15552000','31104000']});
16446: }
16447: }
16448:
16449: =pod
16450:
16451: =item * &js_changer()
16452:
16453: Create script tag containing Javascript used to submit course search form
16454: when course type or domain is changed, and also to hide 'Searching ...' on
16455: page load completion for page showing search result.
16456:
16457: Inputs: None
16458:
16459: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16460:
16461: Side Effects: None
16462:
16463: =cut
16464:
16465: sub js_changer {
16466: return <<ENDJS;
16467: <script type="text/javascript">
16468: // <![CDATA[
16469: function updateFilters(caller) {
16470: if (typeof(caller) != "undefined") {
16471: document.filterpicker.updater.value = caller.name;
16472: }
16473: document.filterpicker.submit();
16474: }
16475:
16476: function hideSearching() {
16477: if (document.getElementById('searching')) {
16478: document.getElementById('searching').style.display = 'none';
16479: }
16480: return;
16481: }
16482:
16483: // ]]>
16484: </script>
16485:
16486: ENDJS
16487: }
16488:
16489: =pod
16490:
16491: =item * &search_courses()
16492:
16493: Process selected filters form course search form and pass to lonnet::courseiddump
16494: to retrieve a hash for which keys are courseIDs which match the selected filters.
16495:
16496: Inputs:
16497:
16498: dom - domain being searched
16499:
16500: type - course type ('Course' or 'Community' or '.' if any).
16501:
16502: filter - anonymous hash of criteria and their values
16503:
16504: numtitles - for institutional codes - number of categories
16505:
16506: cloneruname - optional username of new course owner
16507:
16508: clonerudom - optional domain of new course owner
16509:
16510: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16511: (used when DC is using course creation form)
16512:
16513: codetitles - reference to array of titles of components in institutional codes (official courses).
16514:
16515: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16516: (and so can clone automatically)
16517:
16518: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16519:
16520: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16521: courses to clone
16522:
16523: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16524:
16525:
16526: Side Effects: None
16527:
16528: =cut
16529:
16530:
16531: sub search_courses {
16532: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16533: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16534: my (%courses,%showcourses,$cloner);
16535: if (($filter->{'ownerfilter'} ne '') ||
16536: ($filter->{'ownerdomfilter'} ne '')) {
16537: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16538: $filter->{'ownerdomfilter'};
16539: }
16540: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16541: if (!$filter->{$item}) {
16542: $filter->{$item}='.';
16543: }
16544: }
16545: my $now = time;
16546: my $timefilter =
16547: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16548: my ($createdbefore,$createdafter);
16549: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16550: $createdbefore = $now;
16551: $createdafter = $now-$filter->{'createdfilter'};
16552: }
16553: my ($instcodefilter,$regexpok);
16554: if ($numtitles) {
16555: if ($env{'form.official'} eq 'on') {
16556: $instcodefilter =
16557: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16558: $regexpok = 1;
16559: } elsif ($env{'form.official'} eq 'off') {
16560: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16561: unless ($instcodefilter eq '') {
16562: $regexpok = -1;
16563: }
16564: }
16565: } else {
16566: $instcodefilter = $filter->{'instcodefilter'};
16567: }
16568: if ($instcodefilter eq '') { $instcodefilter = '.'; }
16569: if ($type eq '') { $type = '.'; }
16570:
16571: if (($clonerudom ne '') && ($cloneruname ne '')) {
16572: $cloner = $cloneruname.':'.$clonerudom;
16573: }
16574: %courses = &Apache::lonnet::courseiddump($dom,
16575: $filter->{'descriptfilter'},
16576: $timefilter,
16577: $instcodefilter,
16578: $filter->{'combownerfilter'},
16579: $filter->{'coursefilter'},
16580: undef,undef,$type,$regexpok,undef,undef,
16581: undef,undef,$cloner,$cc_clone,
16582: $filter->{'cloneableonly'},
16583: $createdbefore,$createdafter,undef,
16584: $domcloner,undef,$reqcrsdom,$reqinstcode);
16585: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16586: my $ccrole;
16587: if ($type eq 'Community') {
16588: $ccrole = 'co';
16589: } else {
16590: $ccrole = 'cc';
16591: }
16592: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16593: $filter->{'persondomfilter'},
16594: 'userroles',undef,
16595: [$ccrole,'in','ad','ep','ta','cr'],
16596: $dom);
16597: foreach my $role (keys(%rolehash)) {
16598: my ($cnum,$cdom,$courserole) = split(':',$role);
16599: my $cid = $cdom.'_'.$cnum;
16600: if (exists($courses{$cid})) {
16601: if (ref($courses{$cid}) eq 'HASH') {
16602: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16603: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16604: push(@{$courses{$cid}{roles}},$courserole);
16605: }
16606: } else {
16607: $courses{$cid}{roles} = [$courserole];
16608: }
16609: $showcourses{$cid} = $courses{$cid};
16610: }
16611: }
16612: }
16613: %courses = %showcourses;
16614: }
16615: return %courses;
16616: }
16617:
16618: =pod
16619:
16620: =back
16621:
16622: =head1 Routines for version requirements for current course.
16623:
16624: =over 4
16625:
16626: =item * &check_release_required()
16627:
16628: Compares required LON-CAPA version with version on server, and
16629: if required version is newer looks for a server with the required version.
16630:
16631: Looks first at servers in user's owen domain; if none suitable, looks at
16632: servers in course's domain are permitted to host sessions for user's domain.
16633:
16634: Inputs:
16635:
16636: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16637:
16638: $courseid - Course ID of current course
16639:
16640: $rolecode - User's current role in course (for switchserver query string).
16641:
16642: $required - LON-CAPA version needed by course (format: Major.Minor).
16643:
16644:
16645: Returns:
16646:
16647: $switchserver - query string tp append to /adm/switchserver call (if
16648: current server's LON-CAPA version is too old.
16649:
16650: $warning - Message is displayed if no suitable server could be found.
16651:
16652: =cut
16653:
16654: sub check_release_required {
16655: my ($loncaparev,$courseid,$rolecode,$required) = @_;
16656: my ($switchserver,$warning);
16657: if ($required ne '') {
16658: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16659: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16660: if ($reqdmajor ne '' && $reqdminor ne '') {
16661: my $otherserver;
16662: if (($major eq '' && $minor eq '') ||
16663: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16664: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16665: my $switchlcrev =
16666: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16667: $userdomserver);
16668: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16669: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16670: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16671: my $cdom = $env{'course.'.$courseid.'.domain'};
16672: if ($cdom ne $env{'user.domain'}) {
16673: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16674: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16675: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16676: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16677: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16678: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16679: my $canhost =
16680: &Apache::lonnet::can_host_session($env{'user.domain'},
16681: $coursedomserver,
16682: $remoterev,
16683: $udomdefaults{'remotesessions'},
16684: $defdomdefaults{'hostedsessions'});
16685:
16686: if ($canhost) {
16687: $otherserver = $coursedomserver;
16688: } else {
16689: $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.");
16690: }
16691: } else {
16692: $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).");
16693: }
16694: } else {
16695: $otherserver = $userdomserver;
16696: }
16697: }
16698: if ($otherserver ne '') {
16699: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
16700: }
16701: }
16702: }
16703: return ($switchserver,$warning);
16704: }
16705:
16706: =pod
16707:
16708: =item * &check_release_result()
16709:
16710: Inputs:
16711:
16712: $switchwarning - Warning message if no suitable server found to host session.
16713:
16714: $switchserver - query string to append to /adm/switchserver containing lonHostID
16715: and current role.
16716:
16717: Returns: HTML to display with information about requirement to switch server.
16718: Either displaying warning with link to Roles/Courses screen or
16719: display link to switchserver.
16720:
16721: =cut
16722:
16723: sub check_release_result {
16724: my ($switchwarning,$switchserver) = @_;
16725: my $output = &start_page('Selected course unavailable on this server').
16726: '<p class="LC_warning">';
16727: if ($switchwarning) {
16728: $output .= $switchwarning.'<br /><a href="/adm/roles">';
16729: if (&show_course()) {
16730: $output .= &mt('Display courses');
16731: } else {
16732: $output .= &mt('Display roles');
16733: }
16734: $output .= '</a>';
16735: } elsif ($switchserver) {
16736: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16737: '<br />'.
16738: '<a href="/adm/switchserver?'.$switchserver.'">'.
16739: &mt('Switch Server').
16740: '</a>';
16741: }
16742: $output .= '</p>'.&end_page();
16743: return $output;
16744: }
16745:
16746: =pod
16747:
16748: =item * &needs_coursereinit()
16749:
16750: Determine if course contents stored for user's session needs to be
16751: refreshed, because content has changed since "Big Hash" last tied.
16752:
16753: Check for change is made if time last checked is more than 10 minutes ago
16754: (by default).
16755:
16756: Inputs:
16757:
16758: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16759:
16760: $interval (optional) - Time which may elapse (in s) between last check for content
16761: change in current course. (default: 600 s).
16762:
16763: Returns: an array; first element is:
16764:
16765: =over 4
16766:
16767: 'switch' - if content updates mean user's session
16768: needs to be switched to a server running a newer LON-CAPA version
16769:
16770: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16771: on current server hosting user's session
16772:
16773: '' - if no action required.
16774:
16775: =back
16776:
16777: If first item element is 'switch':
16778:
16779: second item is $switchwarning - Warning message if no suitable server found to host session.
16780:
16781: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16782: and current role.
16783:
16784: otherwise: no other elements returned.
16785:
16786: =back
16787:
16788: =cut
16789:
16790: sub needs_coursereinit {
16791: my ($loncaparev,$interval) = @_;
16792: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16793: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16794: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16795: my $now = time;
16796: if ($interval eq '') {
16797: $interval = 600;
16798: }
16799: if (($now-$env{'request.course.timechecked'})>$interval) {
16800: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16801: my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
16802: if ($blocked) {
16803: return ();
16804: }
16805: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16806: if ($lastchange > $env{'request.course.tied'}) {
16807: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16808: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16809: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16810: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16811: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16812: $curr_reqd_hash{'internal.releaserequired'}});
16813: my ($switchserver,$switchwarning) =
16814: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16815: $curr_reqd_hash{'internal.releaserequired'});
16816: if ($switchwarning ne '' || $switchserver ne '') {
16817: return ('switch',$switchwarning,$switchserver);
16818: }
16819: }
16820: }
16821: return ('update');
16822: }
16823: }
16824: return ();
16825: }
16826:
16827: sub update_content_constraints {
16828: my ($cdom,$cnum,$chome,$cid) = @_;
16829: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16830: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16831: my %checkresponsetypes;
16832: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16833: my ($item,$name,$value) = split(/:/,$key);
16834: if ($item eq 'resourcetag') {
16835: if ($name eq 'responsetype') {
16836: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16837: }
16838: }
16839: }
16840: my $navmap = Apache::lonnavmaps::navmap->new();
16841: if (defined($navmap)) {
16842: my %allresponses;
16843: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16844: my %responses = $res->responseTypes();
16845: foreach my $key (keys(%responses)) {
16846: next unless(exists($checkresponsetypes{$key}));
16847: $allresponses{$key} += $responses{$key};
16848: }
16849: }
16850: foreach my $key (keys(%allresponses)) {
16851: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16852: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16853: ($reqdmajor,$reqdminor) = ($major,$minor);
16854: }
16855: }
16856: undef($navmap);
16857: }
16858: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16859: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16860: }
16861: return;
16862: }
16863:
16864: sub allmaps_incourse {
16865: my ($cdom,$cnum,$chome,$cid) = @_;
16866: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16867: $cid = $env{'request.course.id'};
16868: $cdom = $env{'course.'.$cid.'.domain'};
16869: $cnum = $env{'course.'.$cid.'.num'};
16870: $chome = $env{'course.'.$cid.'.home'};
16871: }
16872: my %allmaps = ();
16873: my $lastchange =
16874: &Apache::lonnet::get_coursechange($cdom,$cnum);
16875: if ($lastchange > $env{'request.course.tied'}) {
16876: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16877: unless ($ferr) {
16878: &update_content_constraints($cdom,$cnum,$chome,$cid);
16879: }
16880: }
16881: my $navmap = Apache::lonnavmaps::navmap->new();
16882: if (defined($navmap)) {
16883: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16884: $allmaps{$res->src()} = 1;
16885: }
16886: }
16887: return \%allmaps;
16888: }
16889:
16890: sub parse_supplemental_title {
16891: my ($title) = @_;
16892:
16893: my ($foldertitle,$renametitle);
16894: if ($title =~ /&&&/) {
16895: $title = &HTML::Entites::decode($title);
16896: }
16897: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16898: $renametitle=$4;
16899: my ($time,$uname,$udom) = ($1,$2,$3);
16900: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16901: my $name = &plainname($uname,$udom);
16902: $name = &HTML::Entities::encode($name,'"<>&\'');
16903: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16904: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16905: $name.': <br />'.$foldertitle;
16906: }
16907: if (wantarray) {
16908: return ($title,$foldertitle,$renametitle);
16909: }
16910: return $title;
16911: }
16912:
16913: sub recurse_supplemental {
16914: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16915: if ($suppmap) {
16916: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16917: if ($fatal) {
16918: $errors ++;
16919: } else {
16920: if ($#LONCAPA::map::resources > 0) {
16921: foreach my $res (@LONCAPA::map::resources) {
16922: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16923: if (($src ne '') && ($status eq 'res')) {
16924: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16925: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16926: } else {
16927: $numfiles ++;
16928: }
16929: }
16930: }
16931: }
16932: }
16933: }
16934: return ($numfiles,$errors);
16935: }
16936:
16937: sub symb_to_docspath {
16938: my ($symb,$navmapref) = @_;
16939: return unless ($symb && ref($navmapref));
16940: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16941: if ($resurl=~/\.(sequence|page)$/) {
16942: $mapurl=$resurl;
16943: } elsif ($resurl eq 'adm/navmaps') {
16944: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16945: }
16946: my $mapresobj;
16947: unless (ref($$navmapref)) {
16948: $$navmapref = Apache::lonnavmaps::navmap->new();
16949: }
16950: if (ref($$navmapref)) {
16951: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16952: }
16953: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16954: my $type=$2;
16955: my $path;
16956: if (ref($mapresobj)) {
16957: my $pcslist = $mapresobj->map_hierarchy();
16958: if ($pcslist ne '') {
16959: foreach my $pc (split(/,/,$pcslist)) {
16960: next if ($pc <= 1);
16961: my $res = $$navmapref->getByMapPc($pc);
16962: if (ref($res)) {
16963: my $thisurl = $res->src();
16964: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16965: my $thistitle = $res->title();
16966: $path .= '&'.
16967: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16968: &escape($thistitle).
16969: ':'.$res->randompick().
16970: ':'.$res->randomout().
16971: ':'.$res->encrypted().
16972: ':'.$res->randomorder().
16973: ':'.$res->is_page();
16974: }
16975: }
16976: }
16977: $path =~ s/^\&//;
16978: my $maptitle = $mapresobj->title();
16979: if ($mapurl eq 'default') {
16980: $maptitle = 'Main Content';
16981: }
16982: $path .= (($path ne '')? '&' : '').
16983: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16984: &escape($maptitle).
16985: ':'.$mapresobj->randompick().
16986: ':'.$mapresobj->randomout().
16987: ':'.$mapresobj->encrypted().
16988: ':'.$mapresobj->randomorder().
16989: ':'.$mapresobj->is_page();
16990: } else {
16991: my $maptitle = &Apache::lonnet::gettitle($mapurl);
16992: my $ispage = (($type eq 'page')? 1 : '');
16993: if ($mapurl eq 'default') {
16994: $maptitle = 'Main Content';
16995: }
16996: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16997: &escape($maptitle).':::::'.$ispage;
16998: }
16999: unless ($mapurl eq 'default') {
17000: $path = 'default&'.
17001: &escape('Main Content').
17002: ':::::&'.$path;
17003: }
17004: return $path;
17005: }
17006:
17007: sub captcha_display {
17008: my ($context,$lonhost,$defdom) = @_;
17009: my ($output,$error);
17010: my ($captcha,$pubkey,$privkey,$version) =
17011: &get_captcha_config($context,$lonhost,$defdom);
17012: if ($captcha eq 'original') {
17013: $output = &create_captcha();
17014: unless ($output) {
17015: $error = 'captcha';
17016: }
17017: } elsif ($captcha eq 'recaptcha') {
17018: $output = &create_recaptcha($pubkey,$version);
17019: unless ($output) {
17020: $error = 'recaptcha';
17021: }
17022: }
17023: return ($output,$error,$captcha,$version);
17024: }
17025:
17026: sub captcha_response {
17027: my ($context,$lonhost,$defdom) = @_;
17028: my ($captcha_chk,$captcha_error);
17029: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17030: if ($captcha eq 'original') {
17031: ($captcha_chk,$captcha_error) = &check_captcha();
17032: } elsif ($captcha eq 'recaptcha') {
17033: $captcha_chk = &check_recaptcha($privkey,$version);
17034: } else {
17035: $captcha_chk = 1;
17036: }
17037: return ($captcha_chk,$captcha_error);
17038: }
17039:
17040: sub get_captcha_config {
17041: my ($context,$lonhost,$dom_in_effect) = @_;
17042: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17043: my $hostname = &Apache::lonnet::hostname($lonhost);
17044: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17045: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17046: if ($context eq 'usercreation') {
17047: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17048: if (ref($domconfig{$context}) eq 'HASH') {
17049: $hashtocheck = $domconfig{$context}{'cancreate'};
17050: if (ref($hashtocheck) eq 'HASH') {
17051: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17052: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17053: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17054: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17055: }
17056: if ($privkey && $pubkey) {
17057: $captcha = 'recaptcha';
17058: $version = $hashtocheck->{'recaptchaversion'};
17059: if ($version ne '2') {
17060: $version = 1;
17061: }
17062: } else {
17063: $captcha = 'original';
17064: }
17065: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17066: $captcha = 'original';
17067: }
17068: }
17069: } else {
17070: $captcha = 'captcha';
17071: }
17072: } elsif ($context eq 'login') {
17073: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17074: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17075: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17076: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17077: if ($privkey && $pubkey) {
17078: $captcha = 'recaptcha';
17079: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17080: if ($version ne '2') {
17081: $version = 1;
17082: }
17083: } else {
17084: $captcha = 'original';
17085: }
17086: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17087: $captcha = 'original';
17088: }
17089: } elsif ($context eq 'passwords') {
17090: if ($dom_in_effect) {
17091: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17092: if ($passwdconf{'captcha'} eq 'recaptcha') {
17093: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17094: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17095: $privkey = $passwdconf{'recaptchakeys'}{'private'};
17096: }
17097: if ($privkey && $pubkey) {
17098: $captcha = 'recaptcha';
17099: $version = $passwdconf{'recaptchaversion'};
17100: if ($version ne '2') {
17101: $version = 1;
17102: }
17103: } else {
17104: $captcha = 'original';
17105: }
17106: } elsif ($passwdconf{'captcha'} ne 'notused') {
17107: $captcha = 'original';
17108: }
17109: }
17110: }
17111: return ($captcha,$pubkey,$privkey,$version);
17112: }
17113:
17114: sub create_captcha {
17115: my %captcha_params = &captcha_settings();
17116: my ($output,$maxtries,$tries) = ('',10,0);
17117: while ($tries < $maxtries) {
17118: $tries ++;
17119: my $captcha = Authen::Captcha->new (
17120: output_folder => $captcha_params{'output_dir'},
17121: data_folder => $captcha_params{'db_dir'},
17122: );
17123: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17124:
17125: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17126: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17127: &mt('Type in the letters/numbers shown below').' '.
17128: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17129: '<br />'.
17130: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17131: last;
17132: }
17133: }
17134: return $output;
17135: }
17136:
17137: sub captcha_settings {
17138: my %captcha_params = (
17139: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17140: www_output_dir => "/captchaspool",
17141: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17142: numchars => '5',
17143: );
17144: return %captcha_params;
17145: }
17146:
17147: sub check_captcha {
17148: my ($captcha_chk,$captcha_error);
17149: my $code = $env{'form.code'};
17150: my $md5sum = $env{'form.crypt'};
17151: my %captcha_params = &captcha_settings();
17152: my $captcha = Authen::Captcha->new(
17153: output_folder => $captcha_params{'output_dir'},
17154: data_folder => $captcha_params{'db_dir'},
17155: );
17156: $captcha_chk = $captcha->check_code($code,$md5sum);
17157: my %captcha_hash = (
17158: 0 => 'Code not checked (file error)',
17159: -1 => 'Failed: code expired',
17160: -2 => 'Failed: invalid code (not in database)',
17161: -3 => 'Failed: invalid code (code does not match crypt)',
17162: );
17163: if ($captcha_chk != 1) {
17164: $captcha_error = $captcha_hash{$captcha_chk}
17165: }
17166: return ($captcha_chk,$captcha_error);
17167: }
17168:
17169: sub create_recaptcha {
17170: my ($pubkey,$version) = @_;
17171: if ($version >= 2) {
17172: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17173: } else {
17174: my $use_ssl;
17175: if ($ENV{'SERVER_PORT'} == 443) {
17176: $use_ssl = 1;
17177: }
17178: my $captcha = Captcha::reCAPTCHA->new;
17179: return $captcha->get_options_setter({theme => 'white'})."\n".
17180: $captcha->get_html($pubkey,undef,$use_ssl).
17181: &mt('If the text is hard to read, [_1] will replace them.',
17182: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17183: '<br /><br />';
17184: }
17185: }
17186:
17187: sub check_recaptcha {
17188: my ($privkey,$version) = @_;
17189: my $captcha_chk;
17190: if ($version >= 2) {
17191: my $ua = LWP::UserAgent->new;
17192: $ua->timeout(10);
17193: my %info = (
17194: secret => $privkey,
17195: response => $env{'form.g-recaptcha-response'},
17196: remoteip => $ENV{'REMOTE_ADDR'},
17197: );
17198: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17199: if ($response->is_success) {
17200: my $data = JSON::DWIW->from_json($response->decoded_content);
17201: if (ref($data) eq 'HASH') {
17202: if ($data->{'success'}) {
17203: $captcha_chk = 1;
17204: }
17205: }
17206: }
17207: } else {
17208: my $captcha = Captcha::reCAPTCHA->new;
17209: my $captcha_result =
17210: $captcha->check_answer(
17211: $privkey,
17212: $ENV{'REMOTE_ADDR'},
17213: $env{'form.recaptcha_challenge_field'},
17214: $env{'form.recaptcha_response_field'},
17215: );
17216: if ($captcha_result->{is_valid}) {
17217: $captcha_chk = 1;
17218: }
17219: }
17220: return $captcha_chk;
17221: }
17222:
17223: sub emailusername_info {
17224: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17225: my %titles = &Apache::lonlocal::texthash (
17226: lastname => 'Last Name',
17227: firstname => 'First Name',
17228: institution => 'School/college/university',
17229: location => "School's city, state/province, country",
17230: web => "School's web address",
17231: officialemail => 'E-mail address at institution (if different)',
17232: id => 'Student/Employee ID',
17233: );
17234: return (\@fields,\%titles);
17235: }
17236:
17237: sub cleanup_html {
17238: my ($incoming) = @_;
17239: my $outgoing;
17240: if ($incoming ne '') {
17241: $outgoing = $incoming;
17242: $outgoing =~ s/;/;/g;
17243: $outgoing =~ s/\#/#/g;
17244: $outgoing =~ s/\&/&/g;
17245: $outgoing =~ s/</</g;
17246: $outgoing =~ s/>/>/g;
17247: $outgoing =~ s/\(/(/g;
17248: $outgoing =~ s/\)/)/g;
17249: $outgoing =~ s/"/"/g;
17250: $outgoing =~ s/'/'/g;
17251: $outgoing =~ s/\$/$/g;
17252: $outgoing =~ s{/}{/}g;
17253: $outgoing =~ s/=/=/g;
17254: $outgoing =~ s/\\/\/g
17255: }
17256: return $outgoing;
17257: }
17258:
17259: # Checks for critical messages and returns a redirect url if one exists.
17260: # $interval indicates how often to check for messages.
17261: # $context is the calling context -- roles, grades, contents, menu or flip.
17262: sub critical_redirect {
17263: my ($interval,$context) = @_;
17264: if ((time-$env{'user.criticalcheck.time'})>$interval) {
17265: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17266: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17267: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17268: my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
17269: if ($blocked) {
17270: my $checkrole = "cm./$cdom/$cnum";
17271: if ($env{'request.course.sec'} ne '') {
17272: $checkrole .= "/$env{'request.course.sec'}";
17273: }
17274: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17275: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17276: return;
17277: }
17278: }
17279: }
17280: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17281: $env{'user.name'});
17282: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17283: my $redirecturl;
17284: if ($what[0]) {
17285: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17286: $redirecturl='/adm/email?critical=display';
17287: my $url=&Apache::lonnet::absolute_url().$redirecturl;
17288: return (1, $url);
17289: }
17290: }
17291: }
17292: return ();
17293: }
17294:
17295: # Use:
17296: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17297: #
17298: ##################################################
17299: # password associated functions #
17300: ##################################################
17301: sub des_keys {
17302: # Make a new key for DES encryption.
17303: # Each key has two parts which are returned separately.
17304: # Please note: Each key must be passed through the &hex function
17305: # before it is output to the web browser. The hex versions cannot
17306: # be used to decrypt.
17307: my @hexstr=('0','1','2','3','4','5','6','7',
17308: '8','9','a','b','c','d','e','f');
17309: my $lkey='';
17310: for (0..7) {
17311: $lkey.=$hexstr[rand(15)];
17312: }
17313: my $ukey='';
17314: for (0..7) {
17315: $ukey.=$hexstr[rand(15)];
17316: }
17317: return ($lkey,$ukey);
17318: }
17319:
17320: sub des_decrypt {
17321: my ($key,$cyphertext) = @_;
17322: my $keybin=pack("H16",$key);
17323: my $cypher;
17324: if ($Crypt::DES::VERSION>=2.03) {
17325: $cypher=new Crypt::DES $keybin;
17326: } else {
17327: $cypher=new DES $keybin;
17328: }
17329: my $plaintext='';
17330: my $cypherlength = length($cyphertext);
17331: my $numchunks = int($cypherlength/32);
17332: for (my $j=0; $j<$numchunks; $j++) {
17333: my $start = $j*32;
17334: my $cypherblock = substr($cyphertext,$start,32);
17335: my $chunk =
17336: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17337: $chunk .=
17338: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17339: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17340: $plaintext .= $chunk;
17341: }
17342: return $plaintext;
17343: }
17344:
17345: sub get_requested_shorturls {
17346: my ($cdom,$cnum,$navmap) = @_;
17347: return unless (ref($navmap));
17348: my ($numnew,$errors);
17349: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
17350: if (@toshorten) {
17351: my (%maps,%resources,%titles);
17352: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
17353: 'shorturls',$cdom,$cnum);
17354: if (keys(%resources)) {
17355: my %tocreate;
17356: foreach my $item (sort {$a <=> $b} (@toshorten)) {
17357: my $symb = $resources{$item};
17358: if ($symb) {
17359: $tocreate{$cnum.'&'.$symb} = 1;
17360: }
17361: }
17362: if (keys(%tocreate)) {
17363: ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
17364: \%tocreate);
17365: }
17366: }
17367: }
17368: return ($numnew,$errors);
17369: }
17370:
17371: sub make_short_symbs {
17372: my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
17373: my ($numnew,@errors);
17374: if (ref($tocreateref) eq 'HASH') {
17375: my %tocreate = %{$tocreateref};
17376: if (keys(%tocreate)) {
17377: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
17378: my $su = Short::URL->new(no_vowels => 1);
17379: my $init = '';
17380: my (%newunique,%addcourse,%courseonly,%failed);
17381: # get lock on tiny db
17382: my $now = time;
17383: if ($lockuser eq '') {
17384: $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
17385: }
17386: my $lockhash = {
17387: "lock\0$now" => $lockuser,
17388: };
17389: my $tries = 0;
17390: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17391: my ($code,$error);
17392: while (($gotlock ne 'ok') && ($tries<3)) {
17393: $tries ++;
17394: sleep 1;
17395: $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17396: }
17397: if ($gotlock eq 'ok') {
17398: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
17399: \%addcourse,\%courseonly,\%failed);
17400: if (keys(%failed)) {
17401: my $numfailed = scalar(keys(%failed));
17402: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
17403: }
17404: if (keys(%newunique)) {
17405: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
17406: if ($putres eq 'ok') {
17407: $numnew = scalar(keys(%newunique));
17408: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
17409: unless ($newputres eq 'ok') {
17410: push(@errors,&mt('error: could not store course look-up of short URLs'));
17411: }
17412: } else {
17413: push(@errors,&mt('error: could not store unique six character URLs'));
17414: }
17415: }
17416: }
17417: }
17418: }
17419: return ($numnew,\@errors);
17420: }
17421:
17422: sub shorten_symbs {
17423: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
17424: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
17425: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
17426: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
17427: my (%possibles,%collisions);
17428: foreach my $key (keys(%{$tocreate})) {
17429: my $num = String::CRC32::crc32($key);
17430: my $tiny = $su->encode($num,$init);
17431: if ($tiny) {
17432: $possibles{$tiny} = $key;
17433: }
17434: }
17435: if (!$init) {
17436: $init = 1;
17437: } else {
17438: $init ++;
17439: }
17440: if (keys(%possibles)) {
17441: my @posstiny = keys(%possibles);
17442: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
17443: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
17444: if (keys(%currtiny)) {
17445: foreach my $key (keys(%currtiny)) {
17446: next if ($currtiny{$key} eq '');
17447: if ($currtiny{$key} eq $possibles{$key}) {
17448: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
17449: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17450: $courseonly->{$tsymb} = $key;
17451: }
17452: } else {
17453: $collisions{$possibles{$key}} = 1;
17454: }
17455: delete($possibles{$key});
17456: }
17457: }
17458: foreach my $key (keys(%possibles)) {
17459: $newunique->{$key} = $possibles{$key};
17460: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
17461: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17462: $addcourse->{$tsymb} = $key;
17463: }
17464: }
17465: }
17466: if (keys(%collisions)) {
17467: if ($init <5) {
17468: if (!$init) {
17469: $init = 1;
17470: } else {
17471: $init ++;
17472: }
17473: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
17474: $newunique,$addcourse,$courseonly,$failed);
17475: } else {
17476: foreach my $key (keys(%collisions)) {
17477: $failed->{$key} = 1;
17478: $failed->{$key} = 1;
17479: }
17480: }
17481: }
17482: return $init;
17483: }
17484:
17485: sub is_nonframeable {
17486: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17487: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17488: return if (($remprotocol eq '') || ($remhost eq ''));
17489:
17490: $remprotocol = lc($remprotocol);
17491: $remhost = lc($remhost);
17492: my $remport = 80;
17493: if ($remprotocol eq 'https') {
17494: $remport = 443;
17495: }
17496: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17497: if ($cached) {
17498: unless ($nocache) {
17499: if ($result) {
17500: return 1;
17501: } else {
17502: return 0;
17503: }
17504: }
17505: }
17506: my $uselink;
17507: my $request = new HTTP::Request('HEAD',$url);
17508: my $ua = LWP::UserAgent->new;
17509: $ua->timeout(5);
17510: my $response=$ua->request($request);
17511: if ($response->is_success()) {
17512: my $secpolicy = lc($response->header('content-security-policy'));
17513: my $xframeop = lc($response->header('x-frame-options'));
17514: $secpolicy =~ s/^\s+|\s+$//g;
17515: $xframeop =~ s/^\s+|\s+$//g;
17516: if (($secpolicy ne '') || ($xframeop ne '')) {
17517: my $remotehost = $remprotocol.'://'.$remhost;
17518: my ($origin,$protocol,$port);
17519: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
17520: $port = $ENV{'SERVER_PORT'};
17521: } else {
17522: $port = 80;
17523: }
17524: if ($absolute eq '') {
17525: $protocol = 'http:';
17526: if ($port == 443) {
17527: $protocol = 'https:';
17528: }
17529: $origin = $protocol.'//'.lc($hostname);
17530: } else {
17531: $origin = lc($absolute);
17532: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
17533: }
17534: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
17535: my $framepolicy = $1;
17536: $framepolicy =~ s/^\s+|\s+$//g;
17537: my @policies = split(/\s+/,$framepolicy);
17538: if (@policies) {
17539: if (grep(/^\Q'none'\E$/,@policies)) {
17540: $uselink = 1;
17541: } else {
17542: $uselink = 1;
17543: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
17544: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
17545: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
17546: undef($uselink);
17547: }
17548: if ($uselink) {
17549: if (grep(/^\Q'self'\E$/,@policies)) {
17550: if (($origin ne '') && ($remotehost eq $origin)) {
17551: undef($uselink);
17552: }
17553: }
17554: }
17555: if ($uselink) {
17556: my @possok;
17557: if ($ip ne '') {
17558: push(@possok,$ip);
17559: }
17560: my $hoststr = '';
17561: foreach my $part (reverse(split(/\./,$hostname))) {
17562: if ($hoststr eq '') {
17563: $hoststr = $part;
17564: } else {
17565: $hoststr = "$part.$hoststr";
17566: }
17567: if ($hoststr eq $hostname) {
17568: push(@possok,$hostname);
17569: } else {
17570: push(@possok,"*.$hoststr");
17571: }
17572: }
17573: if (@possok) {
17574: foreach my $poss (@possok) {
17575: last if (!$uselink);
17576: foreach my $policy (@policies) {
17577: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
17578: undef($uselink);
17579: last;
17580: }
17581: }
17582: }
17583: }
17584: }
17585: }
17586: }
17587: } elsif ($xframeop ne '') {
17588: $uselink = 1;
17589: my @policies = split(/\s*,\s*/,$xframeop);
17590: if (@policies) {
17591: unless (grep(/^deny$/,@policies)) {
17592: if ($origin ne '') {
17593: if (grep(/^sameorigin$/,@policies)) {
17594: if ($remotehost eq $origin) {
17595: undef($uselink);
17596: }
17597: }
17598: if ($uselink) {
17599: foreach my $policy (@policies) {
17600: if ($policy =~ /^allow-from\s*(.+)$/) {
17601: my $allowfrom = $1;
17602: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
17603: undef($uselink);
17604: last;
17605: }
17606: }
17607: }
17608: }
17609: }
17610: }
17611: }
17612: }
17613: }
17614: }
17615: if ($nocache) {
17616: if ($cached) {
17617: my $devalidate;
17618: if ($uselink && !$result) {
17619: $devalidate = 1;
17620: } elsif (!$uselink && $result) {
17621: $devalidate = 1;
17622: }
17623: if ($devalidate) {
17624: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
17625: }
17626: }
17627: } else {
17628: if ($uselink) {
17629: $result = 1;
17630: } else {
17631: $result = 0;
17632: }
17633: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
17634: }
17635: return $uselink;
17636: }
17637:
17638: 1;
17639: __END__;
17640:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>